package com.ruoyi.info.collection.utils.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 java.util.HashMap;
import java.util.Map;

/**
 * 中介类型转换器
 * 1=个人, 2=机构
 *
 * @author ruoyi
 */
public class IntermediaryTypeConverter implements Converter<String> {

    private static final Map<String, String> CODE_TO_DESC = new HashMap<>();
    private static final Map<String, String> DESC_TO_CODE = new HashMap<>();

    static {
        CODE_TO_DESC.put("1", "个人");
        CODE_TO_DESC.put("2", "机构");
        DESC_TO_CODE.put("个人", "1");
        DESC_TO_CODE.put("机构", "2");
    }

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

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

    @Override
    public String convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
                                     GlobalConfiguration globalConfiguration) {
        String value = cellData.getStringValue();
        if (value == null) {
            return null;
        }
        // 支持中文和代码两种格式
        if (DESC_TO_CODE.containsKey(value)) {
            return DESC_TO_CODE.get(value);
        }
        // 如果是纯数字，直接返回
        if (value.matches("\\d")) {
            return value;
        }
        throw new IllegalArgumentException("无效的中介类型: " + value + ", 请使用: 个人/机构 或 1/2");
    }

    @Override
    public WriteCellData<?> convertToExcelData(String value, ExcelContentProperty contentProperty,
                                                 GlobalConfiguration globalConfiguration) {
        String desc = CODE_TO_DESC.getOrDefault(value, value);
        return new WriteCellData<>(desc);
    }
}
