package com.pqs9000.controller.report;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.njcn.enums.LogTypeEnum;
import com.njcn.pojo.commons.RedisDB;
import com.njcn.pojo.commons.SimpleValue;
import com.njcn.pojo.terminal.DeviceUnitVO;
import com.njcn.service.log.UserLogDetailService;
import com.njcn.service.point.PointBaseInfoService;
import com.njcn.service.system.ThemeService;
import com.njcn.shiro.token.TokenManager;
import com.njcn.utils.ClearPathUtil;
import com.njcn.utils.PubUtils;
import com.njcn.utils.UserUtil;
import com.njcn.utils.redis.JedisManager;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.njcn.pojo.commons.device.LineInfo;
import com.njcn.pojo.user.Depts;
import com.njcn.service.configuration.DeviceService;
import com.njcn.utils.AppConfig;
import com.pqs9000.pojo.common.ModelData;
import com.pqs9000.pojo.report.Condition;
import com.pqs9000.pojo.report.OverLimitInfo;
import com.pqs9000.pojo.report.Pass;
import com.pqs9000.pojo.report.ReportTarget;
import com.pqs9000.pojo.report.ReportValue;
import com.pqs9000.pojo.report.enumReport.EnumPass;
import com.pqs9000.service.report.GetDistortionDataService;
import com.pqs9000.service.report.GetFlickerDataService;
import com.pqs9000.service.report.GetFrequencyDataService;
import com.pqs9000.service.report.GetICurrentService;
import com.pqs9000.service.report.GetOverLimitDataService;
import com.pqs9000.service.report.GetPowerDataService;
import com.pqs9000.service.report.GetThreephaseDataService;
import com.pqs9000.service.report.GetVdeviationDataService;
import com.pqs9000.service.report.GetVirtualDataService;
import com.pqs9000.service.report.GetVoltageRateService;
import com.pqs9000.util.TransformTime;
import com.pqs9000.util.WordUtil2;

import sun.misc.BASE64Encoder;

@Controller
@RequestMapping("exportmodel")
public class ExportModelController {
    // 日志记录
    private static final Logger logger = LoggerFactory.getLogger(ExportModelController.class);
    @Resource
    private ThemeService themeService;
    @Autowired
    private UserUtil userUtil;
    @Autowired
    private GetVirtualDataService getVirtualDataService;
    @Autowired
    private GetPowerDataService getPowerDataService;
    @Autowired
    private GetOverLimitDataService getOverLimitDataService;
    @Autowired
    private GetFlickerDataService getFlickerDataService;
    @Autowired
    private GetDistortionDataService getDistortionDataService;
    @Autowired
    private GetVdeviationDataService getVdeviationDataService;
    @Autowired
    private GetFrequencyDataService getFrequencyDataService;
    @Autowired
    private GetThreephaseDataService getThreephaseDataService;
    @Autowired
    private GetICurrentService getICurrentService;
    @Autowired
    private GetVoltageRateService getVoltageRateService;
    @Autowired
    private JedisManager jedisManager;
    @Resource
    private DeviceService getDeviceInfo;
    @Autowired
    UserLogDetailService userLog;
    @Resource
    private AppConfig appConfig;
    @Resource
    private PointBaseInfoService pointBaseInfoService;
    // 非谐波数据
    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 OverLimitInfo overLimitInfo;

    @GetMapping("downloadModel")
    public void downloadExport(HttpServletResponse response, HttpSession session) throws UnsupportedEncodingException {
        String tmpPath = (String) session.getAttribute("tmpPath");
        String filename = (String) session.getAttribute("fileName");
        if (!StringUtils.isBlank(tmpPath)) {
            tmpPath= ClearPathUtil.cleanString(tmpPath);
			// 设置输出的格式
			response.reset();
			response.setContentType("application/docx");
			response.addHeader("Content-Disposition", "attachment; filename=" + new String(filename.getBytes("gb2312"), "ISO8859-1"));
			// 循环取出流中的数据
			byte[] b = new byte[1024];
			int len;
			// 读到流中
			InputStream inStream=null;
			try {
				inStream = new FileInputStream(tmpPath);
				if(null!=inStream){
					while ((len = inStream.read(b)) > 0)
						response.getOutputStream().write(b, 0, len);
				}
			} catch (IOException e) {
                logger.error("读取报表信息失败：" + e.getMessage());
			} finally {
                if (inStream != null) {
                    try {
                        inStream.close();
                    } catch (IOException e) {
                        logger.error("关闭输入流异常，异常为："+e.toString());
                    }
                }
            }
            File file = new File(tmpPath);
            file.delete();
        }
        // 清除session中的数据
        session.removeAttribute("fileName");
        session.removeAttribute("tmpPath");
    }


    @RequestMapping(value = "importImg", method = RequestMethod.POST)
    @ResponseBody
    public String importImg(@RequestParam(value = "file", required = false) MultipartFile file, HttpSession session, HttpServletRequest request)
            throws IOException {
        /**
         * ---------------------------------------------------------------------------------------------------
         * xuyang 2020.08.27
         * 修改：对上传文件做判断
         * 文件大小
         */
        //文件大小(此大小为kb)
        Long fileSize  = file.getSize()/1024;
        //判断文件大小
        if (fileSize > 3072){
            return "sizefail";
        }
        /**
         * over
         * ---------------------------------------------------------------------------------------------------
         */

        // 解析图片
        InputStream in = null;
        byte[] data = null;
        boolean imaflag = false;
        String contentType = null;
        try {
            in = file.getInputStream();
            String name = file.getOriginalFilename();

            String suffix = name.substring(name.lastIndexOf(".")
                    + 1, name.length());
            if (!suffix.trim().toLowerCase().equalsIgnoreCase("png") && !suffix.trim().toLowerCase().equalsIgnoreCase("jpg")) {
                return "namefail";
            }

            contentType = file.getContentType();
            if (null != in) {
                imaflag = true;
            }
            data = new byte[in.available()];
            in.read(data);
            in.close();
            userLog.getLog("导入图片", "成功", PubUtils.getIpAddr(request), LogTypeEnum.BUSSINESS.toString(), 0);
        } catch (IOException e) {
            imaflag = false;
            throw e;
        }
        if (in != null) {
            in.close();
        }
        if (!imaflag) {
            return "fail";
        } else {
            session.setAttribute("image", data);
            session.setAttribute("contentType", contentType);
            return "success";
        }

    }


    @PostMapping("exportModel")
    @ResponseBody
    public String exportworld( HttpSession session, HttpServletResponse response,
                              String startTime, String endTime, String lineIndex,String name,String reportNumber,String crmName,String picdefault) throws ParseException, IOException {
        LineInfo lineDto = getDeviceInfo.getDeviceInfo(Long.valueOf(lineIndex));
        name = lineDto.getLineName();
        String bdname = lineDto.getSubName();
        Integer pttype = lineDto.getPtvalue();
        String atype = "";
        String btype = "";
        String ctype = "";
        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 = "-";
        }

        TransformTime TransformTime = new TransformTime(startTime, endTime);
        try {
            TransformTime.string2Date();
        } catch (Exception e2) {
            logger.error("获取报表发生异常，异常是"+e2.getMessage());
        }

        Condition tempCondition = new Condition();
        tempCondition.setStart(TransformTime.getStart());
        tempCondition.setEnd(TransformTime.getEnd());
        tempCondition.setPointIndex(Integer.valueOf(lineIndex));
        List<TransformTime> exc = new ArrayList<>();
        tempCondition.setExceptTime(exc);
        int day = appConfig.getReportday();
        int days = (int) ((TransformTime.getEnd().getTime() - TransformTime.getStart().getTime()) / (1000 * 3600 * 24))+1;
        Boolean b = (days > day) ? new Boolean(false) : new Boolean(true);
        saveConditionData(tempCondition);
        getOverLimitData();
        tempCondition.setB(b);
        tempCondition.setCount(this.overLimitInfo.getCount());
        tempCondition.setPltCount(this.overLimitInfo.getPltCount());
        tempCondition.setPstCount(this.overLimitInfo.getPstCount());


        Condition condition=getConditionData();


        if (0 == this.overLimitInfo.getOverLimitRate().size()) {
            return "datafail";
        }

        String rtfPath = "";
        String picPath = "file/default.jpg";
        boolean flagPath = false;

        SimpleValue simpleValue;
        try {
            simpleValue = themeService.getThemeInfo();
        } catch (Exception e) {
            logger.error(e.toString());
            simpleValue = new SimpleValue();
            simpleValue.setName("国网");
            simpleValue.setValue("#006565");
        }

        //标识，目前灿能报告特有标识 true:灿能 false:其他
        boolean isSimple = false;
        if(simpleValue.getName().equals("国网")){
        	rtfPath = "file/reportModelGW.docx";
        }else if(simpleValue.getName().equals("南网")){
        	rtfPath = "file/reportModelNW.docx";
        }else if(simpleValue.getName().equals("灿能")){
            isSimple = true;
        	rtfPath = "file/reportModelCN.docx";
        }else{
        	rtfPath = "file/reportModel.docx";
        }

        try {
            rtfPath = getClass().getClassLoader().getResource(rtfPath).getPath();
            picPath = getClass().getClassLoader().getResource(picPath).getPath();
            rtfPath = rtfPath.replaceAll("%20", " ");
            picPath = picPath.replaceAll("%20", " ");
        } catch (Exception e1) {
            logger.error("获取报表发生异常，异常是"+e1.getMessage());
        }
        File tmpfile = new File(rtfPath);
        if (!tmpfile.exists()) {
            return "pathfail";
        }

        InputStream ins = null;
        try {
            ins = new FileInputStream(rtfPath);
            if (null != ins) {
                flagPath = true;
            }
        } catch (FileNotFoundException e) {
            flagPath = false;
            return "readerror";
        } finally {
            if (ins != null) {
               ins.close();
            }
        }

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

        //处理单位
        DeviceUnitVO deviceUnitVO = pointBaseInfoService.lineUnitDetail(Integer.valueOf(lineIndex));
        reportmap.put("$fund_v$", "电压（"+deviceUnitVO.getPhaseVoltage()+"）");
        reportmap.put("$totalActiveP$", "有功功率（"+deviceUnitVO.getTotalActiveP()+"）");
        reportmap.put("$totalNoP$", "无功功率（"+deviceUnitVO.getTotalNoP()+"）");
        reportmap.put("$totalViewP$", "视在功率（"+deviceUnitVO.getTotalViewP()+"）");




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

        Map<String, Object> header = new HashMap<String, Object>();
        if (picdefault.equals("0")) {
            byte[] image = (byte[]) session.getAttribute("image");
            String contentType = (String) session.getAttribute("contentType");
            header.put("width", 400);
            header.put("height", 250);
            header.put("type", contentType);
            header.put("content", image);
        } else {
            InputStream inStream = null;
            byte[] data = null;
            try {
                inStream = new FileInputStream(new File(picPath));
                data = new byte[inStream.available()];
                inStream.read(data);
            } catch (FileNotFoundException e) {
                logger.error("读取报表信息失败：" + e.getMessage());
            } finally {
                if (inStream != null) {
                    inStream.close();
                }
            }
            String contentType = "application/x-jpg";
            header.put("width", 400);
            header.put("height", 250);
            header.put("type", contentType);
            header.put("content", data);
        }

        reportmap.put("$image$", header);

        getVirtualData();
        ReportValue voltage1 = (ReportValue) this.listVirtual.get(0).getList().get(0);// 电压幅值
        ReportValue voltage2 = (ReportValue) this.listVirtual.get(0).getList().get(1);// 电压幅值
        ReportValue voltage3 = (ReportValue) this.listVirtual.get(0).getList().get(2);// 电压幅值
        ReportValue current1 = (ReportValue) this.listVirtual.get(1).getList().get(0);// 电流幅值
        ReportValue current2 = (ReportValue) this.listVirtual.get(1).getList().get(1);// 电流幅值
        ReportValue current3 = (ReportValue) this.listVirtual.get(1).getList().get(2);// 电流幅值
        String strLineBaseName = String.format("%s%s", new String[]{bdname+"_", name});
        String strAnalysis = "";// 分析建议
        String strError = "";// 报表错误
        reportmap.put("$base_info$", strLineBaseName);
        /**************************************************************
         **** 基波电压/电流有效值表格
         **************************************
         **************************************
         * 一、用基波电压和基波电流做是否有值的判断， 判断策略为所有的基波电压和基波电流都为空
         * *************************************
         * ************************************* 二、基本数据判断
         * ①、(最大值>=最小值、平均值、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$", judgeNull(current1.getFmaxValue()));
        reportmap.put("$B" + "I0" + "X" + "_B$", judgeNull(current2.getFmaxValue()));
        reportmap.put("$B" + "I0" + "X" + "_C$", judgeNull(current3.getFmaxValue()));

        /**************************************************************
         **** 三张大表基础数据幅值
         ***************************************************************/
        // 基波电压最大值
        reportmap.put("$C" + "V0" + "X" + "_A$", judgeNull(voltage1.getFmaxValue()));
        reportmap.put("$C" + "V0" + "X" + "_B$", judgeNull(voltage2.getFmaxValue()));
        reportmap.put("$C" + "V0" + "X" + "_C$", judgeNull(voltage3.getFmaxValue()));

        // 基波电流最大值
        reportmap.put("$C" + "I0" + "X" + "_A$", judgeNull(current1.getFmaxValue()));
        reportmap.put("$C" + "I0" + "X" + "_B$", judgeNull(current2.getFmaxValue()));
        reportmap.put("$C" + "I0" + "X" + "_C$", judgeNull(current3.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$", judgeNull(current1.getMinValue()));
        reportmap.put("$B" + "I0" + "N" + "_B$", judgeNull(current2.getMinValue()));
        reportmap.put("$B" + "I0" + "N" + "_C$", judgeNull(current3.getMinValue()));

        /**************************************************************
         **** 三张大表基础数据幅值
         ***************************************************************/
        // 基波电压最小值
        reportmap.put("$C" + "V0" + "N" + "_A$", judgeNull(voltage1.getMinValue()));
        reportmap.put("$C" + "V0" + "N" + "_B$", judgeNull(voltage2.getMinValue()));
        reportmap.put("$C" + "V0" + "N" + "_C$", judgeNull(voltage3.getMinValue()));

        // 基波电流最小值
        reportmap.put("$C" + "I0" + "N" + "_A$", judgeNull(current1.getMinValue()));
        reportmap.put("$C" + "I0" + "N" + "_B$", judgeNull(current2.getMinValue()));
        reportmap.put("$C" + "I0" + "N" + "_C$", judgeNull(current3.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$", judgeNull(current1.getMeanValue()));
        reportmap.put("$B" + "I0" + "E" + "_B$", judgeNull(current2.getMeanValue()));
        reportmap.put("$B" + "I0" + "E" + "_C$", judgeNull(current3.getMeanValue()));

        /**************************************************************
         **** 三张大表基础数据幅值
         ***************************************************************/
        // 基波电压平均值
        reportmap.put("$C" + "V0" + "E" + "_A$", judgeNull(voltage1.getMeanValue()));
        reportmap.put("$C" + "V0" + "E" + "_B$", judgeNull(voltage2.getMeanValue()));
        reportmap.put("$C" + "V0" + "E" + "_C$", judgeNull(voltage3.getMeanValue()));

        // 基波电流平均值
        reportmap.put("$C" + "I0" + "E" + "_A$", judgeNull(current1.getMeanValue()));
        reportmap.put("$C" + "I0" + "E" + "_B$", judgeNull(current2.getMeanValue()));
        reportmap.put("$C" + "I0" + "E" + "_C$", judgeNull(current3.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$", judgeNull(current1.getCp95Value()));
        reportmap.put("$B" + "I0" + "%" + "_B$", judgeNull(current2.getCp95Value()));
        reportmap.put("$B" + "I0" + "%" + "_C$", judgeNull(current3.getCp95Value()));

        /**************************************************************
         **** 三张大表基础数据幅值
         ***************************************************************/
        // 基波电压cp95值
        reportmap.put("$C" + "V0" + "%" + "_A$", judgeNull(voltage1.getCp95Value()));
        reportmap.put("$C" + "V0" + "%" + "_B$", judgeNull(voltage2.getCp95Value()));
        reportmap.put("$C" + "V0" + "%" + "_C$", judgeNull(voltage3.getCp95Value()));

        // 基波电流cp95值
        reportmap.put("$C" + "I0" + "%" + "_A$", judgeNull(current1.getCp95Value()));
        reportmap.put("$C" + "I0" + "%" + "_B$", judgeNull(current2.getCp95Value()));
        reportmap.put("$C" + "I0" + "%" + "_C$", judgeNull(current3.getCp95Value()));

        // 遍历map中的值
        int iCount = 0;
        // 判断所取的基波电压、基波电流值是否为null
        for (Object value : reportmap.values()) {
            if (value == null) {
                iCount++;
            }
        }
        // 假如所有的数据都为null,则返回（所选的时间段内未找到数据）
        if (iCount == reportmap.size()) {
            return "exportworld";// 未找到数据
        }
        // 基本数据判断
        for (int i = 0; i < 3; i++) {
            String tmpstrMap = "A";
            switch (i) {
                case 0:
                    tmpstrMap = "A";
                    break;
                case 1:
                    tmpstrMap = "B";
                    break;
                case 2:
                    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 = Double.parseDouble(reportmap.get("$BI0X_" + tmpstrMap + "$").toString());
                Double iminValue = Double.parseDouble(reportmap.get("$BI0N_" + tmpstrMap + "$").toString());
                Double iaveValue = Double.parseDouble(reportmap.get("$BI0E_" + tmpstrMap + "$").toString());
                Double icp95Value = Double.parseDouble(reportmap.get("$BI0%_" + tmpstrMap + "$").toString());

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

        /**************************************************************
         **** 所选的时间段内有数据存在则进行其他加载
         ***************************************************************/
        Depts dep = userUtil.getCurrentDept();
        String detpName = dep.getArea();
        reportmap.put("$detpName$", detpName); // 区域名称
        // 获取报告生成时间
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");// 报告时分秒格式
        String strTime = String.format("%s——%s。",
                new String[]{(String) formatter.format(condition.getStart()), (String) formatter.format(condition.getEnd())});
        reportmap.put("$number$", reportNumber); // 报告编号
        reportmap.put("$titlePoint$", crmName); // 客户名称

        SimpleDateFormat formatterOnly = new SimpleDateFormat("yyyy年MM月dd日");// 报告时分秒格式
        reportmap.put("$TitleTime$", formatterOnly.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}));// 谐波电流

        reportmap.put("$LineName1$", name);// 监测点名称1
        reportmap.put("$LineName2$", name);// 监测点名称2
        reportmap.put("$LineName3$", name);// 监测点名称3
        reportmap.put("$LineName4$", name);// 监测点名称4
        reportmap.put("$LineName5$", name);// 监测点名称5

        /**********************
         **** 数据获取
         ***********************/
        getPowerData();
        getFlicker();
        getVdeviation();
        getDistortion();
        getFre();
        getThreePhase();
        getVoltageRate();
        getCurrentRate();

        ReportValue pst1 = (ReportValue) this.listFlicker.get(0).getList().get(0);// 短闪
        ReportValue pst2 = (ReportValue) this.listFlicker.get(0).getList().get(1);// 短闪
        ReportValue pst3 = (ReportValue) this.listFlicker.get(0).getList().get(2);// 短闪
        ReportValue plt1 = (ReportValue) this.listFlicker.get(1).getList().get(0);// 长闪
        ReportValue plt2 = (ReportValue) this.listFlicker.get(1).getList().get(1);// 长闪
        ReportValue plt3 = (ReportValue) this.listFlicker.get(1).getList().get(2);// 长闪

        reportmap.put("$bd_name$",bdname);
        reportmap.put("$monitor_base$",name);
        reportmap.put("$devType$",lineDto.getDevType());
        reportmap.put("$devIp$",lineDto.getIP());
        reportmap.put("$Line_Base$", 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.getJZCMP()));
        reportmap.put("$CI_DLRL$", String.valueOf(lineDto.getDLCMP()));
        reportmap.put("$CI_XYRL$", String.valueOf(lineDto.getXYCMP()));
        reportmap.put("$CI_SBRL$", String.valueOf(lineDto.getDEVCMP()));

        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.getJZCMP()));
        reportmap.put("$CV_DLRL$", String.valueOf(lineDto.getDLCMP()));
        reportmap.put("$CV_XYRL$", String.valueOf(lineDto.getXYCMP()));
        reportmap.put("$CV_SBRL$", String.valueOf(lineDto.getDEVCMP()));

        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.getJZCMP()));
        reportmap.put("$FV_DLRL$", String.valueOf(lineDto.getDLCMP()));
        reportmap.put("$FV_XYRL$", String.valueOf(lineDto.getXYCMP()));
        reportmap.put("$FV_SBRL$", String.valueOf(lineDto.getDEVCMP()));

        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 = (ReportValue) this.listVdeviation.get(0).getList().get(0);
        ReportValue vdeviation2 = (ReportValue) this.listVdeviation.get(0).getList().get(1);
        ReportValue vdeviation3 = (ReportValue) this.listVdeviation.get(0).getList().get(2);
        String vdeviationLimit = judgeNull(this.listVdeviation.get(0).getOverLimit());// 获取电压上下偏差的国标限值
        reportmap.put("$VD_L$", vdeviationLimit);
        String strResultVdeviationdata = "";
        String tmpstrResultVdeviationdata = "";
        String strResultVdeviationdataValue = "";
        // 获取电压偏差
        String tmpstrMap = "";
        reportmap.put("$VDTX_A$", judgeNull(vdeviation1.getFmaxValue()));
        reportmap.put("$VDTN_A$", judgeNull(vdeviation1.getMinValue()));
        reportmap.put("$VDTE_A$", judgeNull(vdeviation1.getMeanValue()));
        reportmap.put("$VDT%_A$", judgeNull(vdeviation1.getCp95Value()));
        reportmap.put("$VDTX_B$", judgeNull(vdeviation2.getFmaxValue()));
        reportmap.put("$VDTN_B$", judgeNull(vdeviation2.getMinValue()));
        reportmap.put("$VDTE_B$", judgeNull(vdeviation2.getMeanValue()));
        reportmap.put("$VDT%_B$", judgeNull(vdeviation2.getCp95Value()));
        if (pttype != 2) {
            reportmap.put("$VDTX_C$", judgeNull(vdeviation3.getFmaxValue()));
            reportmap.put("$VDTN_C$", judgeNull(vdeviation3.getMinValue()));
            reportmap.put("$VDTE_C$", judgeNull(vdeviation3.getMeanValue()));
            reportmap.put("$VDT%_C$", judgeNull(vdeviation3.getCp95Value()));
        } else {
            reportmap.put("$VDTX_C$", "-");
            reportmap.put("$VDTN_C$", "-");
            reportmap.put("$VDTE_C$", "-");
            reportmap.put("$VDT%_C$", "-");
        }

        // 值错误判断
        try {
            maxValue = Double.parseDouble(vdeviation1.getFmaxValue().toString());
            minValue = Double.parseDouble(vdeviation1.getMinValue().toString());
            aveValue = Double.parseDouble(vdeviation1.getMeanValue().toString());
            cp95Value =Double.parseDouble(vdeviation1.getCp95Value().toString());
            limit = Double.parseDouble(vdeviationLimit);
        } catch (Exception e) {
            strResultVdeviationdataValue += "注意:从上表中可以看出" + strLineBaseName + "电压偏差数据存在异常(不是数值类型)。";
        }

        if ("".equals(strResultVdeviationdataValue)) {
            if (!(maxValue >= minValue && maxValue >= aveValue && maxValue >= cp95Value)) {
                strResultVdeviationdataValue += "注意:从上表中可以看出" + strLineBaseName
                        + "电压偏差数据存在异常( 1、最大值>=最小值、平均值、95%概率值；2、平均值>=最小值；3、95%概率值>=最小值)。";
            } else if (aveValue < minValue) {
                strResultVdeviationdataValue += "注意:从上表中可以看出" + strLineBaseName
                        + "电压偏差数据存在异常( 1、最大值>=最小值、平均值、95%概率值；2、平均值>=最小值；3、95%概率值>=最小值)。";
            } else if (cp95Value < minValue) {
                strResultVdeviationdataValue += "注意:从上表中可以看出" + strLineBaseName
                        + "电压偏差数据存在异常( 1、最大值>=最小值、平均值、95%概率值；2、平均值>=最小值；3、95%概率值>=最小值)。";
            }
        }
        // 限值判断
        if(isSimple){
            if (Math.abs(cp95Value) > limit) {
                if (!"".equals(tmpstrResultVdeviationdata)) {
                    tmpstrResultVdeviationdata += "、";
                }
                tmpstrResultVdeviationdata += tmpstrMap + "相";
            }
        }else {
            if (Math.abs(maxValue) > limit || Math.abs(minValue)> limit ) {
                if (!"".equals(tmpstrResultVdeviationdata)) {
                    tmpstrResultVdeviationdata += "、";
                }
                tmpstrResultVdeviationdata += tmpstrMap + "相";
            }
        }


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

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

        /**************************************************************
         **** 频率偏差
         ***************************************************************/
        ReportValue valueOfFreValue = (ReportValue) 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 = Math.abs(Double.parseDouble(valueOfFreValue.getFmaxValue().toString()));
            minValue = Math.abs(Double.parseDouble(valueOfFreValue.getMinValue().toString()));
            aveValue = Math.abs(Double.parseDouble(valueOfFreValue.getMeanValue().toString()));
            cp95Value = Math.abs(Double.parseDouble(valueOfFreValue.getCp95Value().toString()));
            limit = Math.abs(Double.parseDouble(valueOfFreLimit));
        } catch (Exception e) {
            strResultFreValue += "注意:从上表中可以看出" + strLineBaseName + "频率偏差数据存在异常(不是数值类型)。";
        }

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

        if (Objects.isNull(valueOfFreValue.getMinValue()) || Objects.isNull(valueOfFreValue.getFmaxValue()) || Objects.isNull(valueOfFreValue.getMeanValue()) || Objects.isNull(valueOfFreValue.getCp95Value())) {
            strResultFreValue += "";
        } else {
            if (!(valueOfFreValue.getFmaxValue() >= valueOfFreValue.getMinValue() && valueOfFreValue.getFmaxValue() >= valueOfFreValue.getMeanValue() && valueOfFreValue.getFmaxValue() >= valueOfFreValue.getCp95Value())) {
                strResultFreValue += "注意:从上表中可以看出" + strLineBaseName
                        + "频率偏差数据存在异常( 1、最大值>=最小值、平均值、95%概率值；2、平均值>=最小值；3、95%概率值>=最小值)。";
            } else if (valueOfFreValue.getMeanValue() < valueOfFreValue.getMinValue()) {
                strResultFreValue += "注意:从上表中可以看出" + strLineBaseName
                        + "频率偏差数据存在异常( 1、最大值>=最小值、平均值、95%概率值；2、平均值>=最小值；3、95%概率值>=最小值)。";
            } else if (valueOfFreValue.getCp95Value() < valueOfFreValue.getMinValue()) {
                strResultFreValue += "注意:从上表中可以看出" + strLineBaseName
                        + "频率偏差数据存在异常( 1、最大值>=最小值、平均值、95%概率值；2、平均值>=最小值；3、95%概率值>=最小值)。";
            }
        }

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

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

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

        /**************************************************************
         **** 三相电压不平衡度
         ***************************************************************/
        ReportValue valueOfThree = (ReportValue) 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 + "三相电压不平衡度数据存在异常(不是数值类型)。";
        }
        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%概率值>=最小值)。";
        } else if (aveValue < minValue) {
            strResultThreeValue += "注意:从上表中可以看出" + strLineBaseName
                    + "三相电压不平衡度数据存在异常( 1、最大值>=最小值、平均值、95%概率值；2、平均值>=最小值；3、95%概率值>=最小值)。";
        } else if (cp95Value < minValue) {
            strResultThreeValue += "注意:从上表中可以看出" + strLineBaseName
                    + "三相电压不平衡度数据存在异常( 1、最大值>=最小值、平均值、95%概率值；2、平均值>=最小值；3、95%概率值>=最小值)。";
        }

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

            if(isSimple){
                footTitle3 += "三相电压不平衡度不满足国标限值的要求（" + valueOfThreeLimit + "%）;";
            }else {
                footTitle3 = strResultThree;
            }
        }

        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 = "";
        String strPhase = "";// 相别，A、B、C
        String strType = "";// 长闪还是短闪；S:短闪；L：长闪
        String strValueType = "";// 值类型，最大，最小，平均，95%概率值
        try {
            if (Double.parseDouble(plt1.getFmaxValue().toString()) > Double.parseDouble(valueOfFlickerLimit)) {
                if (!"".equals(tmpstrResultFlicker))
                    tmpstrResultFlicker += ",";
                tmpstrResultFlicker += atype + "最大值为：" + plt1.getFmaxValue().toString();
                reportmap.put("$" + "L" + "V0R_" + "A" + "$", "不合格");
            } else {
                reportmap.put("$" + "L" + "V0R_" + "A" + "$", "合格");
            }

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

            if (Double.parseDouble(plt3.getFmaxValue().toString()) > Double.parseDouble(valueOfFlickerLimit) && pttype != 2) {
                if (!"".equals(tmpstrResultFlicker))
                    tmpstrResultFlicker += ",";
                tmpstrResultFlicker += ctype + "最大值为：" + plt3.getFmaxValue().toString();
                reportmap.put("$" + "L" + "V0R_" + "C" + "$", "不合格");
            } else {
                reportmap.put("$" + "L" + "V0R_" + "C" + "$", "合格");
            }
        } catch (Exception e) {
            if ("".equals(strResultFlickerValue))
                strResultFlickerValue += "注意:从上表中可以看出" + strLineBaseName + "长时闪变数据存在异常(不是数值类型)。";
        }

        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()));

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

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

            if(isSimple){
                footTitle4 += "电压长时闪变不满足国标限值的要求（" + valueOfFlickerLimit + "）;";
            }else {
                footTitle4 = strResultFlicker;
            }

        }

        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(((ReportValue) this.listVoltageRate.get(i).getList().get(0)).getCp95Value());
            strCurrentB = judgeNull(((ReportValue) this.listVoltageRate.get(i).getList().get(1)).getCp95Value());
            strCurrentC = judgeNull(((ReportValue) 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(((ReportValue) this.listVoltageRate.get(i).getList().get(0)).getFmaxValue()));
            reportmap.put("$CV" + (i + 1) + "X_B$",
                    judgeNull(((ReportValue) this.listVoltageRate.get(i).getList().get(1)).getFmaxValue()));

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

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

            if (pttype != 2) {
                reportmap.put("$CV" + (i + 1) + "X_C$",
                        judgeNull(((ReportValue) this.listVoltageRate.get(i).getList().get(2)).getFmaxValue()));
                reportmap.put("$CV" + (i + 1) + "N_C$",
                        judgeNull(((ReportValue) this.listVoltageRate.get(i).getList().get(2)).getMinValue()));
                reportmap.put("$CV" + (i + 1) + "E_C$",
                        judgeNull(((ReportValue) 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 + "谐波电压含有率95%概率值数据存在异常(不是数值类型)。";
            }

            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 + ";";
            }
        }

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

            if(isSimple){
                strAnalysis += tmpstrResultVoltageRate + "2-25次谐波电压含有率均不满足国标限值要求。";
                strResultVoltageRate += "从上表中可以看出" + strLineBaseName + tmpstrResultVoltageRate + "均不满足国标限值要求。";
                footTitle5 += "2-25次谐波电压含有率均不满足国标限值要求 ";
            }else {
                strAnalysis += tmpstrResultVoltageRate + "2-25次谐波电压含有率95%概率值均不满足国标限值要求。";
                strResultVoltageRate += "从上表中可以看出" + strLineBaseName + tmpstrResultVoltageRate + "均不满足国标限值要求。";
                footTitle5 = strResultVoltageRate;
            }
        }

        /**************************************************************
         **** 电压总谐波畸变率(THD)
         ***************************************************************/
        ReportValue distortion1 = (ReportValue) this.listDistortion.get(0).getList().get(0);
        ReportValue distortion2 = (ReportValue) this.listDistortion.get(0).getList().get(1);
        ReportValue distortion3 = (ReportValue) 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)数据存在异常(不是数值类型)。";
        }
        // 限值判断
        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$", "合格");// 三张大表取值
        }

        // 假如为空则所有的都满足
        String footTitle6 = "";
        if ("".equals(tmpstrResultDistortion)) {
            strResultDistortion += "电压总谐波畸变率满足国标限值要求;";
            footTitle6 = strResultDistortion;
        } else {
            strAnalysis += "电压总谐波畸变率(THD)95%概率值" + tmpstrResultDistortion + "均不满足国标限值要求。";
            strResultDistortion += "电压总谐波畸变率(THD)95%概率值" + tmpstrResultDistortion + "均不满足国标限值要求。";

            if(isSimple){
                footTitle6 = "电压总谐波畸变率不满足国标限值要求;";
            }else {
                footTitle6 = strResultDistortion;
            }
        }

        if(isSimple){
            if("".equals(tmpstrResultDistortion) && "".equals(tmpstrResultVoltageRate)){
                footTitle5 ="2-25次谐波电压含有率及电压总谐波畸变率均满足国标限值要求。";
            }

            if(!"".equals(tmpstrResultDistortion) && !"".equals(tmpstrResultVoltageRate)){
                footTitle5 ="2-25次谐波电压含有率及电压总谐波畸变率均不满足国标限值要求。";
            }
        }


        reportmap.put("$ResultVoltageRate$", strResultVoltageRate + strResultDistortion);
        reportmap.put("$ResultVoltageRateValue$", strResultVoltageRateValue + strResultDistortionValue);
        strError += strResultVoltageRateValue + strResultDistortionValue;

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

            // 基波电流含有率
            strCurrentA = judgeNull(((ReportValue) this.listICurrent.get(i).getList().get(0)).getCp95Value());
            strCurrentB = judgeNull(((ReportValue) this.listICurrent.get(i).getList().get(1)).getCp95Value());
            strCurrentC = judgeNull(((ReportValue) this.listICurrent.get(i).getList().get(2)).getCp95Value());
            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(((ReportValue) this.listICurrent.get(i).getList().get(0)).getFmaxValue()));
            reportmap.put("$CI" + (i + 1) + "X_B$", judgeNull(((ReportValue) this.listICurrent.get(i).getList().get(1)).getFmaxValue()));
            reportmap.put("$CI" + (i + 1) + "X_C$", judgeNull(((ReportValue) this.listICurrent.get(i).getList().get(2)).getFmaxValue()));

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

            reportmap.put("$CI" + (i + 1) + "E_A$", judgeNull(((ReportValue) this.listICurrent.get(i).getList().get(0)).getMeanValue()));
            reportmap.put("$CI" + (i + 1) + "E_B$", judgeNull(((ReportValue) this.listICurrent.get(i).getList().get(1)).getMeanValue()));
            reportmap.put("$CI" + (i + 1) + "E_C$", judgeNull(((ReportValue) 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 = Double.parseDouble(strCurrentA);
                minValue = Double.parseDouble(strCurrentB);
                aveValue = Double.parseDouble(strCurrentC);
                limit = Double.parseDouble(strLimit);
            } catch (Exception e) {
                strResultCurrentValue += "注意:从上表中可以看出" + strLineBaseName + "谐波电流幅值95%概率值数据存在异常(不是数值类型)。";
            }

            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 + ";";
            }
        }

        // 假如为空则所有的都满足
        String footTitle7 = "";
        if ("".equals(tmpstrResultCurrent)) {
            if(isSimple){
                strResultCurrent += "从上表中可以看出" + strLineBaseName + "2-25次谐波电流幅值均满足国标限值要求。";
                footTitle7 += "2-25次谐波电流满足国标限值要求;";
            }else {
                strResultCurrent += "从上表中可以看出" + strLineBaseName + "2-25次谐波电流幅值95%概率值均满足国标限值要求。";
                footTitle7 = strResultCurrent;
            }
        } else {
            strAnalysis += tmpstrResultCurrent + "均不满足国标限值要求。";
            strResultCurrent += "从上表中可以看出" + strLineBaseName + tmpstrResultCurrent + "均不满足国标限值要求。";
            if(isSimple){
                footTitle7 += "2-25次谐波电流不满足国标限值要求。";
            }else {
                footTitle7 = strResultCurrent;
            }
        }

        reportmap.put("$ResultCurrent$", strResultCurrent);
        reportmap.put("$ResultCurrentValue$", strResultCurrentValue);
        strError += strResultCurrentValue;

        // 测试结果填写

        if(isSimple){
            reportmap.put("$ResultTitle$", String.format("%s",
                    new String[]{strLineBaseName+"电能质量测试结论："}));// 结论标题
            reportmap.put("$Result_VD$", String.format("（1）%s", new String[]{footTitle1}));// 电压偏差
            reportmap.put("$Result_FRE$", String.format("（2）%s", new String[]{footTitle2}));// 频率偏差
            reportmap.put("$Result_THE$", String.format("（3）%s", new String[]{footTitle3}));// 三相电压不平衡度
            reportmap.put("$Result_FIC$", String.format("（4）%s", new String[]{footTitle4}));// 电压长时闪变

            String tem = "(电压总谐波畸变率"+judgeNull(this.listDistortion.get(0).getOverLimit())+"%，奇次谐波电压含有率"+judgeNull(this.listVoltageRate.get(2).getOverLimit())+"%，偶次谐波电压含有率"+judgeNull(this.listVoltageRate.get(3).getOverLimit())+"%)";
            footTitle5+=tem;
            reportmap.put("$Result_VOL$", String.format("（5）%s", new String[]{footTitle5}));// 谐波电压
            reportmap.put("$Result_CUR$", String.format("（6）%s", new String[]{footTitle7}));// 谐波电流
            // 分析建议填写
            if (!"".equals(strAnalysis) || !"".equals(strError)) {
                reportmap.put("$Analysis$", "根据统计数据结果分析,监测点为：" + name + "," + strAnalysis + strError);// 分析建议
            } else {
                reportmap.put("$Analysis$", "根据统计数据结果分析,监测点为：" + name + "，电能质量数据满足国标限值要求。");// 分析建议
            }
        }else {
            reportmap.put("$ResultTitle$", String.format("通过对（%s——%s）时间段内%s电能质量统计数据分析后得出以下结论：",
                    new String[]{(String) formatter.format(condition.getStart()), (String) formatter.format(condition.getEnd()), 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 = (ReportValue) this.listPower.get(0).getList().get(3);
        ReportValue powerDto2 = (ReportValue) this.listPower.get(1).getList().get(3);
        ReportValue powerDto3 = (ReportValue) this.listPower.get(2).getList().get(3);
        ReportValue powerDto4 = (ReportValue) 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");// 报告时分秒格式
        WordUtil2 oRTF = new WordUtil2();
        try {
            response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:8080");
            oRTF.getWord(rtfPath, reportmap, name + formatter.format(currentTime) + ".docx", response, session);
        } catch (Exception e) {
            logger.error("获取报告发生异常，异常是"+e.getMessage());
        }

        return "success";
    }

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

        return decoder.encode(base64Info);
    }

    private ModelData getModelData(String startTime,String endTime,String lineIndex,String lineName,String reportNumber,String crmName) {
        ModelData modelData = new ModelData();
        modelData.setStartTime(startTime);
        modelData.setEndTime(endTime);
        modelData.setLineIndex(lineIndex);
        // MultipartHttpServletRequest multipartRequest =
        // (MultipartHttpServletRequest) request;
        // List<MultipartFile> files = multipartRequest.getFiles("file");
        // modelData.setFile((File) files.get(0));
        modelData.setName(lineName);
        modelData.setReportNumber(reportNumber);
        modelData.setCrmName(crmName);

        return modelData;

    }

    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 getOverLimitData() {
        Condition condition=getConditionData();
        this.overLimitInfo = getOverLimitDataService.getOverLimitData(condition);
        condition.setCount(this.overLimitInfo.getCount());
        saveConditionData(condition);

    }

    // 基波幅值
    public void getVirtualData() {
        Condition condition=getConditionData();
        List<ReportValue> listVirtual = getVirtualDataService.getVirtualData(condition);

        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() {
        Condition condition=getConditionData();
        List<ReportValue> listPower = getPowerDataService.getPowerData(condition);

        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() {
        Condition condition=getConditionData();
        List<ReportValue> listFlicker = getFlickerDataService.getFlickerData(condition);

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

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

            if (i == 1) {
                pass = new Pass(overLimitInfo.getOverLimitRate().get(0).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() {
        Condition condition=getConditionData();
        List<ReportValue> listVdeviation = getVdeviationDataService.getVdeviation(condition);

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

        for (int i = 0; i < 2; i++) {
            Pass pass;
            pass = new Pass(overLimitInfo.getOverLimitRate().get(0).getVoltageDev(), EnumPass.MAX.getCode());
            list.add(pass);
        }

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

    // 畸变率
    public void getDistortion() {
        Condition condition=getConditionData();
        List<ReportValue> listDistortion = getDistortionDataService.getDistortionData(condition);

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

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

            if (i == 0) {
                pass = new Pass(overLimitInfo.getOverLimitRate().get(0).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() {
        Condition condition=getConditionData();
        List<ReportValue> listFrequency = getFrequencyDataService.getFrequencyData(condition);

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

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

            if (i == 1) {
                pass = new Pass(overLimitInfo.getOverLimitRate().get(0).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() {
        Condition condition=getConditionData();
        List<ReportValue> listThreephase = getThreephaseDataService.getThreephase(condition);

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

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

            if (i == 0) {
                pass = new Pass(overLimitInfo.getOverLimitRate().get(0).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() {
        Condition condition=getConditionData();
        List<ReportValue> listICurrent = getICurrentService.getICurrent(condition);

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

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

            if (i < overLimitInfo.getOverLimitRate().get(0).getIHarmList().size() + 1 && i > 0) {
                pass = new Pass(overLimitInfo.getOverLimitRate().get(0).getIHarmList().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() {
        Condition condition=getConditionData();
        List<ReportValue> listVoltageRate = getVoltageRateService.getVoltageRate(condition);

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

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

            if (i == 0) {
                pass = new Pass(null);
            } else if (i == 50) {
                pass = new Pass(overLimitInfo.getOverLimitRate().get(0).getUaberrance(), EnumPass.MAX.getCode());
            } else if (i < overLimitInfo.getOverLimitRate().get(0).getVHarmList().size() + 1) {
                pass = new Pass(overLimitInfo.getOverLimitRate().get(0).getVHarmList().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();
    }
    /**
     * 保存condition数据
     * @param condition 数据
     */
    private void saveConditionData(Condition condition) {
        String userId = TokenManager.getUserId();
        String key = userId+"ExportModelController";
        JSONObject conditionJson=JSONObject.fromObject(condition);
        jedisManager.saveValueByKey(RedisDB.LONG_TIME_QUERY,key,conditionJson.toString(),-1);
    }

    /**
     * 获取condition数据
     */
    private Condition getConditionData() {
        String userId = TokenManager.getUserId();
        String key = userId+"ExportModelController";
        String valueJson = jedisManager.getValueByKey(RedisDB.LONG_TIME_QUERY, key);
        JSONObject conditionJSONObject=JSONObject.fromObject(valueJson);
        return (Condition) JSONObject.toBean(conditionJSONObject,Condition.class);
    }


}
