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

import cn.hutool.core.date.DateUtil;
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.core.domain.entity.SysDictData;
import com.ximai.common.exception.ServiceException;
import com.ximai.common.utils.DictUtils;
import com.ximai.common.utils.MessageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>Title: DictionaryConverter</p>
 * <p>Description: 字典转换</p>
 *
 * @author chicheng.li
 * @version V1.0
 */
@Component
public class DictionaryConverter implements Converter<String> {

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

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

    @Override
    public String convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        Optional<DictionaryFormat> conf = Optional.ofNullable(contentProperty.getField().getAnnotation(DictionaryFormat.class));
        if(!conf.isPresent()){
            throw new ServiceException(MessageUtils.message("basic.excel.error.not.null.DictionaryFormat"));
        }
        if (cellData.getType().equals(CellDataTypeEnum.STRING)){
            String dateStr = cellData.getStringValue();
            return DictUtils.getDictValue(conf.get().dictType(), dateStr);
        }else {
            return null;
        }
    }

    @Override
    public WriteCellData<?> convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        Optional<DictionaryFormat> conf = Optional.ofNullable(contentProperty.getField().getAnnotation(DictionaryFormat.class));
        if(!conf.isPresent()){
            throw new ServiceException(MessageUtils.message("basic.excel.error.not.null.DictionaryFormat"));
        }
        return new WriteCellData(DictUtils.getDictLabel(conf.get().dictType(), value));
    }
}