package com.ximai.common.utils.excel.converter;

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.ximai.common.exception.ServiceException;
import io.netty.util.internal.StringUtil;

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

/**
 * <p>Title: LocalDateConverter</p>
 * <p>Description: 日期转换</p>
 *
 * @author xi.feng
 * @version V1.0
 */
public class LocalDateConverter implements Converter<LocalDate> {
    private static final String PATTERN = "yyyy-MM-dd";

    private static final String PATTERN1 = "yyyy.M.d";

    private static final String PATTERN2 = "yyyy/M/d";

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

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

    @Override
    public LocalDate convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {

        if (StringUtil.isNullOrEmpty(cellData.getStringValue())) {
            return null;
        }

        try {
            return LocalDate.parse(cellData.getStringValue(), DateTimeFormatter.ofPattern(PATTERN));
        } catch (Exception exception) {
        }
        try {
            return LocalDate.parse(cellData.getStringValue(), DateTimeFormatter.ofPattern(PATTERN1));
        } catch (Exception exception) {
        }
        try {
            return LocalDate.parse(cellData.getStringValue(), DateTimeFormatter.ofPattern(PATTERN2));
        } catch (Exception exception) {
        }

        throw new ServiceException("不能解析的日期格式");
    }

    @Override
    public WriteCellData<?> convertToExcelData(LocalDate value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        return new WriteCellData(value.format(DateTimeFormatter.ofPattern(PATTERN)));
    }
}
