package com.njcn;

import com.njcn.gather.tools.comtrade.comparewave.core.model.CompareWaveDTO;
import com.njcn.gather.tools.comtrade.comparewave.service.ICompareWaveService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;


/**
 * 流式文件分析测试
 * 测试从本地文件读取并转换为流进行分析
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = com.njcn.gather.EntranceApplication.class)
public class AnalysisServiceStreamTest {

    @Autowired
    private ICompareWaveService compareWaveServiceImpl;

    // 测试文件路径 - 请根据实际情况修改
    private static final String SOURCE_CFG_PATH = "C:\\Users\\Administrator\\Desktop\\wavedata\\192.168.1.200\\PQ_PQLD1_000020_20251017_140358_193.cfg";
    private static final String SOURCE_DAT_PATH = "C:\\Users\\Administrator\\Desktop\\wavedata\\192.168.1.200\\PQ_PQLD1_000020_20251017_140358_193.dat";
    private static final String TARGET_CFG_PATH = "C:\\Users\\Administrator\\Desktop\\wavedata\\192.168.1.168\\PQ_PQLD1_000018_20251017_140357_625.cfg";
    private static final String TARGET_DAT_PATH = "C:\\Users\\Administrator\\Desktop\\wavedata\\192.168.1.168\\PQ_PQLD1_000018_20251017_140357_625.dat";


//    private static final String SOURCE_CFG_PATH = "F:\\hatch\\wavecompare\\数据比对\\统计数据1\\B码\\217\\PQMonitor_PQM1_000006_20200430_115517_889.cfg";
//    private static final String SOURCE_DAT_PATH = "F:\\hatch\\wavecompare\\数据比对\\统计数据1\\B码\\217\\PQMonitor_PQM1_000006_20200430_115517_889.dat";
//    private static final String TARGET_CFG_PATH = "F:\\hatch\\wavecompare\\数据比对\\统计数据1\\B码\\216\\PQMonitor_PQM1_000006_20200430_115515_479.cfg";
//    private static final String TARGET_DAT_PATH = "F:\\hatch\\wavecompare\\数据比对\\统计数据1\\B码\\216\\PQMonitor_PQM1_000006_20200430_115515_479.dat";

    // 输出路径
    private static final String OUTPUT_PATH = "./test-output/";

    /**
     * 测试使用文件流进行电能质量分析
     */
    @Test
    public void testAnalyzeWithStreams() throws Exception {
        System.out.println("========================================");
        System.out.println("开始测试流式文件分析");
        System.out.println("========================================");

        // 验证文件是否存在
        checkFileExists(SOURCE_CFG_PATH, "源CFG文件");
        checkFileExists(SOURCE_DAT_PATH, "源DAT文件");
        checkFileExists(TARGET_CFG_PATH, "目标CFG文件");
        checkFileExists(TARGET_DAT_PATH, "目标DAT文件");

        // 读取本地文件并创建输入流
        try (InputStream sourceCfgStream = new FileInputStream(SOURCE_CFG_PATH);
             InputStream sourceDatStream = new FileInputStream(SOURCE_DAT_PATH);
             InputStream targetCfgStream = new FileInputStream(TARGET_CFG_PATH);
             InputStream targetDatStream = new FileInputStream(TARGET_DAT_PATH)) {

            System.out.println("成功创建文件输入流");
            System.out.println("源CFG文件: " + SOURCE_CFG_PATH);
            System.out.println("源DAT文件: " + SOURCE_DAT_PATH);
            System.out.println("目标CFG文件: " + TARGET_CFG_PATH);
            System.out.println("目标DAT文件: " + TARGET_DAT_PATH);
            System.out.println("输出路径: " + OUTPUT_PATH);

            // 创建输出目录
            File outputDir = new File(OUTPUT_PATH);
            if (!outputDir.exists()) {
                outputDir.mkdirs();
                System.out.println("创建输出目录: " + outputDir.getAbsolutePath());
            }

            // 执行分析，使用星型接线方式（0）
            System.out.println("\n开始执行电能质量分析（星型接线）...");
            long startTime = System.currentTimeMillis();

            CompareWaveDTO result = compareWaveServiceImpl.analyzeAndCompareWithStreams(
                    sourceCfgStream,
                    sourceDatStream,
                    targetCfgStream,
                    targetDatStream,
                    // 接线方式: 0=星型接线, 1=V型接线
                    0
            );

            long endTime = System.currentTimeMillis();
            long duration = endTime - startTime;

            // 输出分析结果
            System.out.println("========================================");
            System.out.println("分析完成！");
            System.out.println("总耗时: " + duration + " ms (" + String.format("%.2f", duration / 1000.0) + " 秒)");
            


            
            System.out.println("========================================");
            System.out.println("流式文件分析测试完成！");
            System.out.println("========================================");

        }
    }

    /**
     * 测试段信息保留模式的波形分析（新方法）
     * <p>不进行跨段的统一降采样，保留每个段的原始采样率（超过512才降到256）</p>
     * <p>跨段的窗口会被丢弃，只计算不跨段的窗口</p>
     */
    @Test
    public void testAnalyzeWithSegmentPreservation() throws Exception {
        System.out.println("========================================");
        System.out.println("开始执行电能质量分析（段信息保留模式）...");
        System.out.println("========================================");

        // 检查文件是否存在
        checkFileExists(SOURCE_CFG_PATH, "源CFG文件");
        checkFileExists(SOURCE_DAT_PATH, "源DAT文件");
        checkFileExists(TARGET_CFG_PATH, "目标CFG文件");
        checkFileExists(TARGET_DAT_PATH, "目标DAT文件");

        long startTime = System.currentTimeMillis();

        try (InputStream sourceCfgStream = new FileInputStream(SOURCE_CFG_PATH);
             InputStream sourceDatStream = new FileInputStream(SOURCE_DAT_PATH);
             InputStream targetCfgStream = new FileInputStream(TARGET_CFG_PATH);
             InputStream targetDatStream = new FileInputStream(TARGET_DAT_PATH)) {

            CompareWaveDTO result = compareWaveServiceImpl.analyzeWithSegmentPreservation(
                    sourceCfgStream,
                    sourceDatStream,
                    targetCfgStream,
                    targetDatStream,
                    0  // 接线方式: 0=星型接线, 1=V型接线
            );

            long endTime = System.currentTimeMillis();
            long duration = endTime - startTime;

            // 输出分析结果
            System.out.println("========================================");
            System.out.println("分析完成！");
            System.out.println("总耗时: " + duration + " ms (" + String.format("%.2f", duration / 1000.0) + " 秒)");
            System.out.println("源文件有效窗口数: " + (result.getSourceResults() != null ? result.getSourceResults().size() : 0));
            System.out.println("目标文件有效窗口数: " + (result.getTargetResults() != null ? result.getTargetResults().size() : 0));
            System.out.println("========================================");
            System.out.println("段信息保留模式测试完成！");
            System.out.println("========================================");

        }
    }

    /**
     * 检查文件是否存在
     */
    private void checkFileExists(String filePath, String description) {
        File file = new File(filePath);
        if (!file.exists()) {
            System.err.println("警告: " + description + " 不存在: " + filePath);
            System.err.println("请确保文件路径正确，或修改测试中的文件路径");
        } else {
            System.out.println(description + " 存在: " + filePath);
            System.out.println("  文件大小: " + file.length() + " bytes");
        }
    }

}