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.exception.ServiceException;
import com.ximai.common.utils.MessageUtils;
import io.swagger.annotations.ApiModel;

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: StaticDataMappingConverter</p>
 * <p>Description: 静态数据内容转换</p>
 *
 * @author chicheng.li
 * @version V1.0
 */
public class StaticDataMappingConverter 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<StaticDataMappingFormat> conf = Optional.ofNullable(contentProperty.getField().getAnnotation(StaticDataMappingFormat.class));
        if(!conf.isPresent()){
            throw new ServiceException(MessageUtils.message("basic.excel.error.not.null.StaticDataMappingFormat"));
        }
        if (cellData.getType().equals(CellDataTypeEnum.STRING)){
            String dateStr = cellData.getStringValue();
            int i=0;
            for(String s : conf.get().excelValue()){
                if(s.equals(dateStr)){
                    break;
                }
                i++;
            }
            return conf.get().value()[i];
        }
        return null;
    }

    @Override
    public WriteCellData<?> convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        Optional<StaticDataMappingFormat> conf = Optional.ofNullable(contentProperty.getField().getAnnotation(StaticDataMappingFormat.class));
        if(!conf.isPresent()){
            throw new ServiceException(MessageUtils.message("basic.excel.error.not.null.StaticDataMappingFormat"));
        }
        int i=0;
        for(String s : conf.get().value()){
            if(s.equals(value)){
                break;
            }
            i++;
        }
        return new WriteCellData(conf.get().excelValue()[i]);
    }
}