package org.dromara.common.excel.convert;

import cn.hutool.core.date.DateUtil;
import cn.idev.excel.converters.Converter;
import cn.idev.excel.enums.CellDataTypeEnum;
import cn.idev.excel.metadata.GlobalConfiguration;
import cn.idev.excel.metadata.data.ReadCellData;
import cn.idev.excel.metadata.data.WriteCellData;
import cn.idev.excel.metadata.property.ExcelContentProperty;

import java.util.Date;

/**
 * 日期导出为字符串(yyyy-MM-dd)转换器
 */
public class ExcelDateStringConvert implements Converter<Date> {

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

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

    @Override
    public Date convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        Object data = cellData.getData();
        if (data instanceof Date) {
            return (Date) data;
        }
        return null;
    }

    @Override
    public WriteCellData<Object> convertToExcelData(Date value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        String str = value == null ? "" : DateUtil.format(value, "yyyy-MM-dd");
        WriteCellData<Object> cellData = new WriteCellData<>(str);
        cellData.setType(CellDataTypeEnum.STRING);
        return cellData;
    }
}
