package com.cf.imes.framework.excel.core.convert;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.cf.imes.framework.excel.core.annotations.EnumFormat;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;

/**
 * Excel 枚举转换器
 *
 * @author Gqr
 * @since 2025/8/27 11:02
 */
@Slf4j
public class EnumConvert implements Converter<Integer> {
    @Override
    public Class<?> supportJavaTypeKey() {
        return Integer.class; // 泛型接口
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING; // Excel 存字符串
    }

    // 写出：Integer -> 枚举描述
    @Override
    public WriteCellData<String> convertToExcelData(WriteConverterContext<Integer> context) {
        Integer code = context.getValue();
        if (code == null) {
            return new WriteCellData<>("");
        }
        Class<? extends Enum> enumClass = getEnumClass(context.getContentProperty().getField());
        if (enumClass != null) {
            for (Object e : enumClass.getEnumConstants()) {
                BaseEnum baseEnum = (BaseEnum) e;
                if (baseEnum.getCode().equals(code)) {
                    return new WriteCellData<>(baseEnum.getDesc());
                }
            }
        }
        return new WriteCellData<>("");
    }

    // 读入：枚举描述 -> Integer code
    @Override
    public Integer convertToJavaData(ReadConverterContext<?> context) {
        String desc = context.getReadCellData().getStringValue();
        if (desc == null) {
            return null;
        }
        Class<? extends Enum> enumClass = getEnumClass(context.getContentProperty().getField());
        if (enumClass != null) {
            for (Object e : enumClass.getEnumConstants()) {
                BaseEnum baseEnum = (BaseEnum) e;
                if (baseEnum.getDesc().equals(desc)) {
                    return baseEnum.getCode();
                }
            }
        }
        return null;
    }

    private Class<? extends Enum> getEnumClass(Field field) {
        EnumFormat annotation = field.getAnnotation(EnumFormat.class);
        return annotation != null ? annotation.value() : null;
    }
}
