package com.ruoyi.common.convert;

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 com.alibaba.excel.util.DateUtils;
import lombok.extern.slf4j.Slf4j;

import java.text.ParseException;
import java.util.Date;

/**
 * 自定义时间格式转换器
 *
 * @author wuchao
 */
@Slf4j
public class ExcelDateConvert implements Converter<Date> {

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

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

    @Override
    public Date convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        try {
            return DateUtils.parseDate(cellData.getStringValue(), DateUtils.DATE_FORMAT_10);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public WriteCellData<String> convertToExcelData(Date object, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        return new WriteCellData<>(DateUtils.format(object, DateUtils.DATE_FORMAT_10));
    }

}
