package com.njcn.harmonic.service.report.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.common.pojo.dto.SimpleDTO;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.device.biz.commApi.CommTerminalGeneralClient;
import com.njcn.device.biz.pojo.dto.MonitorCommLedgerInfoDTO;
import com.njcn.device.biz.pojo.param.DeptGetLineParam;
import com.njcn.harmonic.pojo.dto.report.TableMergeRule;
import com.njcn.harmonic.pojo.param.report.AreaHarmReportParam;
import com.njcn.harmonic.pojo.vo.OverAreaLimitVO;
import com.njcn.harmonic.pojo.vo.OverAreaVO;
import com.njcn.harmonic.service.IAnalyzeService;
import com.njcn.harmonic.service.report.AreaHarmonicService;
import com.njcn.harmonic.utils.WordUtil2;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.enums.DicDataTypeEnum;
import com.njcn.system.pojo.po.DictData;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.user.pojo.po.Dept;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * @Author: cdf
 * @CreateTime: 2026-01-04
 * @Description: 区域报告 - 优化版本
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class AreaHarmonicServiceImpl implements AreaHarmonicService {

    // 常量定义
    private static final String REPORT_TEMPLATE_PATH = "file/areaReportTemplate.docx";

    @Value("${areaReportTitle:上海电力有限公司电力科学研究院}")
    private String DEFAULT_PROVIDER_DEPT;
    private static final String NO_DATA_PLACEHOLDER = "无";
    private static final String UNKNOWN_VALUE = "/";

    // 指标等级阈值
    private static final double EXCELLENT_MAX_THRESHOLD = 5.0;
    private static final double GOOD_MAX_THRESHOLD = 10.0;
    private static final double MEDIUM_MAX_THRESHOLD = 30.0;

    // 谐波次数顺序（保持原有顺序）
    private static final List<String> HARMONIC_ORDERS = Arrays.asList("3", "5", "7", "11","other");

    // 表格索引（保持原有顺序）
    private static final int LEDGER_TABLE_INDEX = 1;
    private static final int VOLTAGE_DEV_TABLE_INDEX = 3;
    private static final int FREQUENCY_TABLE_INDEX = 4;
    private static final int VOLTAGE_BALANCE_TABLE_INDEX = 5;
    private static final int FLICKER_TABLE_INDEX = 6;
    private static final int VOLTAGE_HARMONIC_TABLE_INDEX = 7;
    private static final int CURRENT_HARMONIC_TABLE_INDEX = 8;

    private final WordUtil2 wordUtil2;
    private final DeptFeignClient deptFeignClient;
    private final CommTerminalGeneralClient commTerminalGeneralClient;
    private final IAnalyzeService iAnalyzeService; // 修正变量名
    private final DicDataFeignClient dicDataFeignClient;

    @Override
    public void areaHarmonicReport(AreaHarmReportParam areaHarmReportParam, HttpServletResponse response) {
        try {
            Assert.notNull(areaHarmReportParam, "报告参数不能为空");

            // 1. 构建报告数据
            Map<String, Object> reportData = buildReportData(areaHarmReportParam);

            // 2. 构建表格数据
            List<List<String[]>> tableList = buildTableData(areaHarmReportParam,reportData);

            // 3. 生成Word报告
            generateWordReport(reportData, tableList, response);

        } catch (BusinessException e){
            throw e;
        }catch (Exception e) {
            log.error("区域谐波报告生成失败，参数: {}", areaHarmReportParam, e);
            throw new BusinessException(CommonResponseEnum.FAIL,"报告生成失败");
        }
    }

    /**
     * 构建报告基础数据
     */
    private Map<String, Object> buildReportData(AreaHarmReportParam param) {
        Map<String, Object> reportData = new HashMap<>(32);

        // 部门信息
        Dept dept = getDeptInfo(param.getDeptId());
        reportData.put("$deptName$", dept.getName());
        reportData.put("$provideDept$", DEFAULT_PROVIDER_DEPT);

        DateTime now = DateTime.now();
        reportData.put("$TitleTime$", DateUtil.format(now, DatePattern.CHINESE_DATE_PATTERN));

        // 时间范围
        String timeRange = formatTimeRange(param.getStartTime(), param.getEndTime(),now);
        reportData.put("$reportRangeTime$", timeRange);

        return reportData;
    }

    /**
     * 构建所有表格数据
     */
    private List<List<String[]>> buildTableData(AreaHarmReportParam param,Map<String, Object> reportData){
        List<List<String[]>> tableList = new ArrayList<>();

        // 添加空行（保持原有结构）
        tableList.add(new ArrayList<>());

        // 1. 台账表格
        List<String[]> ledgerTable = buildLedgerTable(param.getDeptId(),param.getVoltageIds());
        if(CollUtil.isEmpty(ledgerTable)){
            throw new BusinessException(CommonResponseEnum.FAIL,"未查询到在运监测点");
        }
        tableList.add(ledgerTable);

        // 添加空行（保持原有结构）
        tableList.add(new ArrayList<>());

        // 2. 电能质量数据表格
        List<OverAreaLimitVO> qualityData = getPowerQualityData(param);
        if (CollUtil.isNotEmpty(qualityData)) {
            // 构建监控点名称映射
            Map<String, String> monitorNameMap = buildMonitorNameMap(param.getDeptId(),param.getVoltageIds());

            // 过滤有效数据（在线监控数>0）
            List<OverAreaLimitVO> validData = qualityData.stream()
                    .filter(vo -> vo.getOnlineMonitorNumber() != null && vo.getOnlineMonitorNumber() > 0)
                    .collect(Collectors.toList());

            if (CollUtil.isNotEmpty(validData)) {
                tableList.add(buildVoltageDeviationTable(validData));
                tableList.add(buildFrequencyTable(validData));
                tableList.add(buildVoltageBalanceTable(validData));
                tableList.add(buildFlickerTable(validData));
                tableList.add(buildVoltageHarmonicTable(validData));
                tableList.add(buildCurrentHarmonicTable(validData));
                tableList.add(buildIHarmonicVTable(validData));

                // 计算并设置指标数据到临时存储，稍后合并
                calculateAndStoreIndicatorData(reportData, validData, monitorNameMap);
            }else {
                throw new BusinessException(CommonResponseEnum.FAIL,"时间范围内数据为空");
            }
        }

        // 添加空行（保持原有结构）
        tableList.add(new ArrayList<>());

        return tableList;
    }

    /**
     * 构建台账表格
     */
    private List<String[]> buildLedgerTable(String deptId, List<String> voltageIds) {
        List<MonitorCommLedgerInfoDTO> ledgerList = getLedgerInfo(deptId,voltageIds);
        if (CollUtil.isEmpty(ledgerList)) {
            return new ArrayList<>();
        }

        // 获取电压等级字典
        Map<String, String> voltageLevelMap = getVoltageLevelMap();

        return IntStream.range(0, ledgerList.size())
                .mapToObj(i -> {
                    MonitorCommLedgerInfoDTO ledger = ledgerList.get(i);
                    return new String[]{
                            String.valueOf(i + 1),
                            StringUtils.hasText(ledger.getObjName())? ledger.getObjName()+"_"+ledger.getMonitorName():ledger.getMonitorName(),
                            ledger.getBdName(),
                            ledger.getBusBarName(),
                            voltageLevelMap.getOrDefault(ledger.getVoltageLevel(), ""),
                            ledger.getShortCapacity(),
                            ledger.getDevCapacity(),
                            ledger.getDealCapacity()
                    };
                })
                .collect(Collectors.toList());
    }

    /**
     * 构建电压偏差表格
     */
    private List<String[]> buildVoltageDeviationTable(List<OverAreaLimitVO> dataList) {
        return dataList.stream()
                .filter(vo -> vo.getOnlineMonitorNumber() != null && vo.getOnlineMonitorNumber() > 0)
                .map(vo -> new String[]{
                        vo.getName(),
                        vo.getOnlineMonitorNumber().toString(),
                        vo.getVoltageMonitorNumber().toString(),
                        vo.getVoltageBiLi().toString(),
                        vo.getVoltageDayAvgBiLi().toString(),
                        vo.getVoltageOverDayBiLi().toString()
                })
                .collect(Collectors.toList());
    }

    /**
     * 构建频率表格
     */
    private List<String[]> buildFrequencyTable(List<OverAreaLimitVO> dataList) {
        return dataList.stream()
                .filter(vo -> vo.getOnlineMonitorNumber() != null && vo.getOnlineMonitorNumber() > 0)
                .map(vo -> new String[]{
                        vo.getName(),
                        vo.getOnlineMonitorNumber().toString(),
                        vo.getFrequencyMonitorNumber().toString(),
                        vo.getFrequencyBiLi().toString(),
                        vo.getFrequencyDayAvgBiLi().toString(),
                        vo.getFrequencyOverDayBiLi().toString()
                })
                .collect(Collectors.toList());
    }

    /**
     * 构建三相电压不平衡度表格
     */
    private List<String[]> buildVoltageBalanceTable(List<OverAreaLimitVO> dataList) {
        return dataList.stream()
                .filter(vo -> vo.getOnlineMonitorNumber() != null && vo.getOnlineMonitorNumber() > 0)
                .map(vo -> new String[]{
                        vo.getName(),
                        vo.getOnlineMonitorNumber().toString(),
                        vo.getThreePhaseVoltageMonitorNumber().toString(),
                        vo.getThreePhaseVoltageBiLi().toString(),
                        vo.getThreePhaseVoltageDayAvgBiLi().toString(),
                        vo.getThreePhaseVoltageOverDayBiLi().toString()
                })
                .collect(Collectors.toList());
    }

    /**
     * 构建闪变表格
     */
    private List<String[]> buildFlickerTable(List<OverAreaLimitVO> dataList) {
        return dataList.stream()
                .filter(vo -> vo.getOnlineMonitorNumber() != null && vo.getOnlineMonitorNumber() > 0)
                .map(vo -> new String[]{
                        vo.getName(),
                        vo.getOnlineMonitorNumber().toString(),
                        vo.getFlickerMonitorNumber().toString(),
                        vo.getFlickerBiLi().toString(),
                        vo.getFlickerDayAvgBiLi().toString(),
                        vo.getFlickerOverDayBiLi().toString()
                })
                .collect(Collectors.toList());
    }

    /**
     * 构建间谐波表格
     */
    private List<String[]> buildIHarmonicVTable(List<OverAreaLimitVO> dataList) {
        return dataList.stream()
                .filter(vo -> vo.getOnlineMonitorNumber() != null && vo.getOnlineMonitorNumber() > 0)
                .map(vo -> new String[]{
                        vo.getName(),
                        vo.getOnlineMonitorNumber().toString(),
                        vo.getInterHarmonicMonitorNumber().toString(),
                        vo.getInterHarmonicBiLi().toString(),
                        vo.getInterHarmonicDayAvgBiLi().toString(),
                        vo.getInterHarmonicOverDayBiLi().toString()
                })
                .collect(Collectors.toList());
    }

    /**
     * 构建谐波电压表格
     */
    private List<String[]> buildVoltageHarmonicTable(List<OverAreaLimitVO> dataList) {
        List<String[]> tableData = new ArrayList<>();

        for (OverAreaLimitVO vo : dataList) {
            if (vo.getOnlineMonitorNumber() == null || vo.getOnlineMonitorNumber() == 0) {
                continue;
            }

            // 添加总行
            tableData.add(new String[]{
                    vo.getName(),
                    "2~25",
                    vo.getOnlineMonitorNumber().toString(),
                    vo.getHarmonicVoltageMonitorNumber().toString(),
                    vo.getHarmonicVoltageBiLi().toString(),
                    vo.getHarmonicVoltageDayAvgBiLi().toString(),
                    vo.getHarmonicVoltageOverDayBiLi().toString()
            });

            // 添加各次谐波行
            if (CollUtil.isNotEmpty(vo.getInnerHarmVList())) {
                for (OverAreaLimitVO.InnerHarmV innerHarm : vo.getInnerHarmVList()) {
                    tableData.add(new String[]{
                            "",
                            innerHarm.getName(),
                            vo.getOnlineMonitorNumber().toString(),
                            innerHarm.getLimitCount().toString(),
                            innerHarm.getLimitRate().toString(),
                            innerHarm.getDayAvg().toString(),
                            innerHarm.getDayLimit().toString()
                    });
                }
            }
        }

        return tableData;
    }

    /**
     * 构建谐波电流表格
     */
    private List<String[]> buildCurrentHarmonicTable(List<OverAreaLimitVO> dataList) {
        List<String[]> tableData = new ArrayList<>();

        for (OverAreaLimitVO vo : dataList) {
            if (vo.getOnlineMonitorNumber() == null || vo.getOnlineMonitorNumber() == 0) {
                continue;
            }

            // 添加总行
            tableData.add(new String[]{
                    vo.getName(),
                    "2~25",
                    vo.getOnlineMonitorNumber().toString(),
                    vo.getHarmonicCurrentMonitorNumber().toString(),
                    vo.getHarmonicCurrentBiLi().toString(),
                    vo.getHarmonicCurrentDayAvgBiLi().toString(), // 注意：这里保持原逻辑，使用谐波电压日均值
                    vo.getHarmonicCurrentOverDayBiLi().toString()
            });

            // 添加各次谐波行
            if (CollUtil.isNotEmpty(vo.getInnerHarmIList())) {
                for (OverAreaLimitVO.InnerHarmV innerHarm : vo.getInnerHarmIList()) {
                    tableData.add(new String[]{
                            "",
                            innerHarm.getName(),
                            vo.getOnlineMonitorNumber().toString(),
                            innerHarm.getLimitCount().toString(),
                            innerHarm.getLimitRate().toString(),
                            innerHarm.getDayAvg().toString(),
                            innerHarm.getDayLimit().toString()
                    });
                }
            }
        }

        return tableData;
    }

    /**
     * 计算并存储指标数据
     */
    private void calculateAndStoreIndicatorData(Map<String, Object> reportData,
                                                List<OverAreaLimitVO> validData,
                                                Map<String, String> monitorNameMap) {
        // 电压偏差
        processVoltageDeviation(reportData, validData, monitorNameMap);

        // 频率偏差
        processFrequencyDeviation(reportData, validData, monitorNameMap);

        // 三相电压不平衡度
        processVoltageBalance(reportData, validData, monitorNameMap);

        // 闪变
        processFlicker(reportData, validData, monitorNameMap);

        // 谐波电压
        processVoltageHarmonic(reportData, validData, monitorNameMap);

        // 谐波电流
        processCurrentHarmonic(reportData, validData, monitorNameMap);

        //间谐波电压含有率
        processIHarmonicV(reportData, validData, monitorNameMap);
        // 生成结论
        generateConclusion(reportData);
    }

    /**
     * 处理电压偏差
     */
    private void processVoltageDeviation(Map<String, Object> reportData,
                                         List<OverAreaLimitVO> dataList,
                                         Map<String, String> monitorNameMap) {
        double avgRate = calculateAverage(dataList, OverAreaLimitVO::getVoltageBiLi);
        List<String> monitorList = extractMonitorNames(dataList,
                vo -> vo.getVoltageMonitorList(), monitorNameMap);

        reportData.put("$voltageDevRate$", formatPercentage(avgRate));
        reportData.put("$voltageDevMark$", getGrade(avgRate));
        reportData.put("$voltageDevLine$", formatMonitorList(monitorList));
    }

    /**
     * 处理频率偏差
     */
    private void processFrequencyDeviation(Map<String, Object> reportData,
                                           List<OverAreaLimitVO> dataList,
                                           Map<String, String> monitorNameMap) {
        double avgRate = calculateAverage(dataList, OverAreaLimitVO::getFrequencyBiLi);
        List<String> monitorList = extractMonitorNames(dataList,
                vo -> vo.getFreqMonitorList(), monitorNameMap);

        reportData.put("$freqRate$", formatPercentage(avgRate));
        reportData.put("$freqMark$", getGrade(avgRate));
        reportData.put("$freqLine$", formatMonitorList(monitorList));
    }

    /**
     * 处理三相电压不平衡度
     */
    private void processVoltageBalance(Map<String, Object> reportData,
                                       List<OverAreaLimitVO> dataList,
                                       Map<String, String> monitorNameMap) {
        double avgRate = calculateAverage(dataList, OverAreaLimitVO::getThreePhaseVoltageBiLi);
        List<String> monitorList = extractMonitorNames(dataList,
                vo -> vo.getThreePhaseVoltageMonitorList(), monitorNameMap);

        reportData.put("$balanceRate$", formatPercentage(avgRate));
        reportData.put("$balanceMark$", getGrade(avgRate));
        reportData.put("$balanceLine$", formatMonitorList(monitorList));
    }

    /**
     * 处理闪变
     */
    private void processFlicker(Map<String, Object> reportData,
                                List<OverAreaLimitVO> dataList,
                                Map<String, String> monitorNameMap) {
        double avgRate = calculateAverage(dataList, OverAreaLimitVO::getFlickerBiLi);
        List<String> monitorList = extractMonitorNames(dataList,
                vo -> vo.getFlickerMonitorList(), monitorNameMap);

        reportData.put("$flickerRate$", formatPercentage(avgRate));
        reportData.put("$flickerMark$", getGrade(avgRate));
        reportData.put("$flickerLine$", formatMonitorList(monitorList));
    }

    /**
     * 处理间谐波电压含有率
     */
    private void processIHarmonicV(Map<String, Object> reportData,
                                List<OverAreaLimitVO> dataList,
                                Map<String, String> monitorNameMap) {
        double avgRate = calculateAverage(dataList, OverAreaLimitVO::getInterHarmonicBiLi);
        List<String> monitorList = extractMonitorNames(dataList,
                vo -> vo.getInHarmonicVMonitorList(), monitorNameMap);

        reportData.put("$iharmVRate$", formatPercentage(avgRate));
        reportData.put("$iharmVMark$", getGrade(avgRate));
        reportData.put("$iharmVLine$", formatMonitorList(monitorList));
    }


    /**
     * 处理谐波电压
     */
    private void processVoltageHarmonic(Map<String, Object> reportData,
                                        List<OverAreaLimitVO> dataList,
                                        Map<String, String> monitorNameMap) {
        // 总谐波电压
        double avgAll = calculateAverage(dataList, OverAreaLimitVO::getHarmonicVoltageBiLi);
        List<String> monitorAllList = extractMonitorNames(dataList,
                vo -> vo.getHarmonicVoltageMonitorList(), monitorNameMap);

        reportData.put("$v_all_Rate$", formatPercentage(avgAll));
        reportData.put("$v_all_Mark$", getGrade(avgAll));
        reportData.put("$v_all_Line$", formatMonitorList(monitorAllList));

        // 各次谐波电压（保持原有顺序）
        for (int i = 0; i < HARMONIC_ORDERS.size(); i++) {
            final int index = i;
            double avgHarmonic = calculateAverageFromInnerList(dataList,
                    vo -> vo.getInnerHarmVList().get(index).getLimitRate());
            List<String> monitorHarmonicList = extractMonitorNamesFromInnerList(dataList,
                    vo -> vo.getInnerHarmVList().get(index).getLimitIdList(), monitorNameMap);

            String harmonicKey = HARMONIC_ORDERS.get(i);
            reportData.put("$v_" + harmonicKey + "_Rate$", formatPercentage(avgHarmonic));
            reportData.put("$v_" + harmonicKey + "_Mark$", getGrade(avgHarmonic));
            reportData.put("$v_" + harmonicKey + "_Line$", formatMonitorList(monitorHarmonicList));
        }
    }

    /**
     * 处理谐波电流
     */
    private void processCurrentHarmonic(Map<String, Object> reportData,
                                        List<OverAreaLimitVO> dataList,
                                        Map<String, String> monitorNameMap) {
        // 总谐波电流
        double avgAll = calculateAverage(dataList, OverAreaLimitVO::getHarmonicCurrentBiLi);
        List<String> monitorAllList = extractMonitorNames(dataList,
                vo -> vo.getHarmonicCurrentMonitorList(), monitorNameMap);

        reportData.put("$i_all_Rate$", formatPercentage(avgAll));
        reportData.put("$i_all_Mark$", getGrade(avgAll));
        reportData.put("$i_all_Line$", formatMonitorList(monitorAllList));

        // 各次谐波电流（保持原有顺序）
        for (int i = 0; i < HARMONIC_ORDERS.size(); i++) {
            final int index = i;
            double avgHarmonic = calculateAverageFromInnerList(dataList,
                    vo -> vo.getInnerHarmIList().get(index).getLimitRate());
            List<String> monitorHarmonicList = extractMonitorNamesFromInnerList(dataList,
                    vo -> vo.getInnerHarmIList().get(index).getLimitIdList(), monitorNameMap);

            String harmonicKey = HARMONIC_ORDERS.get(i);
            reportData.put("$i_" + harmonicKey + "_Rate$", formatPercentage(avgHarmonic));
            reportData.put("$i_" + harmonicKey + "_Mark$", getGrade(avgHarmonic));
            reportData.put("$i_" + harmonicKey + "_Line$", formatMonitorList(monitorHarmonicList));
        }
    }

    /**
     * 生成结论
     */
    private void generateConclusion(Map<String, Object> reportData) {
        Map<String, String> indicatorScores = new LinkedHashMap<>();
        indicatorScores.put("供电电压偏差", reportData.get("$voltageDevMark$").toString());
        indicatorScores.put("频率偏差", reportData.get("$freqMark$").toString());
        indicatorScores.put("三相电压不平衡度", reportData.get("$balanceMark$").toString());
        indicatorScores.put("闪变", reportData.get("$flickerMark$").toString());
        indicatorScores.put("谐波电压", reportData.get("$v_all_Mark$").toString());
        indicatorScores.put("谐波电流", reportData.get("$i_all_Mark$").toString());
        indicatorScores.put("间谐波电压含有率", reportData.get("$iharmVMark$").toString());
        // 按等级分类指标
        Map<String, List<String>> categorizedIndicators = categorizeIndicators(indicatorScores);

        // 构建结论文本
        String conclusion = buildConclusionText(categorizedIndicators);
        reportData.put("$conclusion$", conclusion);
    }

    /**
     * 按等级分类指标
     */
    private Map<String, List<String>> categorizeIndicators(Map<String, String> indicatorScores) {
        Map<String, List<String>> categorized = new LinkedHashMap<>();
        categorized.put("优秀", new ArrayList<>());
        categorized.put("良", new ArrayList<>());
        categorized.put("中", new ArrayList<>());
        categorized.put("差", new ArrayList<>());

        indicatorScores.forEach((indicator, grade) -> {
            if (categorized.containsKey(grade)) {
                categorized.get(grade).add(indicator);
            }
        });

        return categorized;
    }

    /**
     * 构建结论文本
     */
    private String buildConclusionText(Map<String, List<String>> categorizedIndicators) {
        StringBuilder conclusion = new StringBuilder();
        List<String> badIndicators = categorizedIndicators.get("差");

        // 按顺序构建结论
        List<Map.Entry<String, List<String>>> entries = new ArrayList<>(categorizedIndicators.entrySet());
        for (Map.Entry<String, List<String>> entry : entries) {
            List<String> indicators = entry.getValue();
            if (CollUtil.isNotEmpty(indicators)) {
                if (conclusion.length() > 0) {
                    conclusion.append("，");
                }
                conclusion.append(String.join("、", indicators))
                        .append("等指标评分为").append(entry.getKey());
            }
        }

        // 添加重点关注提示
        if (CollUtil.isNotEmpty(badIndicators)) {
            conclusion.append("，需要重点关注该区域")
                    .append(String.join("、", badIndicators))
                    .append("等指标情况");
        }

        return conclusion.toString();
    }

    /**
     * 生成Word报告
     */
    private void generateWordReport(Map<String, Object> reportData,
                                    List<List<String[]>> tableList,
                                    HttpServletResponse response) {
        try {
            // 构建表格合并规则
            List<TableMergeRule> mergeRules = buildTableMergeRules();

            // 生成文件名
            String fileName = generateFileName();

            // 调用Word工具生成报告
            wordUtil2.getWord(REPORT_TEMPLATE_PATH, reportData, fileName,
                    tableList, mergeRules, response);

        } catch (Exception e) {
            log.error("Word报告生成失败", e);
            throw new BusinessException(CommonResponseEnum.FAIL,"Word报告生成失败");
        }
    }

    /**
     * 构建表格合并规则
     */
    private List<TableMergeRule> buildTableMergeRules() {
        List<TableMergeRule> mergeRules = new ArrayList<>();
        // 表格7（谐波电压）的第0列，每6行合并一次（对应"单位"列）
        mergeRules.add(TableMergeRule.build(VOLTAGE_HARMONIC_TABLE_INDEX, 0, 1, 6));
        // 表格8（谐波电流）的第0列，每6行合并一次（对应"单位"列）
        mergeRules.add(TableMergeRule.build(CURRENT_HARMONIC_TABLE_INDEX, 0, 1, 6));
        return mergeRules;
    }

    /**
     * 生成文件名
     */
    private String generateFileName() {
        return "fileName.docx"; // 保持原有文件名逻辑
    }

    /**
     * 工具方法：计算平均值
     */
    private double calculateAverage(List<OverAreaLimitVO> dataList,
                                    Function<OverAreaLimitVO, Double> valueExtractor) {
        return dataList.stream()
                .map(valueExtractor)
                .filter(value -> value != null && value >= 0)
                .mapToDouble(Double::doubleValue)
                .average()
                .orElse(0.0);
    }

    /**
     * 工具方法：从内部列表计算平均值
     */
    private double calculateAverageFromInnerList(List<OverAreaLimitVO> dataList,
                                                 Function<OverAreaLimitVO, Double> valueExtractor) {
        return dataList.stream()
                .map(valueExtractor)
                .filter(value -> value != null && value >= 0)
                .mapToDouble(Double::doubleValue)
                .average()
                .orElse(0.0);
    }

    /**
     * 工具方法：提取监控点名称
     */
    private List<String> extractMonitorNames(List<OverAreaLimitVO> dataList,
                                             Function<OverAreaLimitVO, List<String>> idExtractor,
                                             Map<String, String> idToNameMap) {
        return dataList.stream()
                .flatMap(vo -> {
                    List<String> ids = idExtractor.apply(vo);
                    return ids != null ? ids.stream() : Stream.<String>empty();
                })
                .distinct()
                .map(idToNameMap::get)
                .filter(name -> name != null && !name.trim().isEmpty())
                .collect(Collectors.toList());
    }

    /**
     * 工具方法：从内部列表提取监控点名称
     */
    private List<String> extractMonitorNamesFromInnerList(List<OverAreaLimitVO> dataList,
                                                          Function<OverAreaLimitVO, List<String>> idExtractor,
                                                          Map<String, String> idToNameMap) {
        return dataList.stream()
                .flatMap(vo -> {
                    List<String> ids = idExtractor.apply(vo);
                    return ids != null ? ids.stream() : Stream.<String>empty();
                })
                .distinct()
                .map(idToNameMap::get)
                .filter(name -> name != null && !name.trim().isEmpty())
                .collect(Collectors.toList());
    }

    /**
     * 工具方法：格式化百分比
     */
    private String formatPercentage(double value) {
        if (value < 0) {
            return UNKNOWN_VALUE;
        }
        return BigDecimal.valueOf(value)
                .setScale(2, RoundingMode.HALF_UP)
                .doubleValue() + "%";
    }

    /**
     * 工具方法：获取等级
     */
    private String getGrade(double value) {
        if (value < 0) {
            return UNKNOWN_VALUE;
        } else if (value <= EXCELLENT_MAX_THRESHOLD) {
            return "优秀";
        } else if (value <= GOOD_MAX_THRESHOLD) {
            return "良";
        } else if (value <= MEDIUM_MAX_THRESHOLD) {
            return "中";
        } else {
            return "差";
        }
    }

    /**
     * 工具方法：格式化时间范围
     */
    private String formatTimeRange(String startTime, String endTime,DateTime now) {
        try {
            String start = DateUtil.format(
                    DateUtil.beginOfDay(DateUtil.parse(startTime)),
                    DatePattern.CHINESE_DATE_TIME_PATTERN
            );

            DateTime dateTime = DateUtil.endOfDay(DateUtil.parse(endTime));
            String end;
            if(now.isBefore(dateTime)){
                end = DateUtil.format(
                        now,
                        DatePattern.CHINESE_DATE_TIME_PATTERN);
            }else {
                end = DateUtil.format(
                        dateTime,
                        DatePattern.CHINESE_DATE_TIME_PATTERN);
            }


            return start + "-" + end;
        } catch (Exception e) {
            log.error("格式化时间范围失败", e);
            return "";
        }
    }

    /**
     * 工具方法：格式化监控点列表
     */
    private String formatMonitorList(List<String> monitorList) {
        if (CollUtil.isEmpty(monitorList)) {
            return NO_DATA_PLACEHOLDER;
        }
        return String.join(",", monitorList);
    }

    /**
     * 获取部门信息
     */
    private Dept getDeptInfo(String deptId) {
        return deptFeignClient.getDeptById(deptId).getData();
    }

    /**
     * 获取台账信息
     */
    private List<MonitorCommLedgerInfoDTO> getLedgerInfo(String deptId, List<String> voltageIds) {
        DeptGetLineParam param = new DeptGetLineParam();
        param.setDeptId(deptId);
        List<MonitorCommLedgerInfoDTO> data = commTerminalGeneralClient.deptGetLineInfo(param).getData();
        if(CollUtil.isNotEmpty(voltageIds)){
            data=data.stream().filter(temp->voltageIds.contains(temp.getVoltageLevel())).collect(Collectors.toList());
        }
        return data;
    }

    /**
     * 获取电压等级字典
     */
    private Map<String, String> getVoltageLevelMap() {
        List<DictData> dictDataList = dicDataFeignClient
                .getDicDataByTypeCode(DicDataTypeEnum.DEV_VOLTAGE_STAND.getCode())
                .getData();
        return dictDataList.stream()
                .collect(Collectors.toMap(DictData::getId, DictData::getName));
    }

    /**
     * 构建监控点名称映射
     */
    private Map<String, String> buildMonitorNameMap(String deptId, List<String> voltageIds) {
        List<MonitorCommLedgerInfoDTO> ledgerList = getLedgerInfo(deptId, voltageIds);
        return ledgerList.stream()
                .collect(Collectors.toMap(
                                MonitorCommLedgerInfoDTO::getMonitorId,
                            temp-> StringUtils.hasText(temp.getObjName())? temp.getObjName()+"_"+temp.getMonitorName():temp.getMonitorName()

                        ));
    }

    /**
     * 获取电能质量数据
     */
    private List<OverAreaLimitVO> getPowerQualityData(AreaHarmReportParam param) {
        OverAreaVO queryParam = new OverAreaVO();
        queryParam.setDeptIndex(param.getDeptId());
        queryParam.setPageNum(1);
        queryParam.setPageSize(1000);
        queryParam.setSearchBeginTime(param.getStartTime());
        queryParam.setSearchEndTime(param.getEndTime());
        queryParam.setStatisticalType(new SimpleDTO());
        queryParam.setAreaReportFlag(1);
        if(CollUtil.isNotEmpty(param.getVoltageIds())){
            List<SimpleDTO> collect = param.getVoltageIds().stream().map(temp -> {
                SimpleDTO simpleDTO = new SimpleDTO();
                simpleDTO.setId(temp);
                return simpleDTO;
            }).collect(Collectors.toList());
            queryParam.setScale(collect);
        }



        Page<OverAreaLimitVO> page = iAnalyzeService.getAreaData(queryParam);
        return page.getRecords();
    }




}



