package com.njcn.gather.tool.wave.component;

import com.njcn.gather.tool.wave.pojo.dto.EigenvalueDTO;
import com.njcn.gather.tool.wave.pojo.dto.WaveCycleVectorDTO;
import com.njcn.gather.tool.wave.pojo.dto.WaveHarmonicDTO;
import com.njcn.gather.tool.wave.pojo.dto.WavePhaseVectorDTO;
import com.njcn.gather.tool.wave.pojo.dto.WaveVectorGroupDTO;
import com.njcn.gather.tool.wave.pojo.dto.WaveDataDTO;
import com.njcn.gather.tool.wave.pojo.param.WaveComtradeParseParam;
import com.njcn.gather.tool.wave.pojo.vo.WaveComtradeVectorResultVO;

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * 本地调试 getComtrade 的命令行入口。
 */
public final class WaveFileComponentTestMain {

    /** 默认测试 CFG 文件路径。 */
    private static final String DEFAULT_CFG_PATH = "D:\\00-B7-8D-00-E4-09\\PQMonitor_PQM2_006970_20260320_175033_734.CFG";
    /** 默认测试 DAT 文件路径。 */
    private static final String DEFAULT_DAT_PATH = "D:\\00-B7-8D-00-E4-09\\PQMonitor_PQM2_006970_20260320_175033_734.DAT";
    /** 默认解析类型，1 表示普通展示。 */
    private static final int DEFAULT_PARSE_TYPE = 1;
    /** 向量调试固定使用原始波形。 */
    private static final int VECTOR_PARSE_TYPE = 3;
    /** 默认使用浮动门槛计算特征值。 */
    private static final boolean DEFAULT_DYNAMIC_THRESHOLD = true;

    private WaveFileComponentTestMain() {
    }

    /**
     * 用法：
     * java com.njcn.gather.tool.wave.component.WaveFileComponentTestMain <cfgPath> <datPath> [parseType]
     */
    public static void main(String[] args) throws Exception {
        if (args.length < 2) {
            System.out.println("未传入参数，使用默认测试文件路径");
            System.out.println("cfgPath: " + DEFAULT_CFG_PATH);
            System.out.println("datPath: " + DEFAULT_DAT_PATH);
        }

        Path cfgPath = Paths.get(args.length > 0 ? args[0] : DEFAULT_CFG_PATH);
        Path datPath = Paths.get(args.length > 1 ? args[1] : DEFAULT_DAT_PATH);
        int parseType = args.length > 2 ? Integer.parseInt(args[2]) : DEFAULT_PARSE_TYPE;

        WaveFileComponent waveFileComponent = new WaveFileComponent();
        try (InputStream cfgStream = Files.newInputStream(cfgPath);
             InputStream datStream = Files.newInputStream(datPath)) {
            WaveDataDTO waveDataDTO = waveFileComponent.getComtrade(cfgStream, datStream, parseType);
            printComtradeResult(waveDataDTO);

            WaveDataDTO validWaveDataDTO = waveFileComponent.getValidData(waveDataDTO);
            printValidDataResult(validWaveDataDTO);

            List<EigenvalueDTO> eigenvalues = waveFileComponent.getEigenvalue(validWaveDataDTO, DEFAULT_DYNAMIC_THRESHOLD);
            printEigenvalueResult(eigenvalues);
        }

        runParseComtradeVectorTest(cfgPath, datPath);
    }

    /**
     * 调试 parseComtradeVector 逻辑。
     */
    private static void runParseComtradeVectorTest(Path cfgPath, Path datPath) throws Exception {
        System.out.println("=== parseComtradeVector 结果 ===");
        WaveFileComponent waveFileComponent = new WaveFileComponent();
        WaveVectorComponent waveVectorComponent = new WaveVectorComponent();
        WaveComtradeParseParam param = new WaveComtradeParseParam();
        param.setParseType(VECTOR_PARSE_TYPE);
        param.setPtType(0);
        param.setPt(1D);
        param.setCt(1D);
        param.setMonitorName("main方法调试测点");

        try (InputStream cfgStream = Files.newInputStream(cfgPath);
             InputStream datStream = Files.newInputStream(datPath)) {
            WaveDataDTO waveDataDTO = waveFileComponent.getComtrade(cfgStream, datStream, VECTOR_PARSE_TYPE);
            applyWaveMetadata(waveDataDTO, param);

            List<WaveVectorGroupDTO> vectorGroups = waveVectorComponent.calculateVectors(waveDataDTO);
            WaveComtradeVectorResultVO result = new WaveComtradeVectorResultVO();
            result.setMonitorName(waveDataDTO.getMonitorName());
            result.setTime(waveDataDTO.getTime());
            result.setSamplePerCycle(waveDataDTO.getComtradeCfgDTO() == null ? null : waveDataDTO.getComtradeCfgDTO().getFinalSampleRate());
            result.setCycleCount(resolveCycleCount(vectorGroups));
            result.setVectorGroups(vectorGroups);
            printParseComtradeVectorResult(result);
        }
    }

    /**
     * 给向量调试结果补齐 PT/CT/测点信息。
     */
    private static void applyWaveMetadata(WaveDataDTO waveDataDTO, WaveComtradeParseParam param) {
        waveDataDTO.setPt(param.getPt() == null || param.getPt() <= 0 ? 1D : param.getPt());
        waveDataDTO.setCt(param.getCt() == null || param.getCt() <= 0 ? 1D : param.getCt());
        waveDataDTO.setPtType(param.getPtType() == null ? 0 : param.getPtType());
        waveDataDTO.setMonitorName(param.getMonitorName() == null || param.getMonitorName().trim().isEmpty()
                ? "未命名测点"
                : param.getMonitorName().trim());
    }

    /**
     * 打印 parseComtradeVector 的关键摘要。
     */
    private static void printParseComtradeVectorResult(WaveComtradeVectorResultVO result) {
        System.out.println("测点名称: " + result.getMonitorName());
        System.out.println("事件时间: " + result.getTime());
        System.out.println("每周波采样点数: " + result.getSamplePerCycle());
        System.out.println("可计算周波数: " + result.getCycleCount());
        System.out.println("分组数量: " + sizeOf(result.getVectorGroups()));
        if (result.getVectorGroups() == null || result.getVectorGroups().isEmpty()) {
            return;
        }

        for (WaveVectorGroupDTO group : result.getVectorGroups()) {
            System.out.println("-- 分组: channelName=" + group.getChannelName()
                    + ", unit=" + group.getUnit()
                    + ", phaseCount=" + group.getPhaseCount()
                    + ", phaseNames=" + group.getPhaseNames());
            if (group.getVectorSeries() == null || group.getVectorSeries().isEmpty()) {
                continue;
            }
            WaveCycleVectorDTO firstCycle = group.getVectorSeries().get(0);
            System.out.println("   首周波: cycleIndex=" + firstCycle.getCycleIndex() + ", time=" + firstCycle.getTime());
            printPhaseVectorSummary(firstCycle.getPhaseVectors());
            if (firstCycle.getPositiveSequence() != null) {
                System.out.println("   正序: amplitude=" + firstCycle.getPositiveSequence().getAmplitude()
                        + ", rms=" + firstCycle.getPositiveSequence().getRms()
                        + ", phaseAngle=" + firstCycle.getPositiveSequence().getPhaseAngle());
            }
            if (firstCycle.getNegativeSequence() != null) {
                System.out.println("   负序: amplitude=" + firstCycle.getNegativeSequence().getAmplitude()
                        + ", rms=" + firstCycle.getNegativeSequence().getRms()
                        + ", phaseAngle=" + firstCycle.getNegativeSequence().getPhaseAngle());
            }
            if (firstCycle.getZeroSequence() != null) {
                System.out.println("   零序: amplitude=" + firstCycle.getZeroSequence().getAmplitude()
                        + ", rms=" + firstCycle.getZeroSequence().getRms()
                        + ", phaseAngle=" + firstCycle.getZeroSequence().getPhaseAngle());
            }
            if (firstCycle.getUnbalance() != null) {
                System.out.println("   不平衡度: negative=" + firstCycle.getUnbalance().getNegativeUnbalanceRate()
                        + ", zero=" + firstCycle.getUnbalance().getZeroUnbalanceRate());
            }
        }
    }

    /**
     * 打印单相电能质量结果摘要。
     */
    private static void printPhaseVectorSummary(List<WavePhaseVectorDTO> phaseVectors) {
        if (phaseVectors == null || phaseVectors.isEmpty()) {
            return;
        }
        for (WavePhaseVectorDTO phaseVector : phaseVectors) {
            System.out.println("   相别=" + phaseVector.getPhaseName()
                    + ", totalRms=" + phaseVector.getTotalRms()
                    + ", fundamentalAmplitude=" + phaseVector.getFundamentalAmplitude()
                    + ", fundamentalRms=" + phaseVector.getFundamentalRms()
                    + ", fundamentalPhaseAngle=" + phaseVector.getFundamentalPhaseAngle()
                    + ", harmonicDistortionRate=" + phaseVector.getHarmonicDistortionRate());
            printHarmonicSummary("电压谐波", phaseVector.getHarmonicVoltageContentRates());
            printHarmonicSummary("电流谐波", phaseVector.getHarmonicCurrentAmplitudes());
        }
    }

    /**
     * 打印前几个谐波结果，避免控制台过长。
     */
    private static void printHarmonicSummary(String label, List<WaveHarmonicDTO> harmonics) {
        if (harmonics == null || harmonics.isEmpty()) {
            return;
        }
        int limit = Math.min(3, harmonics.size());
        for (int i = 0; i < limit; i++) {
            WaveHarmonicDTO harmonic = harmonics.get(i);
            System.out.println("      " + label + "-第" + harmonic.getHarmonicOrder() + "次: amplitude=" + harmonic.getAmplitude()
                    + ", rms=" + harmonic.getRms()
                    + ", rate=" + harmonic.getRate());
        }
    }

    /**
     * 解析向量结果中的可计算周波数。
     */
    private static Integer resolveCycleCount(List<WaveVectorGroupDTO> vectorGroups) {
        if (vectorGroups == null || vectorGroups.isEmpty() || vectorGroups.get(0).getVectorSeries() == null) {
            return 0;
        }
        return vectorGroups.get(0).getVectorSeries().size();
    }

    /**
     * 打印 getComtrade 的关键摘要，便于快速人工核对。
     */
    private static void printComtradeResult(WaveDataDTO waveDataDTO) {
        System.out.println("=== getComtrade 结果 ===");
        System.out.println("事件时间: " + waveDataDTO.getTime());
        System.out.println("相别数: " + waveDataDTO.getIPhasic());
        System.out.println("标题数: " + sizeOf(waveDataDTO.getWaveTitle()));
        System.out.println("通道数: " + sizeOf(waveDataDTO.getChannelNames()));
        System.out.println("波形点数: " + sizeOf(waveDataDTO.getListWaveData()));
        if (waveDataDTO.getComtradeCfgDTO() != null) {
            System.out.println("模拟量通道数: " + waveDataDTO.getComtradeCfgDTO().getNAnalogNum());
            System.out.println("开关量通道数: " + waveDataDTO.getComtradeCfgDTO().getNDigitalNum());
            System.out.println("最终采样率: " + waveDataDTO.getComtradeCfgDTO().getFinalSampleRate());
        }
        if (waveDataDTO.getWaveTitle() != null && !waveDataDTO.getWaveTitle().isEmpty()) {
            System.out.println("波形标题: " + waveDataDTO.getWaveTitle());
        }
        if (waveDataDTO.getListWaveData() != null && !waveDataDTO.getListWaveData().isEmpty()) {
            System.out.println("首行数据: " + waveDataDTO.getListWaveData().get(0));
            System.out.println("末行数据: " + waveDataDTO.getListWaveData().get(waveDataDTO.getListWaveData().size() - 1));
        }
    }

    /**
     * 打印 getValidData 的关键摘要。
     */
    private static void printValidDataResult(WaveDataDTO waveDataDTO) {
        System.out.println("=== getValidData 结果 ===");
        System.out.println("RMS 点数: " + sizeOf(waveDataDTO.getListRmsData()));
        System.out.println("RMS 最小值点数: " + sizeOf(waveDataDTO.getListRmsMinData()));
        if (waveDataDTO.getListRmsData() != null && !waveDataDTO.getListRmsData().isEmpty()) {
            System.out.println("RMS 首行数据: " + waveDataDTO.getListRmsData().get(0));
            System.out.println("RMS 末行数据: " + waveDataDTO.getListRmsData().get(waveDataDTO.getListRmsData().size() - 1));
        }
        if (waveDataDTO.getListRmsMinData() != null && !waveDataDTO.getListRmsMinData().isEmpty()) {
            System.out.println("RMS 最小值数据: " + waveDataDTO.getListRmsMinData());
        }
    }

    /**
     * 打印特征值结果摘要。
     */
    private static void printEigenvalueResult(List<EigenvalueDTO> eigenvalues) {
        System.out.println("=== getEigenvalue 结果 ===");
        System.out.println("特征值数量: " + sizeOf(eigenvalues));
        if (eigenvalues == null || eigenvalues.isEmpty()) {
            return;
        }
        for (int i = 0; i < eigenvalues.size(); i++) {
            EigenvalueDTO eigenvalueDTO = eigenvalues.get(i);
            System.out.println("第" + (i + 1) + "相: amplitude=" + eigenvalueDTO.getAmplitude()
                    + ", residualVoltage=" + eigenvalueDTO.getResidualVoltage()
                    + ", ratedVoltage=" + eigenvalueDTO.getRatedVoltage()
                    + ", durationTime=" + eigenvalueDTO.getDurationTime());
        }
    }

    /**
     * 安全返回列表大小，避免空指针。
     */
    private static int sizeOf(List<?> list) {
        return list == null ? 0 : list.size();
    }
}
