package com.ruoyi.common.convert;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.util.ObjectUtil;
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.ruoyi.common.annotation.ExcelDictFormat;
import com.ruoyi.common.enums.IIntegerEnum;
import com.ruoyi.common.enums.serializer.EnumConvertFactory;
import com.ruoyi.common.utils.poi.ExcelUtil;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;

/**
 * 枚举转换
 *
 *
 * @author Lion Li
 */
@Slf4j
public class ExcelEnumConvert implements Converter<IIntegerEnum> {

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

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

    @Override
    public IIntegerEnum convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        ExcelDictFormat anno = getAnnotation(contentProperty.getField());
        Class<?> type = contentProperty.getField().getType();
        String label = cellData.getStringValue();
        String value = ExcelUtil.reverseByExp(label, anno.readConverterExp(), anno.separator());
        return EnumConvertFactory.getEnum((Class) type,Integer.valueOf(value));
    }


    @Override
    public WriteCellData<Object> convertToExcelData(IIntegerEnum object, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        if (ObjectUtil.isNull(object)) {
            return new WriteCellData<>("");
        }

        return new WriteCellData<>(object.getMsg());
    }

    private ExcelDictFormat getAnnotation(Field field) {
        return AnnotationUtil.getAnnotation(field, ExcelDictFormat.class);
    }

}
