package com.bonus.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.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class CustomLocalDateTimeConverter implements Converter<LocalDateTime> {
   public Class supportJavaTypeKey() {
      return LocalDate.class;
   }

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

   public LocalDateTime convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
      return LocalDateTime.parse(cellData.getStringValue(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
   }

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

      return new WriteCellData(format);
   }
}
