package com.bonus.canteen.core.common.utils;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class CustomLocalDateConverter implements Converter<LocalDate> {
   @Override
   public Class supportJavaTypeKey() {
      return LocalDate.class;
   }

   @Override
   public CellDataTypeEnum supportExcelTypeKey() {
      return CellDataTypeEnum.STRING;
   }

   @Override
   public LocalDate convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
      return LocalDate.parse(cellData.getStringValue(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
   }

   @Override
   public WriteCellData<Integer> convertToExcelData(LocalDate localDateTime, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
      String format = "";
      if (ObjectUtil.isNotNull(localDateTime)) {
         DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
         format = formatter.format(localDateTime);
      }

      return new WriteCellData(format);
   }
}
