package com.njcn.advance.event.service;

import com.njcn.advance.event.cause.jna.QvvrCauseDLL;
import com.njcn.advance.event.cause.model.DataFeature;
import com.njcn.advance.event.type.jna.QvvrDLL;
import com.njcn.advance.pojo.dto.EventAnalysisDTO;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.event.file.component.WaveFileComponent;
import com.njcn.event.file.pojo.dto.WaveDataDTO;
import com.njcn.event.file.pojo.enums.WaveFileResponseEnum;
import com.njcn.oss.constant.GeneralConstant;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.InputStream;
import java.util.List;
import java.util.Objects;

/**
 * @author hongawen
 * @version 1.0
 * @data 2025/7/30 11:24
 */
@Slf4j
public class Test {

    public static void main(String[] args) {
        WaveFileComponent waveFileComponent = new WaveFileComponent();
        EventAnalysisDTO eventAnalysis = new EventAnalysisDTO();
        WaveDataDTO waveDataDTO;
        String waveName = "11";
        String cfgPath, datPath;
        cfgPath = "D:\\comtrade\\00-B7-8D-00-FA-44" + File.separator + waveName + GeneralConstant.CFG;
        datPath = "D:\\comtrade\\00-B7-8D-00-FA-44" + File.separator + waveName + GeneralConstant.DAT;
        log.info("本地磁盘波形文件路径----" + cfgPath);
        InputStream cfgStream = waveFileComponent.getFileInputStreamByFilePath(cfgPath);
        InputStream datStream = waveFileComponent.getFileInputStreamByFilePath(datPath);
        if (Objects.isNull(cfgStream) || Objects.isNull(datStream)) {
            throw new BusinessException(WaveFileResponseEnum.ANALYSE_WAVE_NOT_FOUND);
        }
        waveDataDTO = waveFileComponent.getComtrade(cfgStream, datStream, 0);
//        // java针对暂降原因分析的调用
//        QvvrDataStruct qvvrDataStruct = new QvvrDataStruct();
//        // 采样率
//        qvvrDataStruct.setSmpRate(waveDataDTO.getComtradeCfgDTO().getFinalSampleRate());
//        // 瞬时值
//        List<List<Float>> listWaveData = waveDataDTO.getListWaveData();
//        // 通道采样个数
//        qvvrDataStruct.setSmpLen(listWaveData.size());
//        // 获取ABC三相的瞬时数据
//        // A相电压采样数据
//        float[] smpVa = new float[listWaveData.size()];
//        // B相电压采样数据
//        float[] smpVb = new float[listWaveData.size()];
//        // C相电压采样数据
//        float[] smpVc = new float[listWaveData.size()];
//        for (int i = 0; i < listWaveData.size(); i++) {
//            smpVa[i] = listWaveData.get(i).get(1);
//            smpVb[i] = listWaveData.get(i).get(2);
//            smpVc[i] = listWaveData.get(i).get(3);
//        }
//        qvvrDataStruct.setSmpVa(smpVa);
//        qvvrDataStruct.setSmpVb(smpVb);
//        qvvrDataStruct.setSmpVc(smpVc);
//
//        // 暂降原因
//        VoltageSagAnalyzer voltageSagAnalyzer = new VoltageSagAnalyzer();
//        try{
//            AnalysisResult cause = voltageSagAnalyzer.analyzeVoltageSagWithDetails(qvvrDataStruct);
//            eventAnalysis.setCause(cause.getCause());
//        }catch (Exception e){
//            log.error("DAT文件分析异常", e);
//            eventAnalysis.setCause(DataFeature.CAUSE_TYPE0);
//            eventAnalysis.setCauseFlag(0);
//        }


        List<List<Float>> listWaveData = waveDataDTO.getListWaveData();

        // 暂降原因JNA的方式
        com.njcn.advance.event.cause.jna.QvvrCauseDLL.QvvrDataStruct causeDataStruct = new com.njcn.advance.event.cause.jna.QvvrCauseDLL.QvvrDataStruct();
        causeDataStruct.smp_rate = waveDataDTO.getComtradeCfgDTO().getFinalSampleRate();
        causeDataStruct.smp_len = listWaveData.size();
        // 获取ABC三相的瞬时数据
        for (int i = 0; i < listWaveData.size(); i++) {
            causeDataStruct.smp_va[i] = listWaveData.get(i).get(1);
            causeDataStruct.smp_vb[i] = listWaveData.get(i).get(2);
            causeDataStruct.smp_vc[i] = listWaveData.get(i).get(3);
        }
        // 执行算法分析 - 直接调用C DLL
        try {
            QvvrCauseDLL.INSTANCE.qvvr_fun_cause(causeDataStruct);
            System.out.println("暂降原因: " + getCauseDescription(causeDataStruct.cause));
        } catch (Exception e) {
            System.err.println("调用DLL失败: " + e.getMessage());
            e.printStackTrace();
        }

        // 暂降类型JNA的方式
        // 创建数据结构
        com.njcn.advance.event.type.jna.QvvrDLL.QvvrDataStruct typeDataStruct = new com.njcn.advance.event.type.jna.QvvrDLL.QvvrDataStruct();
        typeDataStruct.smp_rate = waveDataDTO.getComtradeCfgDTO().getFinalSampleRate();
        typeDataStruct.smp_len = listWaveData.size();
        // 获取ABC三相的瞬时数据
        for (int i = 0; i < listWaveData.size(); i++) {
            typeDataStruct.smp_va[i] = listWaveData.get(i).get(1);
            typeDataStruct.smp_vb[i] = listWaveData.get(i).get(2);
            typeDataStruct.smp_vc[i] = listWaveData.get(i).get(3);
        }
        // 执行算法分析 - 直接调用C DLL
        try {
            QvvrDLL.INSTANCE.qvvr_fun(typeDataStruct);
            if (typeDataStruct.evt_num > 0) {
                // 显示结果
                System.out.println("检测到事件数: " + typeDataStruct.evt_num);
                // 全局比较找出最小三相电压特征值
                float globalMinVoltage = Float.MAX_VALUE;
                int globalFaultType = -1;
                for (int i = 0; i < typeDataStruct.evt_num; i++) {
                    QvvrDLL.EventBuffer evt = typeDataStruct.evt_buf[i];
                    for (int j = 0; j < evt.u_min_num; j++) {
                        float u3min = evt.u3_min[j];
                        if (u3min < globalMinVoltage) {
                            globalMinVoltage = u3min;
                            globalFaultType = evt.qvvr_cata_type[j];
                        }
                    }
                }
                System.out.println("=== 全局比较结果 ===");
                System.out.println("全局最小三相电压: " + String.format("%.3f", globalMinVoltage) + "V");
                System.out.println("最终暂降类型: " + globalFaultType + " (" + getFaultTypeDescription(globalFaultType) + ")");
            } else {
                System.out.println("结果: 未检测到电压暂降事件");
            }

        } catch (Exception e) {
            System.err.println("调用DLL失败: " + e.getMessage());
            e.printStackTrace();
        }
    }


    /**
     * 获取原因描述
     */
    private static String getCauseDescription(int cause) {
        switch (cause) {
            case DataFeature.CAUSE_TYPE0:
                return "未知原因";
            case DataFeature.CAUSE_TYPE1:
                return "短路故障";
            case DataFeature.CAUSE_TYPE2:
                return "电压调节器";
            case DataFeature.CAUSE_TYPE3:
                return "感应电机启动";
            case DataFeature.CAUSE_TYPE4:
                return "电压跌落";
            default:
                return "未定义原因";
        }
    }

    /**
     * 相数类型描述
     */
    public static String getPhaseTypeDescription(int phaseType) {
        switch (phaseType) {
            case 1:
                return "单相";
            case 2:
                return "两相";
            case 3:
                return "三相";
            default:
                return "未知相数(" + phaseType + ")";
        }
    }

    /**
     * 故障类型描述
     */
    public static String getFaultTypeDescription(int faultType) {
        switch (faultType) {
            case 0:
                return "BC相间故障";
            case 1:
                return "C相接地故障";
            case 2:
                return "AC相间故障";
            case 3:
                return "A相接地故障";
            case 4:
                return "AB相间故障";
            case 5:
                return "B相接地故障";
            case 6:
                return "BC相间接地";
            case 7:
                return "AC相间接地";
            case 8:
                return "AB相间接地";
            case 9:
                return "三相故障";
            case 10:
                return "未知";
            default:
                return "未知类型(" + faultType + ")";
        }
    }
}
