package com.chushang.common.excel.convert;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
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 lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;

/**
 * <h1>日期格式化</h1>
 *
 * @author 单傲
 * @version 1.0
 * @Date 2023-04-19 17:57
 **/
@Slf4j
public class LocalDateTimeConvert implements Converter<LocalDateTime> {

    @Override
    public Class<LocalDateTime> supportJavaTypeKey() {
        return LocalDateTime.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return null;
    }

    /**
     * <h2>转换为java对象</h2>
     *
     * @param cellData            Excel 单元格数据
     * @param contentProperty     内容属性
     * @param globalConfiguration 全局配置
     * @return java对象
     * @author 单傲
     * @date 2023/4/19 18:09
     */
    @Override
    public LocalDateTime convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        if (cellData.getStringValue() == null) {
            return null;
        }

        return LocalDateTimeUtil.parse(cellData.getStringValue(), DatePattern.NORM_DATE_PATTERN);
    }


    /**
     * <h2>转换单元格数据</h2>
     *
     * @param value               Java 数据
     * @param contentProperty     内容属性
     * @param globalConfiguration 全局配置
     * @return excel中的数据
     * @author 单傲
     * @date 2023/4/19 18:11
     */
    @Override
    public WriteCellData<String> convertToExcelData(LocalDateTime value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        if (ObjectUtil.isEmpty(value)) {
            return new WriteCellData<>();
        }

        return new WriteCellData<>(LocalDateTimeUtil.format(value, DatePattern.CHINESE_DATE_PATTERN));
    }
}
