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

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.utils.PubUtils;
import com.njcn.device.biz.commApi.CommLineClient;
import com.njcn.device.pms.api.MonitorClient;
import com.njcn.device.pms.pojo.po.Monitor;
import com.njcn.device.pq.api.DeviceUnitClient;
import com.njcn.device.pq.api.LineFeignClient;
import com.njcn.harmonic.common.pojo.dto.DeviceUnitCommDTO;
import com.njcn.harmonic.common.pojo.dto.HarmLineDetailDataCommDTO;
import com.njcn.harmonic.common.pojo.dto.OverLimitInfoCommDTO;
import com.njcn.harmonic.common.service.MonitorCommReportService;
import com.njcn.harmonic.common.service.MonitorHarmonicReportService;
import com.njcn.harmonic.pojo.param.ReportQueryParam;
import com.njcn.harmonic.pojo.po.report.EnumPass;
import com.njcn.harmonic.pojo.po.report.Pass;
import com.njcn.harmonic.pojo.po.report.ReportTarget;
import com.njcn.harmonic.pojo.vo.ReportValue;
import com.njcn.harmonic.utils.WordUtil2;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.api.ThemeFeignClient;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.system.enums.DicDataTypeEnum;
import com.njcn.system.pojo.po.DictData;
import com.njcn.system.pojo.po.Theme;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * pqs
 *
 * @author cdf
 * @date 2026/1/17
 */
@Service
@Slf4j
@RequiredArgsConstructor
@DS("sjzx")
public class MonitorHarmonicReportServiceImpl implements MonitorHarmonicReportService {


    /**
     * 非谐波数据
     */
    List<ReportTarget> listVirtual;
    List<ReportTarget> listPower;
    List<ReportTarget> listFlicker;
    List<ReportTarget> listDistortion;
    List<ReportTarget> listVdeviation;
    List<ReportTarget> listFrequency;
    List<ReportTarget> listThreephase;
    /**
     * 谐波电压数据
     */
    List<ReportTarget> listVoltageRate;
    /**
     * 谐波电流数据
     */
    List<ReportTarget> listICurrent;


    private final MonitorClient monitorClient;
    private final DicDataFeignClient dicDataFeignClient;
    private final ThemeFeignClient themeFeignClient;
    private final MonitorCommReportService reportService;
    private final DeviceUnitClient deviceUnitClient;
    private final WordUtil2 wordUtil2;

    /**
     * @param response
     * @param startTime    开始时间
     * @param endTime      结束时间
     * @param type         区分pq:0 pms:1
     * @param lineIndex    监测点id
     * @param name         监测点名称
     * @param reportNumber 客户编号
     * @param crmName      客户名称
     * @param file         接线图
     * @param isUrl        是否地址栏返回
     * @return
     * @throws IOException
     */
    @Override
    public void exportWorld(HttpServletResponse response,
                            String startTime,
                            String endTime,
                            Integer type,
                            String lineIndex,
                            String name,
                            String reportNumber,
                            String crmName,
                            Boolean isUrl,
                            MultipartFile file,
                            HarmLineDetailDataCommDTO lineDto, OverLimitInfoCommDTO overLimit, DeviceUnitCommDTO deviceUnit, String dataLevel) {
        //获取监测点信息
        String bdname;
        Integer pttype;
        String areaName;
        String atype = "";
        String btype = "";
        String ctype = "";
        //pt
        Double pt = getData(lineDto.getPt());
        //ct
        Double ct = getData(lineDto.getCt());


        if (type == 0) {
            if (ObjectUtil.isNull(lineDto)) {
                throw new BusinessException(CommonResponseEnum.NO_DATA);
            }
            if(StrUtil.isNotBlank(lineDto.getObjId())){
                bdname = lineDto.getObjName();
                name = lineDto.getLineName();
            }else {
                bdname = lineDto.getBdName();
            }
            areaName = lineDto.getAreaName();
            if("冀北".equals(areaName)){
                areaName="国网"+areaName;
            }
            pttype = PubUtils.ptTypeName(lineDto.getPtType());
        } else {
            List<Monitor> monitorList = monitorClient.getMonitorList(Collections.singletonList(lineIndex)).getData();
            if (ObjectUtil.isNull(monitorList)) {
                throw new BusinessException(CommonResponseEnum.NO_DATA);
            }
            Monitor monitor = monitorList.get(0);
            bdname = monitor.getPowerrName();
            areaName = monitor.getOrgName();
            String terminalWiringMethod = dicDataFeignClient.getDicDataById(monitor.getTerminalWiringMethod()).getData().getName();
            pttype = PubUtils.ptTypeName(terminalWiringMethod);
            lineDto.setPt(monitor.getPt1() + "/" + monitor.getPt2());
            lineDto.setCt(monitor.getCt1() + "/" + monitor.getCt2());
            //基准容量
            lineDto.setStandardCapacity(monitor.getStandShortCapacity());
            //短路容量
            lineDto.setShortCapacity(monitor.getMinShortCircuitCapacity());
            //协议容量
            lineDto.setDealCapacity(monitor.getUserAgreementCapacity());
            //设备容量
            lineDto.setDevCapacity(monitor.getPowerSupplyEqCapacity());
            //电压等级
            lineDto.setScale(dicDataFeignClient.getDicDataById(monitor.getVoltageLevel()).getData().getName());

        }
        if (pttype == 0) {
            atype = "A相";
            btype = "B相";
            ctype = "C相";
        } else if (pttype == 1) {
            atype = "AB相";
            btype = "BC相";
            ctype = "CA相";
        } else if (pttype == 2) {
            atype = "AB相";
            btype = "BC相";
            ctype = "-";

        }
        DateTime startDate = DateUtil.beginOfDay(DateUtil.parse(startTime));
        DateTime endDate = DateUtil.endOfDay(DateUtil.parse(endTime));
        long day = DateUtil.betweenDay(startDate, endDate, false);
        //通用查询条件
        ReportQueryParam param = new ReportQueryParam();
        param.setLineId(lineIndex);
        param.setStartTime(DateUtil.format(startDate, "yyyy-MM-dd HH:mm:ss"));
        LocalDateTime parse = LocalDateTimeUtil.parse(DateUtil.format(endDate, "yyyy-MM-dd HH:mm:ss"), DatePattern.NORM_DATETIME_PATTERN);
        if(LocalDateTime.now().isBefore(parse)){
            param.setEndTime(LocalDateTimeUtil.format(LocalDateTime.now(),DatePattern.NORM_DATETIME_PATTERN));
            endDate = DateUtil.parse(LocalDateTimeUtil.format(LocalDateTime.now(),DatePattern.NORM_DATETIME_PATTERN));

        }else {
            param.setEndTime(DateUtil.format(endDate, "yyyy-MM-dd HH:mm:ss"));
        }
        param.setB(day == 0);
        if (Objects.isNull(overLimit)) {
            throw new BusinessException(CommonResponseEnum.FAIL,"限值获取为空");
        }

        String rtfPath;
        String picPath = "file/default.jpg";

        Theme theme = themeFeignClient.getTheme().getData();
        if (theme.getRemark().equals("国网")) {
            rtfPath = "file/reportModelGW.docx";
        } else if (theme.getRemark().equals("南网")) {
            rtfPath = "file/reportModelNW.docx";
        } else if (theme.getRemark().equals("灿能")) {
            rtfPath = "file/reportModelCN.docx";
        } else if (theme.getName().contains("物联")) {
            rtfPath = "file/reportModelWL.docx";
        } else {
            rtfPath = "file/reportModel.docx";
        }

        //获取图片信息
        ClassPathResource picPathResource = null;
        try {
            picPathResource = new ClassPathResource(picPath);
            rtfPath = rtfPath.replaceAll("%20", " ");
        } catch (Exception e1) {
            log.info("获取报表发生异常，异常是" + e1.getMessage());
        }
        //上移提前塞入基波电压基波电流
        getCurrentRate(param, overLimit);
        getVoltageRate(param, overLimit);

        // 报告Map
        Map<String, Object> reportmap = new HashMap<>(16);

        reportmap.putAll(unitMap(deviceUnit));
        reportmap.put("$atype$", atype);
        reportmap.put("$btype$", btype);
        reportmap.put("$ctype$", ctype);


        // ======== 修复后的图片处理核心逻辑 ========
        Map<String, Object> header = handleImageData(file, picPathResource);
        reportmap.put("$image$", header);

        getVirtualData(param);
        // 电压幅值
        ReportValue voltage1 = this.listVirtual.get(0).getList().get(0);
        // 电压幅值
        ReportValue voltage2 = this.listVirtual.get(0).getList().get(1);
        // 电压幅值
        ReportValue voltage3 = this.listVirtual.get(0).getList().get(2);
        // 电流幅值
        ReportValue current1 = this.listVirtual.get(1).getList().get(0);
        // 电流幅值
        ReportValue current2 = this.listVirtual.get(1).getList().get(1);
        // 电流幅值
        ReportValue current3 = this.listVirtual.get(1).getList().get(2);

        String strLineBaseName = String.format("%s%s", new String[]{bdname + "_", name});
        // 分析建议
        String strAnalysis = "";
        // 报表错误
        String strError = "";

        /**************************************************************
         **** 基波电压/电流有效值表格
         * 一、用基波电压和基波电流做是否有值的判断， 判断策略为所有的基波电压和基波电流都为空
         * *************************************
         * ************************************* 二、基本数据判断
         * ①、(最大值>=最小值、平均值、95%概率值) ②、(平均值>=最小值) ③、(95%概率值>=最小值)
         ***************************************************************/
        String strBaseVIResult = "";
        // 基波电压最大值

        reportmap.put("$B" + "V0" + "X" + "_A$", judgeNull(voltage1.getFmaxValue()));
        reportmap.put("$B" + "V0" + "X" + "_B$", judgeNull(voltage2.getFmaxValue()));
        reportmap.put("$B" + "V0" + "X" + "_C$", judgeNull(voltage3.getFmaxValue()));

        // 基波电流最大值
        reportmap.put("$B" + "I0" + "X" + "_A$", dataConversion(current1.getFmaxValue(),dataLevel,ct,true));
        reportmap.put("$B" + "I0" + "X" + "_B$", dataConversion(current2.getFmaxValue(),dataLevel,ct,true));
        reportmap.put("$B" + "I0" + "X" + "_C$", dataConversion(current3.getFmaxValue(),dataLevel,ct,true));

        /**************************************************************
         **** 三张大表基础数据幅值
         ***************************************************************/
        // 基波电压最大值
        reportmap.put("$C" + "V0" + "X" + "_A$", judgeNull(this.listVoltageRate.get(0).getList().get(0).getFmaxValue()));
        reportmap.put("$C" + "V0" + "X" + "_B$", judgeNull(this.listVoltageRate.get(0).getList().get(1).getFmaxValue()));
        reportmap.put("$C" + "V0" + "X" + "_C$", judgeNull(this.listVoltageRate.get(0).getList().get(2).getFmaxValue()));

        // 基波电流最大值
        reportmap.put("$C" + "I0" + "X" + "_A$", judgeNull(this.listICurrent.get(0).getList().get(0).getFmaxValue()));
        reportmap.put("$C" + "I0" + "X" + "_B$", judgeNull(this.listICurrent.get(0).getList().get(1).getFmaxValue()));
        reportmap.put("$C" + "I0" + "X" + "_C$", judgeNull(this.listICurrent.get(0).getList().get(2).getFmaxValue()));

        // 基波电压最小值
        reportmap.put("$B" + "V0" + "N" + "_A$", judgeNull(voltage1.getMinValue()));
        reportmap.put("$B" + "V0" + "N" + "_B$", judgeNull(voltage2.getMinValue()));
        reportmap.put("$B" + "V0" + "N" + "_C$", judgeNull(voltage3.getMinValue()));

        // 基波电流最小值
        reportmap.put("$B" + "I0" + "N" + "_A$", dataConversion(current1.getMinValue(),dataLevel,ct,true));
        reportmap.put("$B" + "I0" + "N" + "_B$", dataConversion(current2.getMinValue(),dataLevel,ct,true));
        reportmap.put("$B" + "I0" + "N" + "_C$", dataConversion(current3.getMinValue(),dataLevel,ct,true));

        /**************************************************************
         **** 三张大表基础数据幅值
         ***************************************************************/
        // 基波电压最小值
        reportmap.put("$C" + "V0" + "N" + "_A$", judgeNull(this.listVoltageRate.get(0).getList().get(0).getMinValue()));
        reportmap.put("$C" + "V0" + "N" + "_B$", judgeNull(this.listVoltageRate.get(0).getList().get(1).getMinValue()));
        reportmap.put("$C" + "V0" + "N" + "_C$", judgeNull(this.listVoltageRate.get(0).getList().get(2).getMinValue()));

        // 基波电流最小值
        reportmap.put("$C" + "I0" + "N" + "_A$", judgeNull(this.listICurrent.get(0).getList().get(0).getMinValue()));
        reportmap.put("$C" + "I0" + "N" + "_B$", judgeNull(this.listICurrent.get(0).getList().get(1).getMinValue()));
        reportmap.put("$C" + "I0" + "N" + "_C$", judgeNull(this.listICurrent.get(0).getList().get(2).getMinValue()));

        // 基波电压平均值
        reportmap.put("$B" + "V0" + "E" + "_A$", judgeNull(voltage1.getMeanValue()));
        reportmap.put("$B" + "V0" + "E" + "_B$", judgeNull(voltage2.getMeanValue()));
        reportmap.put("$B" + "V0" + "E" + "_C$", judgeNull(voltage3.getMeanValue()));

        // 基波电流平均值
        reportmap.put("$B" + "I0" + "E" + "_A$", dataConversion(current1.getMeanValue(),dataLevel,ct,true));
        reportmap.put("$B" + "I0" + "E" + "_B$", dataConversion(current2.getMeanValue(),dataLevel,ct,true));
        reportmap.put("$B" + "I0" + "E" + "_C$", dataConversion(current3.getMeanValue(),dataLevel,ct,true));

        /**************************************************************
         **** 三张大表基础数据幅值
         ***************************************************************/
        // 基波电压平均值
        reportmap.put("$C" + "V0" + "E" + "_A$", judgeNull(this.listVoltageRate.get(0).getList().get(0).getMeanValue()));
        reportmap.put("$C" + "V0" + "E" + "_B$", judgeNull(this.listVoltageRate.get(0).getList().get(1).getMeanValue()));
        reportmap.put("$C" + "V0" + "E" + "_C$", judgeNull(this.listVoltageRate.get(0).getList().get(2).getMeanValue()));

        // 基波电流平均值
        reportmap.put("$C" + "I0" + "E" + "_A$", judgeNull(this.listICurrent.get(0).getList().get(0).getMeanValue()));
        reportmap.put("$C" + "I0" + "E" + "_B$", judgeNull(this.listICurrent.get(0).getList().get(1).getMeanValue()));
        reportmap.put("$C" + "I0" + "E" + "_C$", judgeNull(this.listICurrent.get(0).getList().get(2).getMeanValue()));

        // 基波电压cp95值
        reportmap.put("$B" + "V0" + "%" + "_A$", judgeNull(voltage1.getCp95Value()));
        reportmap.put("$B" + "V0" + "%" + "_B$", judgeNull(voltage2.getCp95Value()));
        reportmap.put("$B" + "V0" + "%" + "_C$", judgeNull(voltage3.getCp95Value()));

        // 基波电流cp95值
        reportmap.put("$B" + "I0" + "%" + "_A$", dataConversion(current1.getCp95Value(),dataLevel,ct,true));
        reportmap.put("$B" + "I0" + "%" + "_B$", dataConversion(current2.getCp95Value(),dataLevel,ct,true));
        reportmap.put("$B" + "I0" + "%" + "_C$", dataConversion(current3.getCp95Value(),dataLevel,ct,true));

        /**************************************************************
         **** 三张大表基础数据幅值
         ***************************************************************/
        // 基波电压cp95值
        reportmap.put("$C" + "V0" + "%" + "_A$", judgeNull(this.listVoltageRate.get(0).getList().get(0).getCp95Value()));
        reportmap.put("$C" + "V0" + "%" + "_B$", judgeNull(this.listVoltageRate.get(0).getList().get(1).getCp95Value()));
        reportmap.put("$C" + "V0" + "%" + "_C$", judgeNull(this.listVoltageRate.get(0).getList().get(2).getCp95Value()));

        // 基波电流cp95值
        reportmap.put("$C" + "I0" + "%" + "_A$", judgeNull(this.listICurrent.get(0).getList().get(0).getCp95Value()));
        reportmap.put("$C" + "I0" + "%" + "_B$", judgeNull(this.listICurrent.get(0).getList().get(1).getCp95Value()));
        reportmap.put("$C" + "I0" + "%" + "_C$", judgeNull(this.listICurrent.get(0).getList().get(2).getCp95Value()));

        // 遍历map中的值
        int iCount = 0;
        // 判断所取的基波电压、基波电流值是否为null
        for (Object value : reportmap.values()) {
            if (value == null)
                iCount++;
        }
        // 假如所有的数据都为null,则返回（所选的时间段内未找到数据）
        if (iCount == reportmap.size()) {
            throw new BusinessException(CommonResponseEnum.FAIL,"范围时间段为空");

        }
        // 基本数据判断
        for (int i = 0; i < 3; i++) {
            String tmpstrMap = "A";
            switch (i) {
                case 0:
                    tmpstrMap = "A";
                    break;
                case 1:
                    tmpstrMap = "B";
                    break;
                default:
                    tmpstrMap = "C";
                    break;
            }
            try {
                // 基波电压
                Double vmaxValue = Double.parseDouble(reportmap.get("$BV0X_" + tmpstrMap + "$").toString());
                Double vminValue = Double.parseDouble(reportmap.get("$BV0N_" + tmpstrMap + "$").toString());
                Double vaveValue = Double.parseDouble(reportmap.get("$BV0E_" + tmpstrMap + "$").toString());
                Double vcp95Value = Double.parseDouble(reportmap.get("$BV0%_" + tmpstrMap + "$").toString());
                // 基波电流
                Double imaxValue = !Objects.equals("Secondary",dataLevel) ? Double.parseDouble(reportmap.get("$BI0X_" + tmpstrMap + "$").toString()):Double.parseDouble(reportmap.get("$BI0X_" + tmpstrMap + "$").toString())*ct;
                Double iminValue = !Objects.equals("Secondary",dataLevel) ? Double.parseDouble(reportmap.get("$BI0N_" + tmpstrMap + "$").toString()):Double.parseDouble(reportmap.get("$BI0N_" + tmpstrMap + "$").toString())*ct;
                Double iaveValue = !Objects.equals("Secondary",dataLevel) ? Double.parseDouble(reportmap.get("$BI0E_" + tmpstrMap + "$").toString()):Double.parseDouble(reportmap.get("$BI0E_" + tmpstrMap + "$").toString())*ct;
                Double icp95Value = !Objects.equals("Secondary",dataLevel) ? Double.parseDouble(reportmap.get("$BI0%_" + tmpstrMap + "$").toString()):Double.parseDouble(reportmap.get("$BI0%_" + tmpstrMap + "$").toString())*ct;

                if (!(vmaxValue >= vminValue && vmaxValue >= vaveValue && vmaxValue >= vcp95Value)) {
                    strBaseVIResult += "注意:从上表中可以看出" + strLineBaseName
                            + "基波电压/电流数据存在异常( 1、最大值>=最小值、平均值、95%概率值；2、平均值>=最小值；3、95%概率值>=最小值)。\r\n";
                    break;
                } else if (vaveValue < vminValue) {
                    strBaseVIResult += "注意:从上表中可以看出" + strLineBaseName
                            + "基波电压/电流数据存在异常( 1、最大值>=最小值、平均值、95%概率值；2、平均值>=最小值；3、95%概率值>=最小值)。\r\n";
                    break;
                } else if (vcp95Value < vminValue) {
                    strBaseVIResult += "注意:从上表中可以看出" + strLineBaseName
                            + "基波电压/电流数据存在异常( 1、最大值>=最小值、平均值、95%概率值；2、平均值>=最小值；3、95%概率值>=最小值)。\r\n";
                    break;
                } else if (!(imaxValue >= iminValue && imaxValue >= iaveValue && imaxValue >= icp95Value)) {
                    strBaseVIResult += "注意:从上表中可以看出" + strLineBaseName
                            + "基波电压/电流数据存在异常( 1、最大值>=最小值、平均值、95%概率值；2、平均值>=最小值；3、95%概率值>=最小值)。\r\n";
                    break;
                } else if (iaveValue < iminValue) {
                    strBaseVIResult += "注意:从上表中可以看出" + strLineBaseName
                            + "基波电压/电流数据存在异常( 1、最大值>=最小值、平均值、95%概率值；2、平均值>=最小值；3、95%概率值>=最小值)。\r\n";
                    break;
                } else if (icp95Value < iminValue) {
                    strBaseVIResult += "注意:从上表中可以看出" + strLineBaseName
                            + "基波电压/电流数据存在异常( 1、最大值>=最小值、平均值、95%概率值；2、平均值>=最小值；3、95%概率值>=最小值)。\r\n";
                    break;
                }
            } catch (Exception e) {
                strBaseVIResult += "注意:从上表中可以看出" + strLineBaseName + "基波电压/电流数据存在异常(不是数值类型)。\r\n";
                break;
            }
        }
        reportmap.put("$BaseVIResult$", strBaseVIResult);
        if (!"".equals(strBaseVIResult))
            strError += strBaseVIResult;

        /**************************************************************
         **** 所选的时间段内有数据存在则进行其他加载
         ***************************************************************/

//        Depts dep = R.getCurrentDept();
//        String detpName = dep.getArea();
        // 区域名称
        reportmap.put("$detpName$", areaName);
        // 获取报告生成时间
        Date currentTime = new Date();
        // 报告日期格式
        SimpleDateFormat dayFormatter = new SimpleDateFormat("yyyy年MM月dd日");
        // 报告时分秒格式
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
        String strTime = String.format("%s——%s。",
                new String[]{DateUtil.format(startDate, "yyyy年MM月dd日 HH时mm分ss秒"),
                        DateUtil.format(endDate, "yyyy年MM月dd日 HH时mm分ss秒")});
        // 报告编号
        if(StrUtil.isNotBlank(reportNumber)){
            reportmap.put("$number$", reportNumber);
        }else {
            reportmap.put("$number$", "");
        }

        // 客户名称
        reportmap.put("$titlePoint$", crmName);
        // 报告生成时间
        reportmap.put("$TitleTime$", dayFormatter.format(currentTime));
        // 报告标题
        reportmap.put("$ReportTitle$",
                String.format("    对该地区%s电能质量在线监测数据进行分析， 以判断电能质量指标是否满足国标。", new String[]{strLineBaseName}));
        // 报告分析时间段
        reportmap.put("$ReportTime$", strTime);
        // 运行数据分析
        reportmap.put("$RunBaseName$", String.format("以下将对%s电能质量统计数据进行分析，数据包括基波电压/电流、谐波电压/电流、电压偏差、三相电压不平衡度、电压闪变、频率偏差。",
                new String[]{strLineBaseName}));
        // 基波电压和电流
        reportmap.put("$BaseVITable$", String.format("报告分析时间段内%s的基波电压/电流分钟统计数据见下表。", new String[]{strLineBaseName}));
        // 供电电压偏差
        reportmap.put("$VDTable$", String.format("报告分析时间段内%s的电压偏差统计数据见下表。", new String[]{strLineBaseName}));
        // 频率偏差
        reportmap.put("$FRETable$", String.format("报告分析时间段内%s的频率偏差统计数据见下表。", new String[]{strLineBaseName}));
        // 三相电压不平衡度
        reportmap.put("$THETable$", String.format("报告分析时间段内%s的三相电压不平衡度统计数据见下表。", new String[]{strLineBaseName}));
        // 闪变
        reportmap.put("$PLTTable$", String.format("报告分析时间段内%s的闪变统计数据见下表。", new String[]{strLineBaseName}));
        // 谐波电压
        reportmap.put("$RVTable$",
                String.format("报告分析时间段内%s的2-25次谐波电压含有率CP95概率值统计数据见下表。", new String[]{strLineBaseName}));
        // 谐波电流
        reportmap.put("$RITable$",
                String.format("报告分析时间段内%s的2-25次谐波电流幅值CP95概率值统计数据见下表。", new String[]{strLineBaseName}));
        // 监测点名称1
        reportmap.put("$LineName1$", name);
        // 监测点名称2
        reportmap.put("$LineName2$", name);
        // 监测点名称3
        reportmap.put("$LineName3$", name);
        // 监测点名称4
        reportmap.put("$LineName4$", name);
        // 监测点名称5
        reportmap.put("$LineName5$", name);

        /**********************
         **** 数据获取
         ***********************/

        getPowerData(param);
        getFlicker(param, overLimit);
        getVdeviation(param, overLimit);
        getDistortion(param, overLimit);
        getFre(param, overLimit);
        getThreePhase(param, overLimit);
//        getVoltageRate(param, overLimit);
//        getCurrentRate(param, overLimit);
        // 短闪
        ReportValue pst1 = this.listFlicker.get(0).getList().get(0);
        // 短闪
        ReportValue pst2 = this.listFlicker.get(0).getList().get(1);
        // 短闪
        ReportValue pst3 = this.listFlicker.get(0).getList().get(2);
        // 长闪
        ReportValue plt1 = this.listFlicker.get(1).getList().get(0);
        // 长闪
        ReportValue plt2 = this.listFlicker.get(1).getList().get(1);
        // 长闪
        ReportValue plt3 = this.listFlicker.get(1).getList().get(2);
        // 监测点基本信息
        reportmap.put("$LineBase$", String.format("%s%s，CT变比为：%s，PT变比为：%s。",
                new String[]{bdname, name, lineDto.getCt(), lineDto.getPt()}));

        /**************************************************************
         **** 三张大表基础数据幅值
         ***************************************************************/
        reportmap.put("$CI_JCD$", bdname);
        reportmap.put("$bdTitle$", bdname);

        reportmap.put("$CI_Time$", strTime);
        reportmap.put("$CI_JCXL$", name);
        reportmap.put("$CI_PT$", lineDto.getPt());
        reportmap.put("$CI_DYDJ$", lineDto.getScale());
        reportmap.put("$CI_CT$", lineDto.getCt());
        reportmap.put("$CI_JZRL$", String.valueOf(lineDto.getStandardCapacity()));
        reportmap.put("$CI_DLRL$", String.valueOf(lineDto.getShortCapacity()));
        reportmap.put("$CI_XYRL$", String.valueOf(lineDto.getDealCapacity()));
        reportmap.put("$CI_SBRL$", String.valueOf(lineDto.getDevCapacity()));

        reportmap.put("$CV_JCD$", bdname);
        reportmap.put("$CV_Time$", strTime);
        reportmap.put("$CV_JCXL$", name);
        reportmap.put("$CV_PT$", lineDto.getPt());
        reportmap.put("$CV_DYDJ$", lineDto.getScale());
        reportmap.put("$CV_CT$", lineDto.getCt());
        reportmap.put("$CV_JZRL$", String.valueOf(lineDto.getStandardCapacity()));
        reportmap.put("$CV_DLRL$", String.valueOf(lineDto.getShortCapacity()));
        reportmap.put("$CV_XYRL$", String.valueOf(lineDto.getDealCapacity()));
        reportmap.put("$CV_SBRL$", String.valueOf(lineDto.getDevCapacity()));

        reportmap.put("$FV_JCD$", bdname);
        reportmap.put("$FV_Time$", strTime);
        reportmap.put("$FV_JCXL$", name);
        reportmap.put("$FV_PT$", lineDto.getPt());
        reportmap.put("$FV_DYDJ$", lineDto.getScale());
        reportmap.put("$FV_CT$", lineDto.getCt());
        reportmap.put("$FV_JZRL$", String.valueOf(lineDto.getStandardCapacity()));
        reportmap.put("$FV_DLRL$", String.valueOf(lineDto.getShortCapacity()));
        reportmap.put("$FV_XYRL$", String.valueOf(lineDto.getDealCapacity()));
        reportmap.put("$FV_SBRL$", String.valueOf(lineDto.getDevCapacity()));

        Double maxValue = 0.00;
        Double minValue = 0.00;
        Double aveValue = 0.00;
        Double cp95Value = 0.00;
        Double cp95ValueA = 0.00;
        Double cp95ValueB = 0.00;
        Double cp95ValueC = 0.00;
        Double limit = 0.00;
        /**************************************************************
         **** 电压偏差（上偏差和下偏差）
         ***************************************************************/
        ReportValue vdeviation1 = this.listVdeviation.get(0).getList().get(0);
        ReportValue vdeviation2 = this.listVdeviation.get(0).getList().get(1);
        ReportValue vdeviation3 = this.listVdeviation.get(0).getList().get(2);
        // 获取电压上下偏差的国标限值
        String vdeviationLimit = judgeNull(this.listVdeviation.get(0).getOverLimit());
        //电压下偏差
        String ldeviationLimit = judgeNull(this.listVdeviation.get(1).getOverLimit());

        reportmap.put("$VD_L$",ldeviationLimit+"至"+ vdeviationLimit);
        String strResultVdeviationdata = "";
        String tmpstrResultVdeviationdata = "";
        String strResultVdeviationdataValue = "";
        String tmpstrMap = "";

        // 获取电压偏差
        // 值错误判断
        for (int i = 0; i < 3; i++) {
            switch (i) {
                case 0:
                    tmpstrMap = "A";
                    break;
                case 1:
                    tmpstrMap = "B";
                    break;
                default:
                    tmpstrMap = "C";
                    break;
            }
            ReportValue vdeviation = this.listVdeviation.get(0).getList().get(i);
            if (Objects.equals("C", tmpstrMap) && pttype == 2) {
                reportmap.put("$VDTX_C$", "-");
                reportmap.put("$VDTN_C$", "-");
                reportmap.put("$VDTE_C$", "-");
                reportmap.put("$VDT%_C$", "-");
                continue;
            } else {
                reportmap.put("$VDTX_" + tmpstrMap + "$", judgeNull(vdeviation.getFmaxValue()));
                reportmap.put("$VDTN_" + tmpstrMap + "$", judgeNull(vdeviation.getMinValue()));
                reportmap.put("$VDTE_" + tmpstrMap + "$", judgeNull(vdeviation.getMeanValue()));
                reportmap.put("$VDT%_" + tmpstrMap + "$", judgeNull(vdeviation.getCp95Value()));
            }
        }
            try {
            for (int i = 0; i < 3; i++) {
                switch (i) {
                    case 0:
                        tmpstrMap = "A";
                        break;
                    case 1:
                        tmpstrMap = "B";
                        break;
                    default:
                        tmpstrMap = "C";
                        break;
                }
//                ReportValue vdeviation = this.listVdeviation.get(0).getList().get(i);
//                if(Objects.equals("C",tmpstrMap)&&pttype == 2){
//                    reportmap.put("$VDTX_C$", "-");
//                    reportmap.put("$VDTN_C$", "-");
//                    reportmap.put("$VDTE_C$", "-");
//                    reportmap.put("$VDT%_C$", "-");
//                    continue;
//                }else {
//                    reportmap.put("$VDTX_" + tmpstrMap + "$", judgeNull(vdeviation.getFmaxValue()));
//                    reportmap.put("$VDTN_" + tmpstrMap + "$", judgeNull(vdeviation.getMinValue()));
//                    reportmap.put("$VDTE_" + tmpstrMap + "$", judgeNull(vdeviation.getMeanValue()));
//                    reportmap.put("$VDT%_" + tmpstrMap + "$", judgeNull(vdeviation.getCp95Value()));
//                }


                // 电压偏差
                Double vmaxValue = Double.parseDouble(reportmap.get("$VDTX_" + tmpstrMap + "$").toString());
                Double vminValue = Double.parseDouble(reportmap.get("$VDTN_" + tmpstrMap + "$").toString());
                Double vaveValue = Double.parseDouble(reportmap.get("$VDTE_" + tmpstrMap + "$").toString());
                Double vcp95Value = Double.parseDouble(reportmap.get("$VDT%_" + tmpstrMap + "$").toString());

                if("".equals(strResultVdeviationdataValue)){
                    if (!(vmaxValue >= vminValue && vmaxValue >= vaveValue && vmaxValue >= vcp95Value)) {
                        strResultVdeviationdataValue += "注意:从上表中可以看出" + strLineBaseName
                                + "电压偏差数据存在异常( 1、最大值>=最小值、平均值、95%概率值；2、平均值>=最小值；3、95%概率值>=最小值)。\r\n";
                    } else if (vaveValue < vminValue) {
                        strResultVdeviationdataValue += "注意:从上表中可以看出" + strLineBaseName
                                + "电压偏差数据存在异常( 1、最大值>=最小值、平均值、95%概率值；2、平均值>=最小值；3、95%概率值>=最小值)。\r\n";
                    } else if (vcp95Value < vminValue) {
                        strResultVdeviationdataValue += "注意:从上表中可以看出" + strLineBaseName
                                + "电压偏差数据数据存在异常( 1、最大值>=最小值、平均值、95%概率值；2、平均值>=最小值；3、95%概率值>=最小值)。\r\n";
                    }
                }

                if(vmaxValue>Double.valueOf(vdeviationLimit)||vmaxValue<Double.valueOf(ldeviationLimit)){
                    if (!"".equals(tmpstrResultVdeviationdata)){
                        tmpstrResultVdeviationdata += "、";
                        tmpstrResultVdeviationdata += tmpstrMap + "相最大值";
                    }else {
                        tmpstrResultVdeviationdata += tmpstrMap + "相最大值";

                    }

                }
                if(vminValue>Double.valueOf(vdeviationLimit)||vminValue<Double.valueOf(ldeviationLimit)){
                    if (!"".equals(tmpstrResultVdeviationdata)){
                        tmpstrResultVdeviationdata += "、";
                        tmpstrResultVdeviationdata += tmpstrMap + "相最小值";
                    }else {
                        tmpstrResultVdeviationdata += tmpstrMap + "相最小值";

                    }

                }
                if(vaveValue>Double.valueOf(vdeviationLimit)||vaveValue<Double.valueOf(ldeviationLimit)){
                    if (!"".equals(tmpstrResultVdeviationdata)){
                        tmpstrResultVdeviationdata += "、";
                        tmpstrResultVdeviationdata += tmpstrMap + "相平均值";
                    }else {
                        tmpstrResultVdeviationdata += tmpstrMap + "相平均值";

                    }

                }
                if(vcp95Value>Double.valueOf(vdeviationLimit)||vcp95Value<Double.valueOf(ldeviationLimit)){
                    if (!"".equals(tmpstrResultVdeviationdata)){
                        tmpstrResultVdeviationdata += "、";
                        tmpstrResultVdeviationdata += tmpstrMap + "相95%概率值";
                    }else {
                        tmpstrResultVdeviationdata += tmpstrMap + "相95%概率值";

                    }

                }
            }

        } catch (Exception e) {
            strResultVdeviationdataValue += "注意:从上表中可以看出" + strLineBaseName + "电压偏差数据存在异常(不是数值类型)。\r\n";
        }

//
//        // 限值判断
//        if (maxValue > limit) {
//            if (!"".equals(tmpstrResultVdeviationdata))
//                tmpstrResultVdeviationdata += "、";
//            tmpstrResultVdeviationdata += tmpstrMap + "相";
//        }

        // 假如为空则所有的都满足
        if ("".equals(tmpstrResultVdeviationdata)&&"".equals(strResultVdeviationdataValue)) {
            strResultVdeviationdata += "从上表中可以看出" + strLineBaseName + "A、B、C三相电压偏差满足国标限值（"+ldeviationLimit+"%至"+vdeviationLimit+"%）的要求。";
        } else {
            strAnalysis += tmpstrResultVdeviationdata + "电压偏差不满足国标限值（"+vdeviationLimit+"）的要求。";
            strResultVdeviationdata += "从上表中可以看出" + strLineBaseName + tmpstrResultVdeviationdata
                    + "电压偏差不满足国标限值（"+ldeviationLimit+"%至"+vdeviationLimit+"%）的要求。";
        }

        reportmap.put("$ResultVdeviationdata$", strResultVdeviationdata);
        reportmap.put("$ResultVdeviationdataValue$", strResultVdeviationdataValue);
        strError += strResultVdeviationdataValue;

        /**************************************************************
         **** 频率偏差
         ***************************************************************/
        ReportValue valueOfFreValue = this.listFrequency.get(1).getList().get(0);
        // 获取频率偏差国标限值
        String valueOfFreLimit = judgeNull(this.listFrequency.get(1).getOverLimit());
        reportmap.put("$FRE_L$", valueOfFreLimit);
        String strResultFre = "";
        String tmpstrResultFre = "";
        String strResultFreValue = "";

        reportmap.put("$FREX$", judgeNull(valueOfFreValue.getFmaxValue()));
        reportmap.put("$FREN$", judgeNull(valueOfFreValue.getMinValue()));
        reportmap.put("$FREE$", judgeNull(valueOfFreValue.getMeanValue()));
        reportmap.put("$FRE%$", judgeNull(valueOfFreValue.getCp95Value()));

        /************************************
         **** 三张大表取值
         **************************************/
        reportmap.put("$FV0L$", valueOfFreLimit);
        reportmap.put("$FV0X$", judgeNull(valueOfFreValue.getFmaxValue()));
        reportmap.put("$FV0N$", judgeNull(valueOfFreValue.getMinValue()));
        reportmap.put("$FV0E$", judgeNull(valueOfFreValue.getMeanValue()));
        reportmap.put("$FV0%$", judgeNull(valueOfFreValue.getCp95Value()));

        try {
            maxValue = Double.parseDouble(valueOfFreValue.getFmaxValue().toString());
            minValue = Double.parseDouble(valueOfFreValue.getMinValue().toString());
            aveValue = Double.parseDouble(valueOfFreValue.getMeanValue().toString());
            cp95Value = Double.parseDouble(valueOfFreValue.getCp95Value().toString());
            limit = Math.abs(Double.parseDouble(valueOfFreLimit));
        } catch (Exception e) {
            strResultFreValue += "注意:从上表中可以看出" + strLineBaseName + "频率偏差数据存在异常(不是数值类型)。\r\n";
        }

        if (Math.abs(maxValue) > limit) {
            tmpstrResultFre += "最大值为：" + valueOfFreValue.getFmaxValue().toString() + deviceUnit.getUnitFrequencyDev();
        }
        if (Math.abs(minValue) > limit) {
            tmpstrResultFre += "最小值为：" + valueOfFreValue.getMinValue().toString() + deviceUnit.getUnitFrequencyDev();
        }
        if (Math.abs(aveValue) > limit) {
            tmpstrResultFre += "平均值为：" + valueOfFreValue.getMeanValue().toString() + deviceUnit.getUnitFrequencyDev();
        }
        if (Math.abs(cp95Value) > limit) {
            tmpstrResultFre += "95%概率值为：" + valueOfFreValue.getCp95Value().toString() + deviceUnit.getUnitFrequencyDev();
        }

        if (!(maxValue >= minValue && maxValue >= aveValue && maxValue >= cp95Value)) {
            strResultFreValue += "注意:从上表中可以看出" + strLineBaseName
                    + "频率偏差数据存在异常( 1、最大值>=最小值、平均值、95%概率值；2、平均值>=最小值；3、95%概率值>=最小值)。\r\n";
        } else if (aveValue < minValue) {
            strResultFreValue += "注意:从上表中可以看出" + strLineBaseName
                    + "频率偏差数据存在异常( 1、最大值>=最小值、平均值、95%概率值；2、平均值>=最小值；3、95%概率值>=最小值)。\r\n";
        } else if (cp95Value < minValue) {
            strResultFreValue += "注意:从上表中可以看出" + strLineBaseName
                    + "频率偏差数据存在异常( 1、最大值>=最小值、平均值、95%概率值；2、平均值>=最小值；3、95%概率值>=最小值)。\r\n";
        }

        if ("".equals(tmpstrResultFre)) {
            // 三张大表取值
            reportmap.put("$FV0R$", "合格");
            strResultFre += "从上表中可以看出" + strLineBaseName + "频率偏差均满足国标限值（±" + valueOfFreLimit + deviceUnit.getUnitFrequencyDev() + "）的要求。";
        } else {
            // 三张大表取值
            reportmap.put("$FV0R$", "不合格");
            strAnalysis += tmpstrResultFre + ",均不满足国标限值（±" + valueOfFreLimit + deviceUnit.getUnitFrequencyDev() + "）的要求。\r\n";
            strResultFre += "从上表中可以看出" + strLineBaseName + "频率偏差" + tmpstrResultFre + ",均不满足国标限值（±" + valueOfFreLimit
                    + deviceUnit.getUnitFrequencyDev() + "）的要求。\r\n";
        }

        reportmap.put("$ResultFre$", strResultFre);
        reportmap.put("$ResultFreValue$", strResultFreValue);
        strError += strResultFreValue;

        /**************************************************************
         **** 三相电压不平衡度
         ***************************************************************/
        ReportValue valueOfThree = this.listThreephase.get(0).getList().get(0);
        // 获取三相电压不平衡度国标限值
        String valueOfThreeLimit = judgeNull(this.listThreephase.get(0).getOverLimit());
        reportmap.put("$THE_L$", valueOfThreeLimit);
        String strResultThree = "";
        String tmpstrResultThree = "";
        String strResultThreeValue = "";
        reportmap.put("$THEX$", judgeNull(valueOfThree.getFmaxValue()));
        reportmap.put("$THEN$", judgeNull(valueOfThree.getMinValue()));
        reportmap.put("$THEE$", judgeNull(valueOfThree.getMeanValue()));
        reportmap.put("$THE%$", judgeNull(valueOfThree.getCp95Value()));

        /************************************
         **** 三张大表取值
         **************************************/
        reportmap.put("$TV0L$", valueOfThreeLimit);
        reportmap.put("$TV0X$", judgeNull(valueOfThree.getFmaxValue()));
        reportmap.put("$TV0N$", judgeNull(valueOfThree.getMinValue()));
        reportmap.put("$TV0E$", judgeNull(valueOfThree.getMeanValue()));
        reportmap.put("$TV0%$", judgeNull(valueOfThree.getCp95Value()));

        try {
            maxValue = Double.parseDouble(valueOfThree.getFmaxValue().toString());
            minValue = Double.parseDouble(valueOfThree.getMinValue().toString());
            aveValue = Double.parseDouble(valueOfThree.getMeanValue().toString());
            cp95Value = Double.parseDouble(valueOfThree.getCp95Value().toString());
            limit = Double.parseDouble(valueOfThreeLimit);
        } catch (Exception e) {
            strResultThreeValue += "注意:从上表中可以看出" + strLineBaseName + "三相电压不平衡度数据存在异常(不是数值类型)。\r\n";
        }
        if (cp95Value > limit) {
            // 三张大表取值
            reportmap.put("$TV0R$", "不合格");
            tmpstrResultThree += "三相电压不平衡度95%概率值为：" + valueOfThree.getCp95Value().toString();
        } else {
            // 三张大表取值
            reportmap.put("$TV0R$", "合格");
        }

        if (!(maxValue >= minValue && maxValue >= aveValue && maxValue >= cp95Value)) {
            strResultThreeValue += "注意:从上表中可以看出" + strLineBaseName
                    + "三相电压不平衡度数据存在异常( 1、最大值>=最小值、平均值、95%概率值；2、平均值>=最小值；3、95%概率值>=最小值)。\r\n";
        } else if (aveValue < minValue) {
            strResultThreeValue += "注意:从上表中可以看出" + strLineBaseName
                    + "三相电压不平衡度数据存在异常( 1、最大值>=最小值、平均值、95%概率值；2、平均值>=最小值；3、95%概率值>=最小值)。\r\n";
        } else if (cp95Value < minValue) {
            strResultThreeValue += "注意:从上表中可以看出" + strLineBaseName
                    + "三相电压不平衡度数据存在异常( 1、最大值>=最小值、平均值、95%概率值；2、平均值>=最小值；3、95%概率值>=最小值)。\r\n";
        }

        if ("".equals(tmpstrResultThree)) {
            strResultThree += "三相电压不平衡度根据国标标准测量结果以95%概率值作为判断是否合格的依据，从上表中可以看出" + strLineBaseName + tmpstrResultThree
                    + "，满足国标限值（" + valueOfThreeLimit + "%）的要求。";
        } else {
            strAnalysis += tmpstrResultThree + "，不满足国标限值（" + valueOfThreeLimit + "%）的要求。";
            strResultThree += "三相电压不平衡度根据国标标准测量结果以95%概率值作为判断是否合格的依据，从上表中可以看出" + strLineBaseName + tmpstrResultThree
                    + "，不满足国标限值（" + valueOfThreeLimit + "%）的要求。";
        }

        reportmap.put("$ResultThree$", strResultThree);
        reportmap.put("$ResultThreeValue$", strResultThreeValue);
        strError += strResultThreeValue;

        /**************************************************************
         **** 电压闪变
         ***************************************************************/
        // 获取电压长时闪变的限值
        String valueOfFlickerLimit = judgeNull(this.listFlicker.get(1).getOverLimit());
        reportmap.put("$PLT_L$", valueOfFlickerLimit);
        String strResultFlicker = "";
        String tmpstrResultFlicker = "";
        String strResultFlickerValue = "";
        Double fmaxValue1 = 0.0;
        Double fmaxValue2 = 0.0;
        Double fmaxValue3 = 0.0;
        Double flickerLimit = 0.0;
        try {
            fmaxValue1 = Double.parseDouble(plt1.getFmaxValue().toString());
            fmaxValue2 = Double.parseDouble(plt2.getFmaxValue().toString());
            fmaxValue3 = Double.parseDouble(plt3.getFmaxValue().toString());
            flickerLimit = Double.parseDouble(valueOfFlickerLimit);
        } catch (Exception e) {
            strResultFlickerValue += "注意:从上表中可以看出" + strLineBaseName + "长时闪变数据存在异常(不是数值类型)。\r\n";
        }
        if (fmaxValue1 > flickerLimit) {
            if (!"".equals(tmpstrResultFlicker))
                tmpstrResultFlicker += ",";
            tmpstrResultFlicker += atype + "最大值为：" + plt1.getFmaxValue().toString();
            reportmap.put("$" + "L" + "V0R_" + "A" + "$", "不合格");
        } else {
            reportmap.put("$" + "L" + "V0R_" + "A" + "$", "合格");
        }

        if (fmaxValue2 > flickerLimit) {
            if (!"".equals(tmpstrResultFlicker))
                tmpstrResultFlicker += ",";
            tmpstrResultFlicker += btype + "最大值为：" + plt2.getFmaxValue().toString();
            reportmap.put("$" + "L" + "V0R_" + "B" + "$", "不合格");
        } else {
            reportmap.put("$" + "L" + "V0R_" + "B" + "$", "合格");
        }

        if (fmaxValue3 > flickerLimit && pttype != 2) {
            if (!"".equals(tmpstrResultFlicker))
                tmpstrResultFlicker += ",";
            tmpstrResultFlicker += ctype + "最大值为：" + plt3.getFmaxValue().toString();
            reportmap.put("$" + "L" + "V0R_" + "C" + "$", "不合格");
        } else {
            reportmap.put("$" + "L" + "V0R_" + "C" + "$", "合格");
        }

        reportmap.put("$PSTX_A$", judgeNull(pst1.getFmaxValue()));
        reportmap.put("$PSTN_A$", judgeNull(pst1.getMinValue()));
        reportmap.put("$PSTE_A$", judgeNull(pst1.getMeanValue()));
        reportmap.put("$PST%_A$", judgeNull(pst1.getCp95Value()));
        reportmap.put("$PSTX_B$", judgeNull(pst2.getFmaxValue()));
        reportmap.put("$PSTN_B$", judgeNull(pst2.getMinValue()));
        reportmap.put("$PSTE_B$", judgeNull(pst2.getMeanValue()));
        reportmap.put("$PST%_B$", judgeNull(pst2.getCp95Value()));
        if (pttype != 2) {
            reportmap.put("$PSTX_C$", judgeNull(pst3.getFmaxValue()));
            reportmap.put("$PSTN_C$", judgeNull(pst3.getMinValue()));
            reportmap.put("$PSTE_C$", judgeNull(pst3.getMeanValue()));
            reportmap.put("$PST%_C$", judgeNull(pst3.getCp95Value()));
        } else {
            reportmap.put("$PSTX_C$", "-");
            reportmap.put("$PSTN_C$", "-");
            reportmap.put("$PSTE_C$", "-");
            reportmap.put("$PST%_C$", "-");
        }

        reportmap.put("$PLTX_A$", judgeNull(plt1.getFmaxValue()));
        reportmap.put("$PLTN_A$", judgeNull(plt1.getMinValue()));
        reportmap.put("$PLTE_A$", judgeNull(plt1.getMeanValue()));
        reportmap.put("$PLT%_A$", judgeNull(plt1.getCp95Value()));
        reportmap.put("$PLTX_B$", judgeNull(plt2.getFmaxValue()));
        reportmap.put("$PLTN_B$", judgeNull(plt2.getMinValue()));
        reportmap.put("$PLTE_B$", judgeNull(plt2.getMeanValue()));
        reportmap.put("$PLT%_B$", judgeNull(plt2.getCp95Value()));
        if (pttype != 2) {
            reportmap.put("$PLTX_C$", judgeNull(plt3.getFmaxValue()));
            reportmap.put("$PLTN_C$", judgeNull(plt3.getMinValue()));
            reportmap.put("$PLTE_C$", judgeNull(plt3.getMeanValue()));
            reportmap.put("$PLT%_C$", judgeNull(plt3.getCp95Value()));
        } else {
            reportmap.put("$PLTX_C$", "-");
            reportmap.put("$PLTN_C$", "-");
            reportmap.put("$PLTE_C$", "-");
            reportmap.put("$PLT%_C$", "-");
        }
        reportmap.put("$PLT_L$", valueOfFlickerLimit);

        /************************************
         **** 三张大表取值
         **************************************/
        reportmap.put("$" + "L" + "V0" + "X" + "_" + "A" + "$", judgeNull(plt1.getFmaxValue()));
        reportmap.put("$" + "L" + "V0" + "E" + "_" + "A" + "$", judgeNull(plt1.getMeanValue()));
        reportmap.put("$" + "L" + "V0" + "N" + "_" + "A" + "$", judgeNull(plt1.getMinValue()));
        reportmap.put("$" + "L" + "V0" + "%" + "_" + "A" + "$", judgeNull(plt1.getCp95Value()));
        reportmap.put("$" + "L" + "V0" + "X" + "_" + "B" + "$", judgeNull(plt2.getFmaxValue()));
        reportmap.put("$" + "L" + "V0" + "E" + "_" + "B" + "$", judgeNull(plt2.getMeanValue()));
        reportmap.put("$" + "L" + "V0" + "N" + "_" + "B" + "$", judgeNull(plt2.getMinValue()));
        reportmap.put("$" + "L" + "V0" + "%" + "_" + "B" + "$", judgeNull(plt2.getCp95Value()));
        reportmap.put("$" + "L" + "V0" + "X" + "_" + "C" + "$", judgeNull(plt3.getFmaxValue()));
        reportmap.put("$" + "L" + "V0" + "E" + "_" + "C" + "$", judgeNull(plt3.getMeanValue()));
        reportmap.put("$" + "L" + "V0" + "N" + "_" + "C" + "$", judgeNull(plt3.getMinValue()));
        reportmap.put("$" + "L" + "V0" + "%" + "_" + "C" + "$", judgeNull(plt3.getCp95Value()));
        reportmap.put("$LV0%_L$", valueOfFlickerLimit);

        reportmap.put("$" + "S" + "V0" + "X" + "_" + "A" + "$", judgeNull(pst1.getFmaxValue()));
        reportmap.put("$" + "S" + "V0" + "E" + "_" + "A" + "$", judgeNull(pst1.getMeanValue()));
        reportmap.put("$" + "S" + "V0" + "N" + "_" + "A" + "$", judgeNull(pst1.getMinValue()));
        reportmap.put("$" + "S" + "V0" + "%" + "_" + "A" + "$", judgeNull(pst1.getCp95Value()));
        reportmap.put("$" + "S" + "V0" + "X" + "_" + "B" + "$", judgeNull(pst2.getFmaxValue()));
        reportmap.put("$" + "S" + "V0" + "E" + "_" + "B" + "$", judgeNull(pst2.getMeanValue()));
        reportmap.put("$" + "S" + "V0" + "N" + "_" + "B" + "$", judgeNull(pst2.getMinValue()));
        reportmap.put("$" + "S" + "V0" + "%" + "_" + "B" + "$", judgeNull(pst2.getCp95Value()));
        reportmap.put("$" + "S" + "V0" + "X" + "_" + "C" + "$", judgeNull(pst3.getFmaxValue()));
        reportmap.put("$" + "S" + "V0" + "E" + "_" + "C" + "$", judgeNull(pst3.getMeanValue()));
        reportmap.put("$" + "S" + "V0" + "N" + "_" + "C" + "$", judgeNull(pst3.getMinValue()));
        reportmap.put("$" + "S" + "V0" + "%" + "_" + "C" + "$", judgeNull(pst3.getCp95Value()));

        if ("".equals(tmpstrResultFlicker)) {
            strResultFlicker += "电压长时闪变根据国标标准测量结果以最大值、最小值、95%概率值作为判断是否合格的依据，从上表中可以看出" + strLineBaseName + "长时闪变"
                    + tmpstrResultFlicker + "，其满足国标限值（" + valueOfFlickerLimit + "）的要求。";
        } else {
            strAnalysis += "长时闪变" + tmpstrResultFlicker + "，其不满足国标限值（" + valueOfFlickerLimit + "）的要求。";
            strResultFlicker += "电压长时闪变根据国标标准测量结果以最大值、最小值、95%概率值作为判断是否合格的依据，从上表中可以看出" + strLineBaseName + "长时闪变"
                    + tmpstrResultFlicker + "，其不满足国标限值（" + valueOfFlickerLimit + "）的要求。";
        }

        reportmap.put("$ResultFlicker$", strResultFlicker);
        reportmap.put("$ResultFlickerValue$", strResultFlickerValue);
        strError += strResultFlickerValue;

        /**************************************************************
         **** 电压含有率
         ***************************************************************/
        String strResultVoltageRate = "";
        String tmpstrResultVoltageRate = "";
        String strResultVoltageRateValue = "";
        String strCurrentA, strCurrentB, strCurrentC, strLimit;
        // 获取25次谐波
        for (int i = 1; i < 25; i++) {
            String strMap = "$RV";
            String strCurrentRate = strMap + (i + 1) + "%";

            // 基波电压含有率
            strCurrentA = judgeNull((this.listVoltageRate.get(i).getList().get(0)).getCp95Value());
            strCurrentB = judgeNull((this.listVoltageRate.get(i).getList().get(1)).getCp95Value());
            strCurrentC = judgeNull((this.listVoltageRate.get(i).getList().get(2)).getCp95Value());
            strLimit = judgeNull(this.listVoltageRate.get(i).getOverLimit());

            reportmap.put(strCurrentRate + "_A$", strCurrentA);
            reportmap.put(strCurrentRate + "_B$", strCurrentB);
            if (pttype != 2) {
                reportmap.put(strCurrentRate + "_C$", strCurrentC);
            } else {
                reportmap.put(strCurrentRate + "_C$", "-");
            }
            reportmap.put(strCurrentRate + "_L$", strLimit);

            /************************************
             **** 三张大表取值
             **************************************/
            reportmap.put("$CV" + (i + 1) + "X_A$",
                    judgeNull((this.listVoltageRate.get(i).getList().get(0)).getFmaxValue()));
            reportmap.put("$CV" + (i + 1) + "X_B$",
                    judgeNull((this.listVoltageRate.get(i).getList().get(1)).getFmaxValue()));

            reportmap.put("$CV" + (i + 1) + "N_A$",
                    judgeNull((this.listVoltageRate.get(i).getList().get(0)).getMinValue()));
            reportmap.put("$CV" + (i + 1) + "N_B$",
                    judgeNull((this.listVoltageRate.get(i).getList().get(1)).getMinValue()));

            reportmap.put("$CV" + (i + 1) + "E_A$",
                    judgeNull((this.listVoltageRate.get(i).getList().get(0)).getMeanValue()));
            reportmap.put("$CV" + (i + 1) + "E_B$",
                    judgeNull((this.listVoltageRate.get(i).getList().get(1)).getMeanValue()));

            if (pttype != 2) {
                reportmap.put("$CV" + (i + 1) + "X_C$",
                        judgeNull((this.listVoltageRate.get(i).getList().get(2)).getFmaxValue()));
                reportmap.put("$CV" + (i + 1) + "N_C$",
                        judgeNull((this.listVoltageRate.get(i).getList().get(2)).getMinValue()));
                reportmap.put("$CV" + (i + 1) + "E_C$",
                        judgeNull((this.listVoltageRate.get(i).getList().get(2)).getMeanValue()));
                reportmap.put("$CV" + (i + 1) + "%_C$", strCurrentC);
            } else {
                reportmap.put("$CV" + (i + 1) + "X_C$", "-");
                reportmap.put("$CV" + (i + 1) + "N_C$", "-");
                reportmap.put("$CV" + (i + 1) + "E_C$", "-");
                reportmap.put("$CV" + (i + 1) + "%_C$", "-");
            }

            reportmap.put("$CV" + (i + 1) + "%_A$", strCurrentA);
            reportmap.put("$CV" + (i + 1) + "%_B$", strCurrentB);
            reportmap.put("$CV" + (i + 1) + "L$", strLimit);

            try {
                maxValue = Double.parseDouble(strCurrentA);
                minValue = Double.parseDouble(strCurrentB);
                aveValue = Double.parseDouble(strCurrentC);
                limit = Double.parseDouble(strLimit);
            } catch (Exception e) {
                strResultVoltageRateValue += "注意:从上表中可以看出" + strLineBaseName + (i+1)+"次谐波电压含有率95%概率值数据存在异常(不是数值类型)。\r\n";
            }

            String tmpstrResult = "";
            if (maxValue > limit) {
                if (!"".equals(tmpstrResult)) {
                    tmpstrResult += "、";
                }
                tmpstrResult += "A";
                // 三张大表取值
                reportmap.put("$CV" + (i + 1) + "R_A$", "不合格");
            } else {
                // 三张大表取值
                reportmap.put("$CV" + (i + 1) + "R_A$", "合格");
            }
            if (minValue > limit) {
                if (!"".equals(tmpstrResult)) {
                    tmpstrResult += "、";
                }
                tmpstrResult += "B";
                // 三张大表取值
                reportmap.put("$CV" + (i + 1) + "R_B$", "不合格");
            } else {
                // 三张大表取值
                reportmap.put("$CV" + (i + 1) + "R_B$", "合格");
            }
            if (aveValue > limit) {
                if (!"".equals(tmpstrResult)) {
                    tmpstrResult += "、";
                }
                tmpstrResult += "C";
                // 三张大表取值
                reportmap.put("$CV" + (i + 1) + "R_C$", "不合格");
            } else {
                // 三张大表取值
                reportmap.put("$CV" + (i + 1) + "R_C$", "合格");
            }
            // 判断单个结论是否存在
            if (!"".equals(tmpstrResult)) {
                tmpstrResultVoltageRate += (i + 1) + "次谐波电压含有率95%概率值" + tmpstrResult + ";\r\n";
            }
        }

        // 假如为空则所有的都满足
        if ("".equals(tmpstrResultVoltageRate)) {
            strResultVoltageRate += "从上表中可以看出" + strLineBaseName + "2-25次谐波电压含有率95%概率值均满足国标限值要求。\r\n";
        } else {
            strAnalysis += tmpstrResultVoltageRate + "2-25次谐波电压含有率95%概率值均不满足国标限值要求。\r\n";
            strResultVoltageRate += "从上表中可以看出" + strLineBaseName + "\r\n"+tmpstrResultVoltageRate + "均不满足国标限值要求。\r\n";
        }

        /**************************************************************
         **** 电压总谐波畸变率(THD)
         ***************************************************************/
        ReportValue distortion1 = this.listDistortion.get(0).getList().get(0);
        ReportValue distortion2 = this.listDistortion.get(0).getList().get(1);
        ReportValue distortion3 = this.listDistortion.get(0).getList().get(2);
        String distortionLimit = judgeNull(this.listDistortion.get(0).getOverLimit());
        reportmap.put("$DV0%_L$", distortionLimit);

        String strResultDistortion = "";
        String tmpstrResultDistortion = "";
        String strResultDistortionValue = "";

        reportmap.put("$DV0%_A$", judgeNull(distortion1.getCp95Value()));
        reportmap.put("$DV0%_B$", judgeNull(distortion2.getCp95Value()));
        reportmap.put("$DV0%_C$", judgeNull(distortion3.getCp95Value()));

        /************************************
         **** 三张大表取值
         **************************************/
        reportmap.put("$TV0X_L$", distortionLimit);
        reportmap.put("$TV0X_A$", judgeNull(distortion1.getFmaxValue()));
        reportmap.put("$TV0E_A$", judgeNull(distortion1.getMeanValue()));
        reportmap.put("$TV0N_A$", judgeNull(distortion1.getMinValue()));
        reportmap.put("$TV0%_A$", judgeNull(distortion1.getCp95Value()));

        reportmap.put("$TV0X_B$", judgeNull(distortion2.getFmaxValue()));
        reportmap.put("$TV0E_B$", judgeNull(distortion2.getMeanValue()));
        reportmap.put("$TV0N_B$", judgeNull(distortion2.getMinValue()));
        reportmap.put("$TV0%_B$", judgeNull(distortion2.getCp95Value()));

        reportmap.put("$TV0X_C$", judgeNull(distortion3.getFmaxValue()));
        reportmap.put("$TV0E_C$", judgeNull(distortion3.getMeanValue()));
        reportmap.put("$TV0N_C$", judgeNull(distortion3.getMinValue()));
        reportmap.put("$TV0%_C$", judgeNull(distortion3.getCp95Value()));

        // 值错误判断
        try {
            cp95ValueA = Math.abs(Double.parseDouble(distortion1.getCp95Value().toString()));
            cp95ValueB = Math.abs(Double.parseDouble(distortion2.getCp95Value().toString()));
            cp95ValueC = Math.abs(Double.parseDouble(distortion3.getCp95Value().toString()));
            limit = Math.abs(Double.parseDouble(distortionLimit));
        } catch (Exception e) {
            strResultDistortionValue += "注意:从上表中可以看出" + strLineBaseName + "电压总谐波畸变率(THD)数据存在异常(不是数值类型)。\r\n";
        }
        // 限值判断
        if (cp95ValueA > limit) {
            if (!"".equals(tmpstrResultDistortion)) {
                tmpstrResultDistortion += "、";
            }
            tmpstrResultDistortion += atype;
            // 三张大表取值
            reportmap.put("$TV0R_A$", "不合格");
        } else {
            // 三张大表取值
            reportmap.put("$TV0R_A$", "合格");
        }
        if (cp95ValueB > limit) {
            if (!"".equals(tmpstrResultDistortion)) {
                tmpstrResultDistortion += "、";
            }
            tmpstrResultDistortion += btype;
            // 三张大表取值
            reportmap.put("$TV0R_B$", "不合格");
        } else {
            // 三张大表取值
            reportmap.put("$TV0R_B$", "合格");
        }
        if (cp95ValueC > limit && pttype != 2) {
            if (!"".equals(tmpstrResultDistortion)) {
                tmpstrResultDistortion += "、";
            }
            tmpstrResultDistortion += ctype;
            // 三张大表取值
            reportmap.put("$TV0R_C$", "不合格");
        } else {
            // 三张大表取值
            reportmap.put("$TV0R_C$", "合格");
        }
        strError += strResultVoltageRateValue + strResultDistortionValue;
        // 假如为空则所有的都满足
        if ("".equals(tmpstrResultDistortion) && "".equals(strResultDistortionValue)) {
            strResultDistortion += "电压总谐波畸变率(THD)95%概率值均满足国标限值要求。\r\n";
            reportmap.put("$ResultVoltageRateValue$", "");
        } else {
            strAnalysis += "电压总谐波畸变率(THD)95%概率值" + tmpstrResultDistortion + "均不满足国标限值要求。\r\n";
            strResultDistortion += "电压总谐波畸变率(THD)95%概率值" + tmpstrResultDistortion + "均不满足国标限值要求。\r\n";
            reportmap.put("$ResultVoltageRateValue$", strError);
        }
        reportmap.put("$ResultVoltageRate$", strResultVoltageRate + strResultDistortion);




        /**************************************************************
         **** 谐波电流幅值
         ***************************************************************/
        String strResultCurrent = "";
        String tmpstrResultCurrent = "";
        String strResultCurrentValue = "";
        // 获取25次谐波
        for (int i = 1; i < 25; i++) {
            String strMap = "$RI";
            String strCurrent = strMap + (i + 1) + "%";

            // 谐波电流幅值
//            strCurrentA = judgeNull(this.listICurrent.get(i).getList().get(0).getCp95Value());
//            strCurrentB = judgeNull(this.listICurrent.get(i).getList().get(1).getCp95Value());
//            strCurrentC = judgeNull(this.listICurrent.get(i).getList().get(2).getCp95Value());
            strCurrentA = dataConversion(this.listICurrent.get(i).getList().get(0).getCp95Value(),dataLevel,ct,true);
            strCurrentB = dataConversion(this.listICurrent.get(i).getList().get(1).getCp95Value(),dataLevel,ct,true);
            strCurrentC = dataConversion(this.listICurrent.get(i).getList().get(2).getCp95Value(),dataLevel,ct,true);
            strLimit = judgeNull(this.listICurrent.get(i).getOverLimit());

            reportmap.put(strCurrent + "_A$", strCurrentA);
            reportmap.put(strCurrent + "_B$", strCurrentB);
            reportmap.put(strCurrent + "_C$", strCurrentC);
            reportmap.put(strCurrent + "_L$", strLimit);

            /************************************
             **** 三张大表取值
             **************************************/
            reportmap.put("$CI" + (i + 1) + "X_A$", judgeNull(this.listICurrent.get(i).getList().get(0).getFmaxValue()));
            reportmap.put("$CI" + (i + 1) + "X_B$", judgeNull(this.listICurrent.get(i).getList().get(1).getFmaxValue()));
            reportmap.put("$CI" + (i + 1) + "X_C$", judgeNull(this.listICurrent.get(i).getList().get(2).getFmaxValue()));

            reportmap.put("$CI" + (i + 1) + "N_A$", judgeNull(this.listICurrent.get(i).getList().get(0).getMinValue()));
            reportmap.put("$CI" + (i + 1) + "N_B$", judgeNull(this.listICurrent.get(i).getList().get(1).getMinValue()));
            reportmap.put("$CI" + (i + 1) + "N_C$", judgeNull(this.listICurrent.get(i).getList().get(2).getMinValue()));

            reportmap.put("$CI" + (i + 1) + "E_A$", judgeNull(this.listICurrent.get(i).getList().get(0).getMeanValue()));
            reportmap.put("$CI" + (i + 1) + "E_B$", judgeNull(this.listICurrent.get(i).getList().get(1).getMeanValue()));
            reportmap.put("$CI" + (i + 1) + "E_C$", judgeNull(this.listICurrent.get(i).getList().get(2).getMeanValue()));

            reportmap.put("$CI" + (i + 1) + "%_A$", strCurrentA);
            reportmap.put("$CI" + (i + 1) + "%_B$", strCurrentB);
            reportmap.put("$CI" + (i + 1) + "%_C$", strCurrentC);
            reportmap.put("$CI" + (i + 1) + "L$", strLimit);

            try {
                maxValue = Objects.equals("Secondary",dataLevel) ? Double.parseDouble(strCurrentA)*ct : Double.parseDouble(strCurrentA);
                minValue = Objects.equals("Secondary",dataLevel) ? Double.parseDouble(strCurrentB)*ct : Double.parseDouble(strCurrentB);
                aveValue = Objects.equals("Secondary",dataLevel) ? Double.parseDouble(strCurrentC)*ct : Double.parseDouble(strCurrentC);;
                limit = Double.parseDouble(strLimit);
            } catch (Exception e) {
                strResultCurrentValue += "注意:从上表中可以看出" + strLineBaseName +(i + 1)+ "次谐波电流幅值95%概率值数据存在异常(不是数值类型)。\r\n";
            }

            String tmpstrResult = "";
            if (maxValue > limit) {
                if (!"".equals(tmpstrResult)) {
                    tmpstrResult += "、";
                }
                tmpstrResult += "A";
                // 三张大表取值
                reportmap.put("$CI" + (i + 1) + "R_A$", "不合格");
            } else {
                // 三张大表取值
                reportmap.put("$CI" + (i + 1) + "R_A$", "合格");
            }
            if (minValue > limit) {
                if (!"".equals(tmpstrResult)) {
                    tmpstrResult += "、";
                }
                tmpstrResult += "B";
                // 三张大表取值
                reportmap.put("$CI" + (i + 1) + "R_B$", "不合格");
            } else {
                // 三张大表取值
                reportmap.put("$CI" + (i + 1) + "R_B$", "合格");
            }
            if (aveValue > limit) {
                if (!"".equals(tmpstrResult)) {
                    tmpstrResult += "、";
                }
                tmpstrResult += "C";
                // 三张大表取值
                reportmap.put("$CI" + (i + 1) + "R_C$", "不合格");
            } else {
                // 三张大表取值
                reportmap.put("$CI" + (i + 1) + "R_C$", "合格");
            }
            // 判断单个结论是否存在
            if (!"".equals(tmpstrResult)) {
                tmpstrResultCurrent += (i + 1) + "次谐波电流幅值95%概率值" + tmpstrResult + ";\r\n";
            }
        }
        strError += strResultCurrentValue;
        // 假如为空则所有的都满足
        if ("".equals(tmpstrResultCurrent) && "".equals(strResultCurrentValue)) {
            strResultCurrent += "从上表中可以看出" + strLineBaseName + "\r\n2-25次谐波电流幅值95%概率值均满足国标限值要求。\r\n";
            reportmap.put("$ResultCurrentValue$", "");
        } else {
            strAnalysis += tmpstrResultCurrent + "均不满足国标限值要求。";
            strResultCurrent += "从上表中可以看出" + strLineBaseName + tmpstrResultCurrent + "均不满足国标限值要求。\r\n";
            reportmap.put("$ResultCurrentValue$", strError);

        }

        reportmap.put("$ResultCurrent$", strResultCurrent);

        // 测试结果填写
        reportmap.put("$ResultTitle$", String.format("通过对（%s——%s）时间段内%s电能质量统计数据分析后得出以下结论：",
                new String[]{DateUtil.format(startDate, "yyyy年MM月dd日 HH时mm分ss秒"),
                        DateUtil.format(endDate, "yyyy年MM月dd日 HH时mm分ss秒"), strLineBaseName}));

        // 电压偏差
        reportmap.put("$Result_VD$", String.format("（1）电压偏差：%s", new String[]{strResultVdeviationdata}));
        // 频率偏差
        reportmap.put("$Result_FRE$", String.format("（2）频率偏差：%s", new String[]{strResultFre}));
        // 三相电压不平衡度
        reportmap.put("$Result_THE$", String.format("（3）三相电压不平衡度：%s", new String[]{strResultThree}));
        // 电压长时闪变
        reportmap.put("$Result_FIC$", String.format("（4）电压长时闪变：%s", new String[]{strResultFlicker}));
        // 谐波电压
        reportmap.put("$Result_VOL$", String.format("（5）谐波电压：%s", new String[]{strResultVoltageRate}));
        // 谐波电流
        reportmap.put("$Result_CUR$", String.format("（6）谐波电流：%s", new String[]{strResultCurrent}));
        // 分析建议填写
        if (!"".equals(strAnalysis) || !"".equals(strError)) {
            // 分析建议
            reportmap.put("$Analysis$", "根据统计数据结果分析,监测点为：" + name + "," + strAnalysis + strError);
        } else {
            // 分析建议
            reportmap.put("$Analysis$", "根据统计数据结果分析,监测点为：" + name + "，电能质量数据满足国标限值要求。");
        }

        /************************************
         **** 三张大表取值 有功:0-11 无功:12-23 视在:24-31 基波有功汇总:32-35 基波无功汇总:36-39
         * 基波视在汇总:40-43 功率因数:44-46
         **************************************/
        ReportValue powerDto1 = this.listPower.get(0).getList().get(3);
        ReportValue powerDto2 = this.listPower.get(1).getList().get(3);
        ReportValue powerDto3 = this.listPower.get(2).getList().get(3);
        ReportValue powerDto4 = this.listPower.get(3).getList().get(3);
        reportmap.put("$BF0X$", judgeNull(powerDto1.getFmaxValue()));
        reportmap.put("$BF0N$", judgeNull(powerDto1.getMinValue()));
        reportmap.put("$BF0E$", judgeNull(powerDto1.getMeanValue()));

        reportmap.put("$NF0X$", judgeNull(powerDto2.getFmaxValue()));
        reportmap.put("$NF0N$", judgeNull(powerDto2.getMinValue()));
        reportmap.put("$NF0E$", judgeNull(powerDto2.getMeanValue()));

        reportmap.put("$SF0X$", judgeNull(powerDto3.getFmaxValue()));
        reportmap.put("$SF0N$", judgeNull(powerDto3.getMinValue()));
        reportmap.put("$SF0E$", judgeNull(powerDto3.getMeanValue()));

        reportmap.put("$YF0X$", judgeNull(powerDto4.getFmaxValue()));
        reportmap.put("$YF0N$", judgeNull(powerDto4.getMinValue()));
        reportmap.put("$YF0E$", judgeNull(powerDto4.getMeanValue()));
        // 报告时分秒格式
        formatter = new SimpleDateFormat("yyyyMMddHHmmss");

        String reportFileUrl = "";
        try {
            String fileName = name + formatter.format(currentTime) + ".docx";
            if(ObjectUtil.isNotNull(isUrl)){
                if (isUrl) {
                    reportFileUrl = wordUtil2.getReportFileUrl(rtfPath, name + formatter.format(currentTime) + ".docx",null ,reportmap);
                }
            }
            wordUtil2.getWord(rtfPath, reportmap, fileName,null, response);
        } catch (Exception e) {
            log.error("获取报告发生异常，异常是" + e.getMessage());
        }
    }

    public Double getData(String data) {
        double ratio = 1.0;
        if (Objects.isNull(data) || data.isEmpty()) {
            return ratio;
        }
        String[] parts = data.split("/");
        if (parts.length == 2) {
            try {
                Double num1 = Double.parseDouble(parts[0]);
                Double num2 = Double.parseDouble(parts[1]);
                ratio = num1 / num2;
            } catch (NumberFormatException var7) {
                System.out.println("字符串格式错误");
            }
        } else {
            ratio = Double.parseDouble(parts[0]);
        }
        return ratio;
    }

    /**
     * 数据单位信息 重组
     *
     * @param deviceUnit 数据单位对象
     * @return
     */
    private Map<String, String> unitMap(DeviceUnitCommDTO deviceUnit) {
        List<DictData> dictData = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.DEVICE_UNIT.getCode()).getData();
        Map<String, String> unit = new HashMap<>(16);
        List<String> list = dictData.stream().map(DictData::getCode).collect(Collectors.toList());
        for (String s : list) {
            //有效值
            if (s.equals(DicDataEnum.EFFECTIVE.getCode())) {
                unit.put("$" + s + "_i$", deviceUnit.getIeffective());
                unit.put("$" + s + "_v$", deviceUnit.getLineVoltage());
            }
            //功率
            if (s.equals(DicDataEnum.POWER.getCode())) {
                unit.put("$" + s + "_p$", deviceUnit.getTotalActiveP());
                unit.put("$" + s + "_q$", deviceUnit.getTotalNoP());
                unit.put("$" + s + "_s$", deviceUnit.getTotalViewP());
            }
            //畸变率
            if (s.equals(DicDataEnum.DISTORTION.getCode())) {
                unit.put("$" + s + "_v$", deviceUnit.getVdistortion());
            }
            //电压偏差
            if (s.equals(DicDataEnum.VOLTAGE.getCode())) {
                unit.put("$" + s + "_v$", deviceUnit.getVoltageDev());
            }
            //频率
            if (s.equals(DicDataEnum.UNIT_FREQUENCY.getCode())) {
                unit.put("$" + s + "_freq$", deviceUnit.getUnitFrequency());
                unit.put("$" + s + "_freqDev$", deviceUnit.getUnitFrequencyDev());
            }
            //三项不平衡度
            if (s.equals(DicDataEnum.UNBALANCE.getCode())) {
                unit.put("$" + s + "_v$", "%");
                unit.put("$" + s + "_vPos$", deviceUnit.getPositiveV());
                unit.put("$" + s + "_vNeg$", deviceUnit.getNoPositiveV());
                unit.put("$" + s + "_vZero$", deviceUnit.getNoPositiveV());
                unit.put("$" + s + "_i$", "%");
                unit.put("$" + s + "_iPos$", "A");
                unit.put("$" + s + "_iNeg$", "A");
                unit.put("$" + s + "_iZero$", "A");
            }
            //基波
            if (s.equals(DicDataEnum.FUND.getCode())) {
                unit.put("$" + s + "_i$", deviceUnit.getIfund());
                unit.put("$" + s + "_v$", deviceUnit.getVfundEffective());

            }
        }
        return unit;
    }


    /**
     * 解析base64，返回图片所在路径
     */
    @SuppressWarnings("restriction")
    private String decodeBase64(byte[] base64Info) {
        if (base64Info.length == 0) {
            return null;
        }
        BASE64Encoder decoder = new BASE64Encoder();

        return decoder.encode(base64Info);
    }

    private void transformData(List<ReportTarget> list, List<ReportValue> listValue, List<Pass> listOverlimit, boolean... b) {
        int offset = b[0] ? 3 : 1;
        offset = (b.length == 2 && !b[1]) ? 4 : offset;
        int i = 0;

        for (int index = 0; index < listValue.size(); index += offset) {
            if (i == listOverlimit.size()) {
                break;
            }
            ReportTarget reportTarget = new ReportTarget();
            reportTarget.setList(listValue.subList(index, index + offset));
            Float overLimit = listOverlimit.get(i).getOverLimit();
            reportTarget.setOverLimit(overLimit);

            switch (listOverlimit.get(i).getCode()) {
                case 1:
                    for (int k = 0; k < reportTarget.getList().size(); k++) {
                        if (null == reportTarget.getList().get(k).getFmaxValue()) {
                            break;
                        } else if (reportTarget.getList().get(k).getFmaxValue().floatValue() > overLimit.floatValue()) {
                            reportTarget.setPass(EnumPass.NOPASS.getCode());
                            break;
                        } else {
                            reportTarget.setPass(EnumPass.PASS.getCode());
                        }
                    }
                    break;
                case 2:
                    for (int k = 0; k < reportTarget.getList().size(); k++) {
                        if (null == reportTarget.getList().get(k).getMinValue()) {
                            break;
                        } else if (reportTarget.getList().get(k).getMinValue().floatValue() > overLimit.floatValue()) {
                            reportTarget.setPass(EnumPass.NOPASS.getCode());
                            break;
                        } else {
                            reportTarget.setPass(EnumPass.PASS.getCode());
                        }
                    }
                    break;
                case 3:
                    for (int k = 0; k < reportTarget.getList().size(); k++) {
                        if (null == reportTarget.getList().get(k).getMeanValue()) {
                            break;
                        } else if (reportTarget.getList().get(k).getMeanValue().floatValue() > overLimit.floatValue()) {
                            reportTarget.setPass(EnumPass.NOPASS.getCode());
                            break;
                        } else {
                            reportTarget.setPass(EnumPass.PASS.getCode());
                        }
                    }
                    break;
                case 4:
                    for (int k = 0; k < reportTarget.getList().size(); k++) {
                        if (null == reportTarget.getList().get(k).getCp95Value()) {
                            break;
                        } else if (reportTarget.getList().get(k).getCp95Value().floatValue() > overLimit.floatValue()) {
                            reportTarget.setPass(EnumPass.NOPASS.getCode());
                            break;
                        } else {
                            reportTarget.setPass(EnumPass.PASS.getCode());
                        }
                    }
                    break;
                default:
                    break;
            }

            i++;
            list.add(reportTarget);
        }
    }

    /**
     * 基波幅值
     */
    public void getVirtualData(ReportQueryParam param) {

        List<ReportValue> listVirtual = reportService.getVirtualData(param);

        List<Pass> list = new ArrayList<>();

        for (int i = 0; i < 3; i++) {
            Pass pass = new Pass(null);
            list.add(pass);
        }

        this.listVirtual = new ArrayList<>();

        transformData(this.listVirtual, listVirtual, list, true);


    }

    /**
     * 功率
     */
    public void getPowerData(ReportQueryParam param) {
        List<ReportValue> listPower = reportService.getPowerData(param);

        List<Pass> list = new ArrayList<>();

        for (int i = 0; i < 4; i++) {
            Pass pass = new Pass(null);
            list.add(pass);
        }
        this.listPower = new ArrayList<>();
        transformData(this.listPower, listPower, list, true, false);
    }

    /**
     * 闪变
     */
    public void getFlicker(ReportQueryParam param, OverLimitInfoCommDTO overLimit) {
        List<ReportValue> listFlicker = reportService.getFlickerData(param);
        List<Pass> list = new ArrayList<>();
        for (int i = 0; i < 2; i++) {
            Pass pass;
            if (i == 1) {
                pass = new Pass(overLimit.getFlicker(), EnumPass.MAX.getCode());
            } else {
                pass = new Pass(null);
            }
            list.add(pass);
        }
        this.listFlicker = new ArrayList<>();
        transformData(this.listFlicker, listFlicker, list, true);
    }

    /**
     * 电压偏差
     */
    public void getVdeviation(ReportQueryParam param, OverLimitInfoCommDTO overLimit) {
        List<ReportValue> listVdeviation = reportService.getVdeviation(param);
        List<Pass> list = new ArrayList<>();
//        for (int i = 0; i < 2; i++) {
        Pass pass;
        pass = new Pass(overLimit.getVoltageDev(), EnumPass.MAX.getCode());
        list.add(pass);

        Pass pass1;
        pass1 = new Pass(overLimit.getUvoltageDev(), EnumPass.MIN.getCode());
        list.add(pass1);
//        }
        this.listVdeviation = new ArrayList<>();
        transformData(this.listVdeviation, listVdeviation, list, true);
    }

    /**
     * 畸变率
     */
    public void getDistortion(ReportQueryParam param, OverLimitInfoCommDTO overLimit) {
        List<ReportValue> listDistortion = reportService.getDistortionData(param);
        List<Pass> list = new ArrayList<>();
        for (int i = 0; i < 2; i++) {
            Pass pass;

            if (i == 0) {
                pass = new Pass(overLimit.getUaberrance(), EnumPass.MAX.getCode());
            } else {
                pass = new Pass(null);
            }

            list.add(pass);
        }
        this.listDistortion = new ArrayList<>();
        transformData(this.listDistortion, listDistortion, list, true);
    }

    /**
     * 频率
     */
    public void getFre(ReportQueryParam param, OverLimitInfoCommDTO overLimit) {
        List<ReportValue> listFrequency = reportService.getFrequencyData(param);

        List<Pass> list = new ArrayList<>();

        for (int i = 0; i < 2; i++) {
            Pass pass;
            if (i == 1) {
                pass = new Pass(overLimit.getFreqDev(), EnumPass.MAX.getCode());
            } else {
                pass = new Pass(null);
            }
            list.add(pass);
        }

        this.listFrequency = new ArrayList<>();
        transformData(this.listFrequency, listFrequency, list, false);
    }


    /**
     * 三相不平衡
     */
    public void getThreePhase(ReportQueryParam param, OverLimitInfoCommDTO overLimit) {
        List<ReportValue> listThreephase = reportService.getThreephase(param);

        List<Pass> list = new ArrayList<>();

        for (int i = 0; i < 8; i++) {
            Pass pass;

            if (i == 0) {
                pass = new Pass(overLimit.getUbalance(), EnumPass.CP95.getCode());
            } else {
                pass = new Pass(null);
            }

            list.add(pass);
        }

        this.listThreephase = new ArrayList<>();
        transformData(this.listThreephase, listThreephase, list, false);
    }


    /**
     * 谐波电流
     */
    public void getCurrentRate(ReportQueryParam param, OverLimitInfoCommDTO overLimit) {
        List<ReportValue> listICurrent = reportService.getICurrent(param);

        List<Pass> list = new ArrayList<>();
        List<Float> iHarmList = getIHarmList(overLimit);
        for (int i = 0; i < 50; i++) {
            Pass pass;
            if (i < iHarmList.size() + 1 && i > 0) {
                pass = new Pass(iHarmList.get(i - 1),
                        EnumPass.CP95.getCode());
            } else {
                pass = new Pass(null);
            }
            list.add(pass);
        }

        this.listICurrent = new ArrayList<>();
        transformData(this.listICurrent, listICurrent, list, true);
    }

    /**
     * 谐波电压
     */
    public void getVoltageRate(ReportQueryParam param, OverLimitInfoCommDTO overLimit) {
        List<ReportValue> listVoltageRate = reportService.getVoltageRate(param);

        List<Pass> list = new ArrayList<>();
        List<Float> vHarmList = getVHarmList(overLimit);
        for (int i = 0; i < 51; i++) {
            Pass pass;

            if (i == 0) {
                pass = new Pass(null);
            } else if (i == 50) {
                pass = new Pass(overLimit.getUaberrance(), EnumPass.MAX.getCode());
            } else if (i < vHarmList.size() + 1) {
                pass = new Pass(vHarmList.get(i - 1),
                        EnumPass.CP95.getCode());
            } else {
                pass = new Pass(null);
            }

            list.add(pass);
        }

        this.listVoltageRate = new ArrayList<>();
        transformData(this.listVoltageRate, listVoltageRate, list, true);
    }

    public String judgeNull(Float result) {
        return (result == null) ? "/" : result.toString();
    }

    public String dataConversion(Float result, String dataLevel, Double ratio, Boolean isI) {
        if (result == null) {
            return "/";
        }
        if (!"Secondary".equals(dataLevel)) {
            return String.valueOf(result);
        }
        double conversionRatio = (ratio != null) ? ratio : 1.0;
        double convertedValue = result * conversionRatio;
        if (isI != null && Boolean.TRUE.equals(isI)) {
            return String.format("%.2f", convertedValue);
        } else {
            return String.format("%.2f", convertedValue / 1000.0);
        }
    }

    /**
     * 谐波电流限值
     *
     * @param overLimit
     * @return
     */
    public List<Float> getIHarmList(OverLimitInfoCommDTO overLimit) {
        List<Float> list = new ArrayList<>();
        list.add(overLimit.getIharm2());
        list.add(overLimit.getIharm3());
        list.add(overLimit.getIharm4());
        list.add(overLimit.getIharm5());
        list.add(overLimit.getIharm6());
        list.add(overLimit.getIharm7());
        list.add(overLimit.getIharm8());
        list.add(overLimit.getIharm9());
        list.add(overLimit.getIharm10());
        list.add(overLimit.getIharm11());
        list.add(overLimit.getIharm12());
        list.add(overLimit.getIharm13());
        list.add(overLimit.getIharm14());
        list.add(overLimit.getIharm15());
        list.add(overLimit.getIharm16());
        list.add(overLimit.getIharm17());
        list.add(overLimit.getIharm18());
        list.add(overLimit.getIharm19());
        list.add(overLimit.getIharm20());
        list.add(overLimit.getIharm21());
        list.add(overLimit.getIharm22());
        list.add(overLimit.getIharm23());
        list.add(overLimit.getIharm24());
        list.add(overLimit.getIharm25());
        return list;
    }

    /**
     * 谐波电压限值
     *
     * @return
     */
    public List<Float> getVHarmList(OverLimitInfoCommDTO overLimit) {
        List<Float> list = new ArrayList<>();
        list.add(overLimit.getUharm2());
        list.add(overLimit.getUharm3());
        list.add(overLimit.getUharm4());
        list.add(overLimit.getUharm5());
        list.add(overLimit.getUharm6());
        list.add(overLimit.getUharm7());
        list.add(overLimit.getUharm8());
        list.add(overLimit.getUharm9());
        list.add(overLimit.getUharm10());
        list.add(overLimit.getUharm11());
        list.add(overLimit.getUharm12());
        list.add(overLimit.getUharm13());
        list.add(overLimit.getUharm14());
        list.add(overLimit.getUharm15());
        list.add(overLimit.getUharm16());
        list.add(overLimit.getUharm17());
        list.add(overLimit.getUharm18());
        list.add(overLimit.getUharm19());
        list.add(overLimit.getUharm20());
        list.add(overLimit.getUharm21());
        list.add(overLimit.getUharm22());
        list.add(overLimit.getUharm23());
        list.add(overLimit.getUharm24());
        list.add(overLimit.getUharm25());
        return list;
    }


    /**
     * 修复：处理图片字节流+获取自适应宽高（按原图比例，适配Word的EMU单位，防止截断）
     * @param multipartFile 上传的图片文件(可为null)
     * @param defaultPicResource 默认图片资源(ClassPathResource)
     * @return Map<String,Object> 包含content/width/height/type，直接给header用
     */
    private Map<String, Object> handleImageData(MultipartFile multipartFile, ClassPathResource defaultPicResource) {
        Map<String, Object> imgMap = new HashMap<>(4);
        byte[] imgBytes = null;
        String contentType = null;
        try {
            if (ObjectUtil.isNotEmpty(multipartFile) && multipartFile.getSize() > 0) {
                // 处理上传的图片
                imgBytes = multipartFile.getBytes();
                contentType = multipartFile.getContentType();
            } else {
                // 处理默认图片，【修复流读取不完整问题】
                if (defaultPicResource != null && defaultPicResource.exists()) {
                    try (InputStream in = defaultPicResource.getInputStream()) {
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        byte[] buffer = new byte[1024];
                        int len;
                        while ((len = in.read(buffer)) != -1) {
                            baos.write(buffer, 0, len);
                        }
                        imgBytes = baos.toByteArray();
                        contentType = "image/jpeg"; // 默认图片是jpg
                    }
                }
            }

            // 核心修复：获取图片真实宽高 + 按比例自适应缩放（关键！解决只显示一半）
            if (imgBytes != null && imgBytes.length > 0) {
                ByteArrayInputStream bais = new ByteArrayInputStream(imgBytes);
                BufferedImage bufferedImage = ImageIO.read(bais);
                int realWidth = bufferedImage.getWidth();
                int realHeight = bufferedImage.getHeight();

                // 【核心配置】设置Word中图片的最大显示宽度，高度按比例自动计算，永不截断
                int maxWordImgWidth = 550; // 建议值，适配Word页面宽度，可微调
                double scale = 1.0;
                if (realWidth > maxWordImgWidth) {
                    scale = (double) maxWordImgWidth / realWidth;
                }
                int adaptWidth = (int) (realWidth * scale);
                int adaptHeight = (int) (realHeight * scale);

                // 赋值到map，直接给原逻辑的header用
                imgMap.put("content", imgBytes);
                imgMap.put("width", adaptWidth);
                imgMap.put("height", adaptHeight);
                imgMap.put("type", ObjectUtil.isNotEmpty(contentType) ? contentType : "image/jpeg");
            }
        } catch (Exception e) {
            log.error("处理图片数据异常", e);
        }
        return imgMap;
    }
}
