package com.multictrl.common.utils;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.multictrl.modules.business.dto.error.DJICloudErrorCode;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * DJI错误码
 *
 * @author Sdy
 * @since 1.0.0 2026/4/24
 */
@Slf4j
@Component
public class DJIErrorCodeUtils {
    public static Map<String, DJICloudErrorCode> ERROR_CODE_INFO = new HashMap<>();

    @PostConstruct
    private void init() {
        try (InputStream inputStream = this.getClass().getClassLoader()
                .getResourceAsStream("dji/dji_cloud_api_error_code.csv")) {
            EasyExcel.read(inputStream, DJICloudErrorCode.class,
                    new AnalysisEventListener<DJICloudErrorCode>() {
                        @Override
                        public void invoke(DJICloudErrorCode djiCloudErrorCode,
                                           AnalysisContext analysisContext) {
                            if (StrUtil.isEmpty(djiCloudErrorCode.getCode())) {
                                return;
                            }
                            ERROR_CODE_INFO.put(djiCloudErrorCode.getCode().trim(), djiCloudErrorCode);
                        }
                        @Override
                        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                            //log.info("dji_cloud_api_error_code--->{}", ERROR_CODE_INFO);
                        }
                    }).excelType(ExcelTypeEnum.CSV).sheet().doRead();
            log.info("大疆 dji_cloud_api_error_code.csv 初始化成功,长度：{}", ERROR_CODE_INFO.size());
            //log.info("dji_cloud_api_error_code.csv 错误码：{}", ERROR_CODE_INFO);
        } catch (Exception e) {
            log.error("dji_cloud_api_error_code.csv 初始化失败", e);
        }
    }

    /**
     * 获取错误码信息
     */
    public static DJICloudErrorCode getErrorMsg(String errorCode) {
        if (ERROR_CODE_INFO.containsKey(errorCode)) {
            return ERROR_CODE_INFO.get(errorCode);
        }
        return null;
    }
}
