package cn.iocoder.yudao.module.mes.controller.admin.deviceledger.vo;

import cn.iocoder.yudao.module.mes.controller.admin.deviceledger.enums.DeviceLedgerStatusEnum;
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 org.springframework.stereotype.Component;

/**
 * 设备状态转换器
 */
@Component
public class DeviceStatusConverter implements Converter<Integer> {

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

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

    /**
     * 读取Excel时调用（从Excel到Java对象）
     */
    @Override
    public Integer convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
                                     GlobalConfiguration globalConfiguration) {
        String cellValue = cellData.getStringValue();
        if (cellValue == null || cellValue.trim().isEmpty()) {
            return null;
        }

        // 将中文状态转换为数字
        for (DeviceLedgerStatusEnum status : DeviceLedgerStatusEnum.values()) {
            if (status.getDescription().equals(cellValue)) {
                return status.getCode();
            }
        }

        // 如果中文没匹配到，尝试直接解析数字
        try {
            return Integer.parseInt(cellValue);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("设备状态格式错误: " + cellValue);
        }
    }

    /**
     * 写入Excel时调用（从Java对象到Excel）
     */
    @Override
    public WriteCellData<?> convertToExcelData(Integer value, ExcelContentProperty contentProperty,
                                               GlobalConfiguration globalConfiguration) {
        if (value == null) {
            return new WriteCellData<>("");
        }

        DeviceLedgerStatusEnum status = DeviceLedgerStatusEnum.getByCode(value);
        String text = status != null ? status.getDescription() : "未知";
        return new WriteCellData<>(text);
    }
}