/**
 *
 */
package com.huatek.busi.task.transformer;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.github.pagehelper.util.StringUtil;
import com.google.common.collect.Maps;
import com.huatek.busi.common.SiteConstants;
import com.huatek.busi.common.util.DateUtil;
import com.huatek.busi.dao.HotSpotTemperatureResultDao;
import com.huatek.busi.entity.*;
import com.huatek.busi.mapper.BusiOfflineTransformerRepairMapper;
import com.huatek.busi.mapper.IecBreakerParamMapper;
import com.huatek.busi.mapper.TransformerEpaDataOriginMapper;
import com.huatek.busi.mapper.TransformerMeteorologicalStatisticsMapper;
import com.huatek.busi.service.BusiSiteTreeService;
import com.huatek.busi.service.BusiTransformerLoadService;
import com.huatek.busi.service.BusiTransfromTemperatureExcessService;
import com.huatek.busi.service.ICalculateStepService;
import com.huatek.busi.service.param.BusiParamTransformerService;
import com.huatek.busi.service.transformer.BusiOfflineTransformerBrandService;
import com.huatek.busi.service.transformer.TransformerEvaluateDataService;
import com.huatek.busi.service.transformer.TransformerEvaluationIntermediateValueService;
import com.huatek.busi.service.transformer.TransformerEvaluationResultsService;
import com.huatek.busi.util.EvaluateConstant;
import com.huatek.busi.util.TransformerEvaluationDescUtil;
import com.huatek.busi.util.TransformerFormulaCal;
import com.huatek.busi.util.TransformerFormulaSingleton;
import com.huatek.busi.vo.BusiParamTransformerVo;
import com.huatek.busi.vo.TransformerEvaluateDataVo;
import com.huatek.busi.vo.TransformerWindingTemperatureVo;
import com.huatek.busi.vo.epa.EpaEvaluatRepairDataVo;
import com.huatek.busi.vo.epa.EpaEvaluateDataVo;
import com.huatek.busi.vo.epa.IecBreakerParamEvaluateVo;
import com.huatek.busi.vo.epa.TemperatureEvaluateDataVo;
import com.huatek.frame.base.util.Constants;
import com.huatek.torch.util.uuid.Uuid;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @ClassName: TransformerEvaluationTask
 * @FullClassPath: com.huatek.busi.task.TransformerEvaluationTask
 * @Description: 变压器评测定时任务.
 * @author: Arno
 * @date: Aug 30, 2019 11:21:38 AM
 * @version: 1.0
 *
 */
@Slf4j
@Component("transformerEvaluationTask")
public class TransformerEvaluationTask {

    /** @Fields busiOfflineTransformerBrandService : 变压器标牌服务 */
    @Autowired
    public BusiOfflineTransformerBrandService busiOfflineTransformerBrandService;

    /** @Fields busiTransformerLoadService : 变压器负荷*/
    @Autowired
    public BusiTransformerLoadService busiTransformerLoadService;

    /** @Fields transformerEvaluateDataService : 变压器评测数据*/
    @Autowired
    public TransformerEvaluateDataService transformerEvaluateDataService;

    /** @Fields busiParamTransformerService :变压器评测分析参数 */
    @Autowired
    private BusiParamTransformerService busiParamTransformerService;

    /** @Fields transformerEpaDataOriginMapper : 油色谱原始数据*/
    @Autowired
    private TransformerEpaDataOriginMapper transformerEpaDataOriginMapper;

    /** @Fields busiOfflineTransformerRepairMapper : 维修管理*/
    @Autowired
    private BusiOfflineTransformerRepairMapper busiOfflineTransformerRepairMapper;

    /** @Fields iecBreakerParamMapper : 短路状态*/
    @Autowired
    private IecBreakerParamMapper iecBreakerParamMapper;

    /** @Fields busiTransfromTemperatureExcessService : 超温时间*/
    @Autowired
    private BusiTransfromTemperatureExcessService busiTransfromTemperatureExcessService;

    /** @Fields transformerEvaluationResultsService : 变压器评测结果*/
    @Autowired
    private TransformerEvaluationResultsService transformerEvaluationResultsService;

    public static TransformerFormulaSingleton instance = TransformerFormulaSingleton.getInstance();

    public static TransformerFormulaCal transformerFormulaCalInstance = TransformerFormulaCal.getInstance();

    /** @Fields transformerEvaluationIntermediateValueService : 变压器评测中间过程*/
    @Autowired
    private TransformerEvaluationIntermediateValueService transformerEvaluationIntermediateValueService;

    @Resource
    private BusiSiteTreeService busiSiteTreeService;

    @Resource
    private ICalculateStepService calculateStepService;

    @Value("${dataoutput.base.path}")
    private String basePath;

    @Autowired
    private HotSpotTemperatureResultDao hotSpotTemperatureResultDao;

    @Autowired
    private TransformerMeteorologicalStatisticsMapper transformerMeteorologicalStatisticsMapper;

    // 报告路径
    private String filePath = "transformer";

    public static String YSP_INDEX = "YSP_INDEX";
    public static String YZSY_INDEX = "YZSY_INDEX";
    public static String KQ_INDEX = "KQ_INDEX";
    public static String JUZSY_INDEX = "JUZSY_INDEX";
    public static String ZDSSY_INDEX = "ZDSSY_INDEX";
    public static String LXSY_INDEX = "LXSY_INDEX";
    public static String TOTAL_INDEX = "TOTAL_INDEX";

    public void execute() {
        List<BusiOfflineTransformerBrand> transformerlist = this.getTransformerlist();
        if (!transformerlist.isEmpty()) {
            DateTimeFormatter dateTimeFormater = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            DateTimeFormatter dateTimeFormater2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDateTime localDateTime = LocalDateTime.now();
            LocalDate localDate = LocalDate.now();
            log.info("--->> 变压器评测时间：{}", dateTimeFormater.format(localDateTime));

            for (BusiOfflineTransformerBrand brand : transformerlist) {
                try {
                    String mainTreeId = brand.getMainEquipmentId();
                    String siteId = brand.getSiteId();
                    String name = brand.getTransformerName();
                    String id = brand.getId();
                    String date = dateTimeFormater2.format(localDate);
                    String fileName = name + "_" + date + ".xml";
                    log.info("--->> 变压器名称：{},mainTreeId:{},id{}", name, mainTreeId, id);

                    TransformerEvaluationIntermediateValue intermediateValue = new TransformerEvaluationIntermediateValue();
                    intermediateValue.setId(Uuid.getUUID());
                    intermediateValue.setTransformeId(id);
                    intermediateValue.setTransformerName(name);
                    intermediateValue.setEvaluateDate(LocalDate.now());
                    intermediateValue.setMainTreeId(mainTreeId);
                    intermediateValue.setDesignLife(brand.getDesignLife());

                    TransformerEvaluateDataVo evaluateData = this.getTransformerEvaluateData(mainTreeId);
                    if (null == evaluateData) {
                        log.error("--->> 变压器:[{}],未设置评测数据", name);
                        intermediateValue.setFailureRreasons("未设置评测数据");
                        transformerEvaluationIntermediateValueService.save(intermediateValue);
                        TransfromerCreateUtil.createFile(intermediateValue, false, basePath, filePath, fileName, date);
                        continue;
                    }

                    List<BusiParamTransformerVo> params = this.getTransformerParams(siteId, mainTreeId);
                    if (CollectionUtils.isEmpty(params)) {
                        log.error("--->> 变压器:[{}],未设置分析参数", name);
                        intermediateValue.setFailureRreasons("未设置分析参数");
                        transformerEvaluationIntermediateValueService.save(intermediateValue);
                        TransfromerCreateUtil.createFile(intermediateValue, false, basePath, filePath, fileName, date);
                        continue;
                    }

                    // 查询油色谱sensor编码
                    String sensorCode = this.getEpaSensorCode(id);
                    EpaEvaluateDataVo epaEvaluateData = this.getEpaEvaluateData(id, sensorCode);
                    if (null == epaEvaluateData) {
                        log.error("--->> 变压器评测油色谱数据为空");
                        intermediateValue.setFailureRreasons("变压器评测油色谱数据为空");
                        transformerEvaluationIntermediateValueService.save(intermediateValue);
                        TransfromerCreateUtil.createFile(intermediateValue, false, basePath, filePath, fileName, date);
                        continue;
                    }

                    Map<String, BusiParamTransformerVo> fristLevelMap = this.convertParams("1", params);
                    Map<String, BusiParamTransformerVo> secondLevelMap = this.convertParams("2", params);
                    Map<String, BusiParamTransformerVo> threeLevelMap = this.convertParams("3", params);

                    Double weight1 = this.getEvaluateWeight(EvaluateConstant.DESIGN_BRAND, fristLevelMap);
                    Double weight2 = this.getEvaluateWeight(EvaluateConstant.INDIVIDUAL_INSULATION, fristLevelMap);
                    Double weight3 = this.getEvaluateWeight(EvaluateConstant.HEREDITY_RISK, fristLevelMap);

                    // 根据站点编号与设备编号查询站点树信息
                    String mainEquipmentId = brand.getMainEquipmentId();
                    BusiSiteTree busiSiteTree = busiSiteTreeService.findByMainEquipmentIdAndSiteId(mainEquipmentId, brand.getSiteId());

                    JSONArray jsonArray = new JSONArray();
                    CalculateStep calculateStep = new CalculateStep();
                    calculateStep.setId(Uuid.getUUID());
                    calculateStep.setSiteId(brand.getSiteId());
                    calculateStep.setEquipmentType(busiSiteTree.getEquipmentType());
                    calculateStep.setMainEquipmentId(mainEquipmentId);
                    calculateStep.setExecuteMode(Integer.valueOf(Constants.DEFAULT_YES));
                    calculateStep.setCreateTime(LocalDateTime.now());

                    int step = 0;

                    // 基本参数计算结果
                    Map<String, Double> map = this.getTransformerAgingHealthIndex(brand, jsonArray, step);
                    Double agingHealthIndex = map.get("agingHealthIndex");
                    // 初始化老化系数
                    Double B0 = map.get("B0");
                    // 预期寿命
                    Double expectlife = map.get("expectlife");
                    // 设计寿命
                    String designLife = brand.getDesignLife();

                    // 个体绝缘计算结果
                    step = Double.valueOf(map.get("step").toString()).intValue();
                    Map<String, Double> individualInsulationMap = this.calcIndividualInsulation(evaluateData, epaEvaluateData,
                            secondLevelMap, threeLevelMap, jsonArray, step);

                    Double individualInsulation = individualInsulationMap.get("TOTAL_INDEX");

                    // 部件可靠性计算结果
                    step = Double.valueOf(individualInsulationMap.get("step").toString()).intValue();
                    Map<String, Object> map1 = this.calcDefectWeight(id, secondLevelMap, jsonArray, step);
                    Double defectWeight = Double.valueOf(map1.get("tmp").toString());
                    step = Integer.valueOf(map1.get("step").toString());
                    step += 1;
                    setStep(jsonArray, step, "部件可靠性计算", "", String.valueOf(defectWeight));

                    double val = agingHealthIndex * weight1;
                    Double tmp1 = new BigDecimal(val).setScale(4, RoundingMode.HALF_UP).doubleValue();
                    log.info("--->> 计算绝缘老化状态健康指数： 老化系数[{}], 权重[{}], 健康指数[{}]", agingHealthIndex, weight1, tmp1);
                    step += 1;
                    com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
                    jsonObject.put("agingHealthIndex", agingHealthIndex);
                    jsonObject.put("weight1", weight1);
                    setStep(jsonArray, step, "绝缘老化状态健康指数计算", jsonObject.toJSONString(), String.valueOf(tmp1));

                    double val2 = individualInsulation * weight2;
                    Double tmp2 = new BigDecimal(val2).setScale(4, RoundingMode.HALF_UP).doubleValue();
                    log.info("--->> 计算绝缘运行状态健康指数： 指数[{}], 权重[{}], 健康指数[{}]", agingHealthIndex, weight2, tmp2);
                    jsonObject.clear();
                    jsonObject.put("individualInsulation", individualInsulation);
                    jsonObject.put("weight2", weight2);
                    step += 1;
                    setStep(jsonArray, step, "绝缘运行状态健康指数计算", jsonObject.toJSONString(), String.valueOf(tmp2));

                    double val3 = defectWeight * weight3;
                    Double tmp3 = new BigDecimal(val3).setScale(4, RoundingMode.HALF_UP).doubleValue();
                    log.info("--->> 计算变压器部件缺陷风险状态健康指数： 指数[{}], 权重[{}], 健康指数[{}]", agingHealthIndex, weight3, tmp3);
                    jsonObject.clear();
                    jsonObject.put("defectWeight", defectWeight);
                    jsonObject.put("weight3", weight3);
                    step += 1;
                    setStep(jsonArray, step, "变压器部件缺陷风险状态健康指数计算", jsonObject.toJSONString(), String.valueOf(tmp3));

                    double val4 = tmp3 + tmp2 + tmp1;
                    Double healthyIndex = new BigDecimal(val4).setScale(4, RoundingMode.HALF_UP).doubleValue();
                    log.info("--->> 变压器状态最终健康指数：[{}] ", healthyIndex);
                    step += 1;
                    jsonObject.clear();
                    jsonObject.put("tmp1", tmp1);
                    jsonObject.put("tmp2", tmp2);
                    jsonObject.put("tmp3", tmp3);
                    setStep(jsonArray, step, "变压器状态最终健康指数计算", jsonObject.toJSONString(), String.valueOf(healthyIndex));

                    Double K1 = this.ShortCircuitCorrectionValue(mainTreeId);
                    log.info("--->> 进出口区短路修正指数：[{}] ", K1);
                    step += 1;
                    setStep(jsonArray, step, "进出口区短路修正指数计算", "", String.valueOf(K1));

                    double val5 = K1 * healthyIndex;
                    Double correctionThealthyIndex = new BigDecimal(val5).setScale(4, RoundingMode.HALF_UP)
                            .doubleValue();
                    jsonObject.clear();
                    jsonObject.put("K1", K1);
                    jsonObject.put("healthyIndex", healthyIndex);
                    log.info("--->> 变压器状态修正后最终健康指数：[{}] ", correctionThealthyIndex);
                    step += 1;
                    setStep(jsonArray, step, "变压器状态修正后最终健康指数计算", jsonObject.toJSONString(), String.valueOf(correctionThealthyIndex));

                    double futureFailureRate = transformerFormulaCalInstance.clacFutureFailureRate(correctionThealthyIndex);
                    log.info("--->> 变压器未来故障率：[{}] ", futureFailureRate);
                    step += 1;
                    setStep(jsonArray, step, "变压器未来故障率计算", String.valueOf(correctionThealthyIndex), String.valueOf(futureFailureRate));

                    Map<String, Object> map2 = this.calcK2(id, jsonArray, step);
                    Double K2 = Double.valueOf(map2.get("K2").toString());
                    log.info("--->> 变压器过负荷/过热修正系数：[{}] ", K2);
                    step = Integer.valueOf(map2.get("step").toString());
                    step += 1;
                    setStep(jsonArray, step, "变压器过负荷/过热修正系数计算", "", String.valueOf(K2));

                    double B = K2 * B0;
                    log.info("--->> 变压器最终老化系数：[{}] ", B);
                    step += 1;
                    jsonObject.clear();
                    jsonObject.put("K2", K2);
                    jsonObject.put("B0", B0);
                    setStep(jsonArray, step, "变压器最终老化系数计算", jsonObject.toJSONString(), String.valueOf(B));

                    // 绕组测温数据 TODO
                    List<TransformerWindingTemperatureVo> winding = this.getWindingTempreature(mainEquipmentId);
                    double naturalAgingRate = 0;
                    JSONArray jsonArray2 = new JSONArray();
                    com.alibaba.fastjson.JSONObject jsonObject2 = new com.alibaba.fastjson.JSONObject();
                    HotSpotTemperatureResult temperatureResult = new HotSpotTemperatureResult();
                    temperatureResult.setResult(Uuid.getUUID());
                    temperatureResult.setMainTreeId(mainTreeId);
                    temperatureResult.setType("2"); //自动
                    temperatureResult.setAssessTime(LocalDateTime.now());
                    temperatureResult.setSiteId(siteId);
                    if (winding == null) {
                        // 老算法 CO2/CO
                        naturalAgingRate = this.calcNaturalAgingRate(epaEvaluateData);
                        log.info("--->> 变压器自然老化率：[{}] ", naturalAgingRate);
                        jsonObject.clear();
                        jsonObject.put("co", epaEvaluateData.getCo());
                        jsonObject.put("co2", Double.valueOf(epaEvaluateData.getCo2()) * 0.65);
                        step += 1;
                        setStep(jsonArray, step, "变压器自然老化率计算", jsonObject.toJSONString(), String.valueOf(naturalAgingRate));
                        temperatureResult.setCo2(String.valueOf(Double.valueOf(epaEvaluateData.getCo2()) * 0.65));
                        temperatureResult.setCo(String.valueOf(epaEvaluateData.getCo()));
                        temperatureResult.setArithmeticType("2");
                        jsonObject2.put("co2", Double.valueOf(epaEvaluateData.getCo2()) * 0.65);
                        jsonObject2.put("co", epaEvaluateData.getCo());
                        setStep(jsonArray2, 1, "热点温度计算", jsonObject2.toJSONString(), String.valueOf(naturalAgingRate));
                    } else {
                        // 新算法 V*B2 V = 2^(h-98)/6
                        double t;
                        double v = 0;
                        for (int i = 0; i < winding.size(); i++) {
                            String temperature = winding.get(i).getMaxTmp();
                            BigDecimal h = BigDecimal.valueOf(Double.valueOf(temperature));
                            if (h.compareTo(BigDecimal.valueOf(400)) > 0) {
                                t = 322 * Math.log10(Double.valueOf(epaEvaluateData.getC2h4()) / Double.valueOf(epaEvaluateData.getC2h6())) + 525;
                            } else {
                                t = Double.valueOf(temperature);
                            }
                            Double v1 = Math.pow(2, (t - 98) / 6);
                            v = v + v1;
                        }
                        naturalAgingRate = (v / winding.size()) * B;
                        temperatureResult.setAgingCoefficient(String.valueOf(B));
                        temperatureResult.setWindingTemperature(String.valueOf(v / winding.size()));
                        temperatureResult.setArithmeticType("3");
                        jsonObject2.put("老化率", B);
                        jsonObject2.put("绕组温度", String.valueOf(v / winding.size()));
                        setStep(jsonArray2, 1, "热点温度计算", jsonObject2.toJSONString(), String.valueOf(naturalAgingRate));
                    }
                    temperatureResult.setResult(String.valueOf(naturalAgingRate));
                    temperatureResult.setCalculationStep(jsonArray2.toString());
                    hotSpotTemperatureResultDao.add(temperatureResult);
                    double surplus = transformerFormulaCalInstance.calcSurplus(correctionThealthyIndex, B);
                    log.info("--->> 变压器剩余寿命：[{}] ", surplus);
                    jsonObject.clear();
                    jsonObject.put("correctionThealthyIndex", correctionThealthyIndex);
                    jsonObject.put("B", B);
                    step += 1;
                    setStep(jsonArray, step, "变压器剩余寿命计算", jsonObject.toJSONString(), String.valueOf(B));

                    TransformerEvaluationResults result = new TransformerEvaluationResults();
                    result.setAgingRate(naturalAgingRate);
                    result.setEvaluateDate(LocalDateTime.now());
                    result.setExpectlife(expectlife);
                    result.setFutureFailureRate(futureFailureRate);
                    result.setId(Uuid.getUUID());
                    result.setMainTreeId(mainTreeId);
                    result.setScore((double) Math.round(100d * correctionThealthyIndex * 100) / 100);
                    result.setSurplusLife(surplus);
                    result.setDesignedLife(Double.valueOf(designLife));
                    result.setType("2");
                    this.tansfrerMsg(result, correctionThealthyIndex, jsonArray, step);
                    TransformerEvaluationDescUtil.evaluatDesc(result);
                    transformerEvaluationResultsService.save(result);

                    /*******************************评估中间变量******************************************/
                    intermediateValue.setOilChromatogramTest(individualInsulationMap.get("YSP_INDEX").toString());
                    intermediateValue.setFurfural(individualInsulationMap.get("KQ_INDEX").toString());
                    intermediateValue.setOilQualityTest(individualInsulationMap.get("YZSY_INDEX").toString());
                    intermediateValue.setInsulatingPaper(individualInsulationMap.get("JUZSY_INDEX").toString());
                    intermediateValue.setRoutineTest(individualInsulationMap.get("LXSY_INDEX").toString());
                    intermediateValue.setDiagnosticTest(individualInsulationMap.get("ZDSSY_INDEX").toString());

                    //绝缘运行状态健康指数
                    intermediateValue.setInsulationOperationHealthIndex(tmp2.toString());
                    //主绝缘老化健康状态
                    intermediateValue.setAgingHealthStatusOfMainInsulation(tmp1.toString());
                    //部件缺陷风险健康指数
                    intermediateValue.setComponentDefectRiskHealthIndex(tmp3.toString());
                    //最终健康水平指数
                    intermediateValue.setFinalHealthLevelIndex(healthyIndex.toString());


                    intermediateValue.setResultId(result.getId());
                    intermediateValue.setAgingRate(result.getAgingRate() + "");
                    intermediateValue.setExpectlife(result.getExpectlife() + "");
                    intermediateValue.setFutureFailureRate(result.getFutureFailureRate() + "");

                    intermediateValue.setMainTreeId(mainTreeId);
                    intermediateValue.setScore(result.getScore() + "");
                    intermediateValue.setHealthIndex(result.getHealthIndex());
                    intermediateValue.setAdvice(result.getAdvice());
                    intermediateValue.setSurplusLife(result.getSurplusLife() + "");
                    transformerEvaluationIntermediateValueService.save(intermediateValue);

                    // 新增算法步骤
                    calculateStep.setStepJson(jsonArray.toString());
                    calculateStep.setPId(result.getId());
                    Runnable runnable = () -> calculateStepService.insert(calculateStep);
                    new Thread(runnable).start();

                    ////临时注释，调测后放开
                    TransfromerCreateUtil.createFile(intermediateValue, true, basePath, filePath, fileName, date);
                } catch (Exception e) {
                    log.error("-->> 评测异常[{}]", e.getMessage());
                }
            }
        }
    }

    // 获取绕组测温数据
    private List<TransformerWindingTemperatureVo> getWindingTempreature(String mainEquipmentId) {
        String type = SiteConstants.TransfromerTreeEnum.RZCW_EQM.getValue();
        List<TransformerWindingTemperatureVo> results = new ArrayList<>();
        Date endDate = new Date();
        Date startDate = DateUtil.getIntervalDate(endDate, 8);
        List<BusiSiteTree> ids = transformerEpaDataOriginMapper.getSubId(mainEquipmentId, type);
        for (BusiSiteTree busiSiteTree : ids) {
            String id = busiSiteTree.getId();
            List<BusiTransformerSensor> sensorCodes = transformerEpaDataOriginMapper.getSensorCode(id);
            for (BusiTransformerSensor busiTransformerSensor : sensorCodes) {
                TransformerWindingTemperatureVo transformerWindingTemperatureVo = new TransformerWindingTemperatureVo();
                String sensorCode = busiTransformerSensor.getSensorCode();
                String temperature = transformerEpaDataOriginMapper.getTemperature(sensorCode, startDate, endDate);
                transformerWindingTemperatureVo.setMaxTmp(temperature);
                results.add(transformerWindingTemperatureVo);
            }
        }
        return results;
    }

    private String getEpaSensorCode(String id) {
        String deleted = SiteConstants.Status.NORMAL.getValue();
        String type = SiteConstants.TransfromerTreeEnum.YSP_EQM.getValue();
        String oilType = SiteConstants.oilType.OILTYPE1.getValue();
        return transformerEpaDataOriginMapper.getSensorCodeById(id, deleted, type, oilType);
    }

    /**
     * @Title: getTransformerAgingHealthIndex
     * @Description: 变压器主绝缘老化状态健康指数
     * @createDate: Aug 30, 2019 6:27:18 PM
     * @param    brand   变压器
     * @return Map<String, Object> map
     */
    private Map<String, Double> getTransformerAgingHealthIndex(BusiOfflineTransformerBrand brand, JSONArray jsonArray, int step) {
        Map<String, Double> map = new HashMap<>();
        String id = brand.getId();
        String siteId = brand.getSiteId();
        String name = brand.getTransformerName();
        String environmentlevel = brand.getEnvironmentLevel();
        LocalDate deliveryTime = brand.getEquipmentDeliveryTime();


        double FE = 1d;
        Date endDate2 = new Date();
        Date startDate2 = DateUtil.getIntervalDate(endDate2, 8);
        List<TemperatureEvaluateDataVo> temperaturelist = transformerMeteorologicalStatisticsMapper.selectStatistics(brand.getMainEquipmentId(), startDate2, endDate2);
        if (null != temperaturelist && temperaturelist.size() > 0) {
            double tmp = 0;
            int count = 0;
            for (TemperatureEvaluateDataVo temperatureEvaluateDataVo : temperaturelist) {
                if (StringUtil.isNotEmpty(temperatureEvaluateDataVo.getTemperature())) {
                    double temperature = Double.valueOf(temperatureEvaluateDataVo.getTemperature()).doubleValue();
                    tmp = tmp + temperature;
                    count = count + 1;
                }
            }
            if (count != 0) {
                FE = transformerFormulaCalInstance.calcEnvironmenCoefficient((double) tmp / count);
            }
        } else {
            FE = transformerFormulaCalInstance.calcEnvironmenCoefficient(environmentlevel);
        }


        step += 1;
        setStep(jsonArray, step, "计算变压器环境等级系数", environmentlevel, String.valueOf(FE));

        double FL = transformerFormulaCalInstance.calcLoadCoefficient(getTransformerLoad(siteId, id));
        step += 1;
        setStep(jsonArray, step, "计算负荷系数", String.valueOf(getTransformerLoad(siteId, id)), String.valueOf(FL));

        double TD = Double.valueOf(brand.getDesignLife() == null || brand.getDesignLife().equals("") ? "30" : brand.getDesignLife());
        // 预期运行寿命 T = TD/(FL*FE)
        double expectlife = transformerFormulaCalInstance.calcExpectRunningLife(FL, FE, TD);
        log.info("--->  变压器:{}, 预期使用寿命：{}", name, expectlife);
        com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
        jsonObject.put("FL", FL);
        jsonObject.put("FE", FE);
        jsonObject.put("TD", TD);
        step += 1;
        setStep(jsonArray, step, "计算变压器预期寿命", jsonObject.toJSONString(), String.valueOf(expectlife));

        // 老化系数
        double B0 = transformerFormulaCalInstance.calcInitAgingCoefficient(expectlife);
        log.info("---> 变压器初始老化系数 ：{}", B0);
        step += 1;
        setStep(jsonArray, step, "变压器初始老化系数", String.valueOf(expectlife), String.valueOf(B0));

        long dayDiff = instance.calcDateDifference(deliveryTime, LocalDate.now(), "YEARS");
        Double agingHealthIndex = transformerFormulaCalInstance.calcAgingHealthIndex(B0, dayDiff);
        log.info("---> 变压器主绝缘老化状态健康指数  ：{}", agingHealthIndex);
        jsonObject.clear();
        jsonObject.put("B0", B0);
        jsonObject.put("dayDiff", dayDiff);
        step += 1;
        setStep(jsonArray, step, "变压器主绝缘老化状态健康指数", jsonObject.toJSONString(), String.valueOf(agingHealthIndex));

        map.put("expectlife", expectlife);
        map.put("B0", B0);
        map.put("agingHealthIndex", agingHealthIndex);
        map.put("step", Double.valueOf(step));
        return map;
    }

    /**
     * @Title: getTransformerLoad
     * @Description: 获取变压器负荷
     * @createDate: Aug 30, 2019 2:28:10 PM
     * @param transformerId
     *            变压器ID
     * @return Double
     */
    private Double getTransformerLoad(String siteId, String transformerId) {
        LocalDate now = LocalDate.now();
        LocalDate loadTime = now.plusDays(-1);
        //TODO 老郭测试未修改
        //LocalDate localDate5 = LocalDate.parse("20200629", DateTimeFormatter.BASIC_ISO_DATE);
        //获取变压器负荷
        BusiTransformerLoad load = busiTransformerLoadService.getLoaByEquipmentIdAndDate(siteId, transformerId, loadTime);
        if (null != load) {
            Double value = Double.valueOf(load.getLoadRate()) * 100d;
            return value;
        }
        return 0d;
    }


    /**
     * @Title: getTransformerEvaluateData
     * @Description: 获取变压器评测数据
     * @createDate: Sep 4, 2019 10:24:37 AM
     * @param    mainTreeId  站点树ID
     * @return TransformerEvaluateDataVo
     */
    public TransformerEvaluateDataVo getTransformerEvaluateData(String mainTreeId) {
        TransformerEvaluateDataVo vo = transformerEvaluateDataService.getLastByMainTreeId(mainTreeId);
        return vo;
    }

    /**
     * @Title: getTransformerParams
     * @Description: 获取变压器评测参数
     * @createDate: Sep 4, 2019 3:38:43 PM
     * @param    siteId   站点id
     * @param    mainTreeId  站点树ID
     * @return List<BusiParamTransformerVo>
     */
    public List<BusiParamTransformerVo> getTransformerParams(String siteId, String mainTreeId) {
        return busiParamTransformerService.findParams(siteId, mainTreeId);
    }

    /**
     * @Title: convertParams
     * @Description: 转换参数形式
     * @createDate: Sep 4, 2019 3:56:05 PM
     * @param    level  等级
     * @param    list   参数
     * @return Map<String, BusiParamTransformerVo>
     */
    public Map<String, BusiParamTransformerVo> convertParams(String level, List<BusiParamTransformerVo> list) {
        List<BusiParamTransformerVo> convertorlist = null;
        convertorlist = list.stream().filter(vo -> vo.getWeightLevel().equalsIgnoreCase(level)).collect(Collectors.toList());
        Map<String, BusiParamTransformerVo> map = convertorlist.stream().collect(Collectors.toMap(BusiParamTransformerVo::getName, Function.identity()));
        return map;
    }

    /**
     * @Title: calcIndividualInsulation
     * @Description: 计算个体绝缘
     * @createDate: Sep 6, 2019 3:40:54 PM
     * @param
     * @return Double
     */
    public Map<String, Double> calcIndividualInsulation(TransformerEvaluateDataVo vo,
                                                        EpaEvaluateDataVo epaEvaluateData,
                                                        Map<String, BusiParamTransformerVo> secondLevelMap,
                                                        Map<String, BusiParamTransformerVo> threeLevelMap,
                                                        JSONArray jsonArray,
                                                        int step) {

        Map<String, Double> map = new HashMap<>();

        //油色谱
        Map<String, Object> map1 = this.calcOilChromatographicTestWeight(epaEvaluateData, secondLevelMap, threeLevelMap, jsonArray, step);
        Double yspWeight = Double.valueOf(map1.get("ysp").toString());
        step = Integer.valueOf(map1.get("step").toString());

        //油质试验
        Map<String, Object> map2 = this.calcOilQualityWeight(vo, secondLevelMap, threeLevelMap, jsonArray, step);
        Double yzsyWeight = Double.valueOf(map2.get("yzsy").toString());
        step = Integer.valueOf(map2.get("step").toString());

        // 声级振动
//		String soundlevel = vo.getVibrationSoundLevel();
//		BusiParamTransformerVo  tmp4 = this.getEvaluateObject(EvaluateConstant.ZDXSY_ZD_SJ, secondLevelMap);
//		Double calcWeight4 = this.calcWeight(soundlevel, tmp4);
//		log.info("-- >> 变压器绝缘试验--诊断性试验--震动、声级（变化率%）计算结果: [{}]", calcWeight4);
//		step += 1;
//		setStep(jsonArray, step, "变压器绝缘试验--诊断性试验--震动、声级（变化率%）计算", calculateModel(soundlevel, tmp4), String.valueOf(calcWeight4));

        //-糠醛指标
        Map<String, Object> map3 = this.calcFurIndexWeight(vo, secondLevelMap, threeLevelMap, jsonArray, step);
        Double kqzbWeight = Double.valueOf(map3.get("kqzb").toString());
        step = Integer.valueOf(map3.get("step").toString());

        //绝缘纸实验
        Map<String, Object> map4 = this.calcInsulationPaperWeight(vo, secondLevelMap, threeLevelMap, jsonArray, step);
        Double juzsyWeight = Double.valueOf(map4.get("jyz").toString());
        step = Integer.valueOf(map4.get("step").toString());

        //诊断性试验
        Map<String, Object> map5 = this.calcDiagnosticTestWeight(vo, secondLevelMap, threeLevelMap, jsonArray, step);
        Double zdssyWeight = Double.valueOf(map5.get("zdxsy").toString());
        step = Integer.valueOf(map5.get("step").toString());

        //例行试验
        Map<String, Object> map6 = this.calcRoutineTestWeight(vo, secondLevelMap, threeLevelMap, jsonArray, step);
        Double lxsyWeight = Double.valueOf(map6.get("lxsy").toString());
        step = Integer.valueOf(map6.get("step").toString());

//		double total = yspWeight+yzsyWeight+kqzbWeight+juzsyWeight+zdssyWeight+lxsyWeight + calcWeight4;
        double total = yspWeight + yzsyWeight + kqzbWeight + juzsyWeight + zdssyWeight + lxsyWeight;
        log.info("-- >>  变压器绝缘试验-个体绝缘计算结果: [{}]", total);
        step += 1;
        setStep(jsonArray, step, "变压器绝缘试验-个体绝缘计算", "", String.valueOf(total));

        map.put("YSP_INDEX", yspWeight);
        map.put("YZSY_INDEX", yzsyWeight);
        map.put("KQ_INDEX", kqzbWeight);
        map.put("JUZSY_INDEX", juzsyWeight);
        map.put("ZDSSY_INDEX", zdssyWeight);
        map.put("LXSY_INDEX", lxsyWeight);
        map.put("TOTAL_INDEX", total);
        map.put("step", Double.valueOf(step));
        return map;
    }


    /**
     * @Title: calcOilChromatographicTestWeight
     * @Description: 变压器绝缘试验-油色谱  权重计算
     * @createDate: Sep 4, 2019 6:24:47 PM
     * @param    secondLevelMap 二级分析参数
     * @param    threeLevelMap  三级分析参数
     * @return Double
     */
    private Map<String, Object> calcOilChromatographicTestWeight(EpaEvaluateDataVo epaEvaluateData, Map<String, BusiParamTransformerVo> secondLevelMap,
                                                                 Map<String, BusiParamTransformerVo> threeLevelMap, JSONArray jsonArray, int step) {
        double ysp = 0d;
        BusiParamTransformerVo YSP = this.getEvaluateObject(EvaluateConstant.YSP, secondLevelMap);
        if (null != YSP) {
            Map<String, Object> map = this.calcOilChromatographicTest(epaEvaluateData, threeLevelMap, jsonArray, step);
            Double tmp = Double.valueOf(map.get("ysp").toString());
            step = Integer.valueOf(map.get("step").toString());

            ysp = this.calcWeight(tmp, YSP);
            step += 1;
            setStep(jsonArray, step, "变压器绝缘试验-油色谱权重计算", calcWeight(YSP.getValue().doubleValue(), tmp), String.valueOf(ysp));
        }
        log.info("-- >>  变压器绝缘试验-油色谱权重计算结果: [{}]", ysp);

        Map<String, Object> map = Maps.newConcurrentMap();
        map.put("ysp", ysp);
        map.put("step", step);
        return map;
    }


    /**
     * @Title: calcInsulationPaperWeight
     * @Description: 变压器绝缘试验-绝缘纸实验 权重计算
     * @createDate: Sep 4, 2019 6:24:47 PM
     * @param    vo  评测数据
     * @param    secondLevelMap 二级分析参数
     * @param    threeLevelMap  三级分析参数
     * @return Double
     */
    private Map<String, Object> calcInsulationPaperWeight(TransformerEvaluateDataVo vo, Map<String, BusiParamTransformerVo> secondLevelMap,
                                                          Map<String, BusiParamTransformerVo> threeLevelMap, JSONArray jsonArray, int step) {
        double jyz = 0d;
        BusiParamTransformerVo JYZ = this.getEvaluateObject(EvaluateConstant.JYZ, secondLevelMap);
        if (null != JYZ) {
            Double tmp = this.calcInsulationPaperExperiment(vo, threeLevelMap);
            step += 1;
            setStep(jsonArray, step, "变压器绝缘试验-绝缘纸实验--分项和计算", vo.getDegreeCardboard(), String.valueOf(tmp));
            jyz = this.calcWeight(tmp, JYZ);
            step += 1;
            setStep(jsonArray, step, "变压器绝缘试验-绝缘纸实验权重计算", calcWeight(JYZ.getValue().doubleValue(), tmp), String.valueOf(jyz));
        }
        log.info("-- >>  变压器绝缘试验-绝缘纸实验权重计算结果: [{}]", jyz);

        Map<String, Object> map = Maps.newConcurrentMap();
        map.put("step", step);
        map.put("jyz", jyz);
        return map;
    }


    /**
     * @Title: calcFurIndexWeight
     * @Description: 变压器绝缘试验-糠醛指标 权重计算
     * @createDate: Sep 4, 2019 6:24:47 PM
     * @param    vo  评测数据
     * @param    secondLevelMap 二级分析参数
     * @param    threeLevelMap  三级分析参数
     * @return Double
     */
    private Map<String, Object> calcFurIndexWeight(TransformerEvaluateDataVo vo, Map<String, BusiParamTransformerVo> secondLevelMap,
                                                   Map<String, BusiParamTransformerVo> threeLevelMap, JSONArray jsonArray, int step) {
        double kqzb = 0d;
        BusiParamTransformerVo KQZB = this.getEvaluateObject(EvaluateConstant.KQZB, secondLevelMap);
        if (null != KQZB) {
            Double tmp = this.calcFurfuralIndex(vo, threeLevelMap);
            step += 1;
            setStep(jsonArray, step, "变压器绝缘试验-糠醛指标--分项和计算", vo.getFurfural(), String.valueOf(tmp));

            kqzb = this.calcWeight(tmp, KQZB);
            step += 1;
            setStep(jsonArray, step, "变压器绝缘试验-糠醛指标权重计算", calcWeight(KQZB.getValue().doubleValue(), tmp), String.valueOf(kqzb));
        }
        log.info("-- >>  变压器绝缘试验-糠醛指标权重计算结果: [{}]", kqzb);

        Map<String, Object> map = Maps.newConcurrentMap();
        map.put("step", step);
        map.put("kqzb", kqzb);
        return map;
    }

    /**
     * @Title: calcOilQualityWeight
     * @Description: 变压器绝缘试验-油质试验 权重计算
     * @createDate: Sep 4, 2019 6:24:47 PM
     * @param    vo  评测数据
     * @param    secondLevelMap 二级分析参数
     * @param    threeLevelMap  三级分析参数
     * @return Double
     */
    private Map<String, Object> calcOilQualityWeight(TransformerEvaluateDataVo vo, Map<String, BusiParamTransformerVo> secondLevelMap,
                                                     Map<String, BusiParamTransformerVo> threeLevelMap, JSONArray jsonArray, int step) {
        double yzsy = 0d;
        BusiParamTransformerVo YZSY = this.getEvaluateObject(EvaluateConstant.YZSY, secondLevelMap);
        if (null != YZSY) {
            Map<String, Object> map1 = this.calcOilQualityTest(vo, threeLevelMap, jsonArray, step);
            Double tmp = Double.valueOf(map1.get("yzsy").toString());
            step = Integer.valueOf(map1.get("step").toString());

            yzsy = this.calcWeight(tmp, YZSY);
            step += 1;
            setStep(jsonArray, step, "变压器绝缘试验-油色谱权重计算", calcWeight(YZSY.getValue().doubleValue(), tmp), String.valueOf(yzsy));
        }
        log.info("-- >> 变压器绝缘试验-油质试验权重计算结果: [{}]", yzsy);

        Map<String, Object> map = Maps.newConcurrentMap();
        map.put("step", step);
        map.put("yzsy", yzsy);
        return map;
    }

    /**
     * @Title: calcDiagnosticTestWeight
     * @Description: 变压器绝缘试验-诊断性试验 权重计算
     * @createDate: Sep 4, 2019 6:24:47 PM
     * @param    vo  评测数据
     * @param    secondLevelMap 二级分析参数
     * @param    threeLevelMap  三级分析参数
     * @return Double
     */
    private Map<String, Object> calcDiagnosticTestWeight(TransformerEvaluateDataVo vo, Map<String, BusiParamTransformerVo> secondLevelMap,
                                                         Map<String, BusiParamTransformerVo> threeLevelMap, JSONArray jsonArray, int step) {
        double zdxsy = 0d;
        BusiParamTransformerVo ZDXSY = this.getEvaluateObject(EvaluateConstant.ZDXSY, secondLevelMap);
        if (null != ZDXSY) {
            Map<String, Object> map = this.calcDiagnosticTest(vo, threeLevelMap, jsonArray, step);
            Double tmp = Double.valueOf(map.get("zdsy").toString());
            step = Integer.valueOf(map.get("step").toString());

            zdxsy = this.calcWeight(tmp, ZDXSY);
            step += 1;
            setStep(jsonArray, step, "变压器绝缘试验-诊断性试验权重计算", calcWeight(ZDXSY.getValue().doubleValue(), tmp), String.valueOf(zdxsy));
        }
        log.info("-- >>  变压器绝缘试验-诊断性试验权重计算结果: [{}]", zdxsy);

        Map<String, Object> map = Maps.newConcurrentMap();
        map.put("step", step);
        map.put("zdxsy", zdxsy);
        return map;
    }

    /**
     * @Title: calcRoutineTestWeight
     * @Description: 变压器绝缘试验-例行试验 权重计算
     * @createDate: Sep 4, 2019 6:24:47 PM
     * @param    vo  评测数据
     * @param    secondLevelMap 二级分析参数
     * @param    threeLevelMap  三级分析参数
     * @return Double
     */
    private Map<String, Object> calcRoutineTestWeight(TransformerEvaluateDataVo vo, Map<String, BusiParamTransformerVo> secondLevelMap,
                                                      Map<String, BusiParamTransformerVo> threeLevelMap, JSONArray jsonArray, int step) {
        double lxsy = 0d;
        BusiParamTransformerVo LXSY = this.getEvaluateObject(EvaluateConstant.LXSY, secondLevelMap);
        if (null != LXSY) {
            Map<String, Object> map = this.calcRoutineTest(vo, threeLevelMap, jsonArray, step);
            Double tmp = Double.valueOf(map.get("lxsy").toString());
            step = Integer.valueOf(map.get("step").toString());

            lxsy = this.calcWeight(tmp, LXSY);
            step += 1;
            setStep(jsonArray, step, "变压器绝缘试验-例行试验权重计算", calcWeight(tmp, LXSY.getValue().doubleValue()), String.valueOf(lxsy));
        }
        log.info("-- >>  变压器绝缘试验-例行试验权重计算结果: [{}]", lxsy);

        Map<String, Object> map = Maps.newConcurrentMap();
        map.put("step", step);
        map.put("lxsy", lxsy);
        return map;
    }

    /**
     * @Title: getTransformerlist
     * @Description: 获取变压器列表
     * @createDate: Aug 30, 2019 1:24:54 PM
     * @return List<BusiOfflineTransformerBrand>
     */
    private List<BusiOfflineTransformerBrand> getTransformerlist() {
        return busiOfflineTransformerBrandService.findAll();
    }


    /**
     * @Title: calcoilChromatographicTest
     * @Description: 变压器绝缘试验-油色谱 分项和
     * @createDate: Sep 5, 2019 2:40:38 PM
     * @param    vo  油色谱评测数据
     * @param    map 分析参数
     * @return Double
     */
    public Map<String, Object> calcOilChromatographicTest(EpaEvaluateDataVo vo, Map<String, BusiParamTransformerVo> map, JSONArray jsonArray, int step) {

        BusiParamTransformerVo tmp1 = this.getEvaluateObject(EvaluateConstant.H2, map);

        BusiParamTransformerVo tmp2 = this.getEvaluateObject(EvaluateConstant.CO, map);

        BusiParamTransformerVo tmp3 = this.getEvaluateObject(EvaluateConstant.CO2, map);

        BusiParamTransformerVo tmp4 = this.getEvaluateObject(EvaluateConstant.CH4, map);

        BusiParamTransformerVo tmp5 = this.getEvaluateObject(EvaluateConstant.C2H2, map);

        BusiParamTransformerVo tmp6 = this.getEvaluateObject(EvaluateConstant.C2H4, map);

        BusiParamTransformerVo tmp7 = this.getEvaluateObject(EvaluateConstant.C2H6, map);

        BusiParamTransformerVo tmp8 = this.getEvaluateObject(EvaluateConstant.ZT, map);

        Double calcWeight = this.calcWeight(vo.getH2(), tmp1);
        log.info("-- >> 变压器绝缘试验-油色谱--H2计算结果: [{}]", calcWeight);
        step += 1;
        setStep(jsonArray, step, "变压器绝缘试验-油色谱--H2计算", calculateModel(vo.getH2(), tmp1), String.valueOf(calcWeight));

        Double calcWeight6 = this.calcWeight(vo.getCo(), tmp2);
        log.info("-- >> 变压器绝缘试验-油色谱--CO计算结果: [{}]", calcWeight6);
        step += 1;
        setStep(jsonArray, step, "变压器绝缘试验-油色谱--CO计算", calculateModel(vo.getCo(), tmp2), String.valueOf(calcWeight6));

        Double calcWeight7 = this.calcWeight(vo.getCo2(), tmp3);
        log.info("-- >> 变压器绝缘试验-油色谱--CO2计算结果: [{}]", calcWeight7);
        step += 1;
        setStep(jsonArray, step, "变压器绝缘试验-油色谱--CO2计算", calculateModel(vo.getCo2(), tmp3), String.valueOf(calcWeight7));

        Double calcWeight2 = this.calcWeight(vo.getCh4(), tmp4);
        log.info("-- >> 变压器绝缘试验-油色谱--CH4计算结果: [{}]", calcWeight2);
        step += 1;
        setStep(jsonArray, step, "变压器绝缘试验-油色谱--CH4计算", calculateModel(vo.getCh4(), tmp4), String.valueOf(calcWeight2));

        Double calcWeight3 = this.calcWeight(vo.getC2h2(), tmp5);
        log.info("-- >> 变压器绝缘试验-油色谱--C2H2计算结果: [{}]", calcWeight3);
        step += 1;
        setStep(jsonArray, step, "变压器绝缘试验-油色谱--C2H2计算", calculateModel(vo.getC2h2(), tmp5), String.valueOf(calcWeight3));

        Double calcWeight4 = this.calcWeight(vo.getC2h4(), tmp6);
        log.info("-- >> 变压器绝缘试验-油色谱--C2H4计算结果: [{}]", calcWeight4);
        step += 1;
        setStep(jsonArray, step, "变压器绝缘试验-油色谱--C2H4计算", calculateModel(vo.getC2h4(), tmp6), String.valueOf(calcWeight4));

        Double calcWeight5 = this.calcWeight(vo.getC2h6(), tmp7);
        log.info("-- >> 变压器绝缘试验-油色谱--C2H6计算结果: [{}]", calcWeight5);
        step += 1;
        setStep(jsonArray, step, "变压器绝缘试验-油色谱--C2H6计算", calculateModel(vo.getC2h6(), tmp7), String.valueOf(calcWeight5));

        Double calcWeight8 = this.calcWeight(vo.getZt(), tmp8);
        log.info("-- >> 变压器绝缘试验-油色谱--总烃计算结果: [{}]", calcWeight8);
        step += 1;
        setStep(jsonArray, step, "变压器绝缘试验-油色谱--总烃计算", calculateModel(vo.getZt(), tmp8), String.valueOf(calcWeight8));
/*
		Double calcWeight9 = 0d;
		Double calcWeight10 = 0d;
		Double calcWeight11 = 0d;
		Double calcWeight12 = 0d;
		BusiParamTransformerVo tmp9 = this.getEvaluateObject(EvaluateConstant.CO_CQ, map);
		if(tmp9.getIsAttend().equals("1")){
			calcWeight9 = tmp9.getValue().doubleValue();
		}
		BusiParamTransformerVo tmp10 = this.getEvaluateObject(EvaluateConstant.CO_XD_CQ, map);
		if(tmp10.getIsAttend().equals("1")){
			calcWeight10 = tmp10.getValue().doubleValue();
		}
		BusiParamTransformerVo tmp11= this.getEvaluateObject(EvaluateConstant.CO2_CQ, map);
		if(tmp11.getIsAttend().equals("1")){
			calcWeight11 = tmp11.getValue().doubleValue();
		}
		BusiParamTransformerVo tmp12 = this.getEvaluateObject(EvaluateConstant.CO2_XD_CQ, map);
		if(tmp12.getIsAttend().equals("1")){
			calcWeight12 = tmp12.getValue().doubleValue();
		}

		double ysp = calcWeight+calcWeight2+calcWeight3+calcWeight4+calcWeight5+calcWeight6+calcWeight7
				+calcWeight8+calcWeight9+calcWeight10+calcWeight11+calcWeight12;

 */
        double ysp = calcWeight + calcWeight2 + calcWeight3 + calcWeight4 + calcWeight5 + calcWeight6 + calcWeight7
                + calcWeight8;
        log.info("-- >> 变压器绝缘试验-油色谱-分项和计算结果: [{}]", ysp);
        step += 1;
        setStep(jsonArray, step, "变压器绝缘试验-油色谱-分项和计算", "", String.valueOf(ysp));

        Map<String, Object> map1 = Maps.newConcurrentMap();
        map1.put("step", step);
        map1.put("ysp", ysp);
        return map1;
    }


    /**
     * @Title: getEpaEvaluateData
     * @Description: 获取油色谱评测数据
     * @createDate: Sep 6, 2019 2:37:34 PM
     * @param    mainEquipmentId  主设备id
     * @return EpaEvaluateDataVo
     */
    public EpaEvaluateDataVo getEpaEvaluateData(String mainEquipmentId, String sensorCode) {
        //TODO
        Date endDate = new Date();
        Date startDate = DateUtil.getIntervalDate(endDate, 8);
        EpaEvaluateDataVo vo = transformerEpaDataOriginMapper.getEvaluatData(mainEquipmentId, startDate, endDate, sensorCode);
        log.info("-- >> 油色谱评测数据:[{}]", vo);
        return vo;
    }

    /**
     * @Title: calcOilQualityTest
     * @Description: 变压器绝缘试验-油质试验计算
     * @createDate: Sep 4, 2019 6:02:20 PM
     * @param    vo  评测数据
     * @param    map 分析参数
     * @return Double
     */
    public Map<String, Object> calcOilQualityTest(TransformerEvaluateDataVo vo, Map<String, BusiParamTransformerVo> map, JSONArray jsonArray, int step) {
        String waterInOil = vo.getWaterInOil();
        String oillMedium = vo.getOillMedium();
        String oilBreakdownVoltage = vo.getOilBreakdownVoltage();

        BusiParamTransformerVo tmp1 = this.getEvaluateObject(EvaluateConstant.YZSY_WS, map);
        Double calcWeight = this.calcWeight(waterInOil, tmp1);
        log.info("-- >> 变压器绝缘试验--油质试验--油中微水计算结果: [{}]", calcWeight);
        step += 1;
        setStep(jsonArray, step, "变压器绝缘试验--油质试验--油中微水计算", calculateModel(waterInOil, tmp1), String.valueOf(calcWeight));

        BusiParamTransformerVo tmp2 = this.getEvaluateObject(EvaluateConstant.YZSY_YJS, map);
        Double calcWeight2 = this.calcWeight(oillMedium, tmp2);
        log.info("-- >> 变压器绝缘试验--油质试--验油介损计算结果: [{}]", calcWeight2);
        step += 1;
        setStep(jsonArray, step, "变压器绝缘试验--油质试--验油介损计算", calculateModel(oillMedium, tmp2), String.valueOf(calcWeight2));

        BusiParamTransformerVo tmp3 = this.getEvaluateObject(EvaluateConstant.YZSY_YJCDY, map);
        Double calcWeight3 = this.calcWeight(oilBreakdownVoltage, tmp3);
        log.info("-- >> 变压器绝缘试验--油质试验--油击穿电压（Kv)计算结果: [{}]", calcWeight3);
        step += 1;
        setStep(jsonArray, step, "变压器绝缘试验--油质试验--油击穿电压（Kv)计算", calculateModel(oilBreakdownVoltage, tmp3), String.valueOf(calcWeight3));

        Double yzsy = calcWeight + calcWeight2 + calcWeight3;
        log.info("-- >> 变压器绝缘试验-油质试验-分项和计算结果: [{}]", yzsy);
        step += 1;
        setStep(jsonArray, step, "变压器绝缘试验-油质试验-分项和计算", "", String.valueOf(yzsy));

        Map<String, Object> map1 = Maps.newConcurrentMap();
        map1.put("step", step);
        map1.put("yzsy", yzsy);
        return map1;
    }


    /**
     * @Title: calcFurfuralIndex
     * @Description: 变压器绝缘试验-糠醛指标
     * @createDate: Sep 4, 2019 4:19:01 PM
     * @param    vo  评测数据
     * @param    map 分析参数
     * @return Double
     */
    public Double calcFurfuralIndex(TransformerEvaluateDataVo vo, Map<String, BusiParamTransformerVo> map) {
        double kqzb = 0d;
        BusiParamTransformerVo param = this.getEvaluateObject(EvaluateConstant.KQZB_KQHL, map);
        String furfural = vo.getFurfural();
        if (null != param && param.getIsAttend().equals("1") && StringUtils.isNoneBlank(furfural)) {
            double DP_A = param.getAValue().doubleValue();
            double DP_B = param.getBValue().doubleValue();
            double FFA = Double.valueOf(furfural);
            if (FFA < DP_A) {
                kqzb = 1d;
            } else if (DP_A < FFA && FFA < DP_B) {
                double b = DP_B - DP_A;
                double a = DP_B - FFA;
                double d = a / b;
                kqzb = new BigDecimal(d).setScale(4, RoundingMode.HALF_UP).doubleValue();
            } else if (DP_B < FFA && DP_B == FFA) {
                kqzb = 0d;
            }
        }
        log.info("-- >> 变压器绝缘试验-糠醛指标--分项和计算结果: [{}]", kqzb);
        return kqzb;
    }

    /**
     * @Title: calcInsulationPaperExperiment
     * @Description: 变压器绝缘试验-绝缘纸实验
     * @createDate: Sep 4, 2019 4:56:01 PM
     * @param    vo  评测数据
     * @param    map 分析参数
     * @return Double
     */
    public Double calcInsulationPaperExperiment(TransformerEvaluateDataVo vo, Map<String, BusiParamTransformerVo> map) {
        double jyz = 0d;
        BusiParamTransformerVo param = this.getEvaluateObject(EvaluateConstant.JYZ_ZBJHD, map);
        String degreeCardboard = vo.getDegreeCardboard();
        if (null != param && param.getIsAttend().equals("1") && StringUtils.isNoneBlank(degreeCardboard)) {
            double DP_A = param.getAValue().doubleValue();
            double DP_B = param.getBValue().doubleValue();
            double FFA = Double.valueOf(degreeCardboard);
            if ((0 < FFA || FFA == 0) && FFA < DP_A) {
                jyz = 0d;
            } else if ((DP_A < FFA || FFA == DP_A) && FFA < DP_B) {
                double d = (FFA - DP_A) / (DP_B - DP_A);
                jyz = new BigDecimal(d).setScale(4, RoundingMode.HALF_UP).doubleValue();
            } else if (DP_B < FFA || FFA == DP_B) {
                jyz = 1d;
            }
        }
        log.info("-- >> 变压器绝缘试验-绝缘纸实验--分项和计算结果: [{}]", jyz);
        return jyz;
    }


    /**
     * @Title: calcDiagnosticTest
     * @Description: 变压器绝缘试验-诊断性试验    各分项和
     * @createDate: Sep 5, 2019 10:27:22 AM
     * @param    vo  评测数据
     * @param    map 分析参数
     * @return Double
     */
    public Map<String, Object> calcDiagnosticTest(TransformerEvaluateDataVo vo, Map<String, BusiParamTransformerVo> map, JSONArray jsonArray, int step) {
        //绝缘纸含水量
        String waterPage = vo.getWaterContentOfInsulatingPaper();
        //空载电流、空载损耗变化率（%）
        String noload = vo.getNoloadCurrentAndNoloadLossRate();
        //短路阻抗变化率(%)
        String shortCircuit = vo.getShortCircuitImpedanceChangeRate();
        //绕组直流泄漏电流（μA）
        String dcleak = vo.getDcLeakageCurrentWinding();

        BusiParamTransformerVo tmp = this.getEvaluateObject(EvaluateConstant.ZDXSY_YJZHSL, map);
        Double calcWeight = this.calcWeight(waterPage, tmp);
        log.info("-- >> 变压器绝缘试验--诊断性试验--绝缘纸含水量计算结果: [{}]", calcWeight);
        step += 1;
        setStep(jsonArray, step, "变压器绝缘试验--诊断性试验--绝缘纸含水量计算", calculateModel(waterPage, tmp), String.valueOf(calcWeight));

        BusiParamTransformerVo tmp2 = this.getEvaluateObject(EvaluateConstant.ZDXSY_KZDL_KZSHL, map);
        Double calcWeight2 = this.calcWeight(noload, tmp2);
        log.info("-- >> 变压器绝缘试验--诊断性试验--空载电流、空载损耗变化率（%）计算结果: [{}]", calcWeight2);
        step += 1;
        setStep(jsonArray, step, "变压器绝缘试验--诊断性试验--空载电流、空载损耗变化率（%）计算", calculateModel(noload, tmp2), String.valueOf(calcWeight2));

        BusiParamTransformerVo tmp3 = this.getEvaluateObject(EvaluateConstant.ZDXSY_DLZKBHL, map);
        Double calcWeight3 = this.calcWeight(shortCircuit, tmp3);
        log.info("-- >> 变压器绝缘试验--诊断性试验--短路阻抗变化率(%)计算结果: [{}]", calcWeight3);
        step += 1;
        setStep(jsonArray, step, "变压器绝缘试验--诊断性试验--短路阻抗变化率(%)计算", calculateModel(shortCircuit, tmp3), String.valueOf(calcWeight3));

        BusiParamTransformerVo tmp5 = this.getEvaluateObject(EvaluateConstant.ZDXSY_RZZL_XLDL, map);
        Double calcWeight5 = this.calcWeight(dcleak, tmp5);
        log.info("-- >> 变压器绝缘试验--诊断性试验--绕组直流泄漏电流计算结果: [{}]", calcWeight5);
        step += 1;
        setStep(jsonArray, step, "变压器绝缘试验--诊断性试验--绕组直流泄漏电流计算", calculateModel(dcleak, tmp5), String.valueOf(calcWeight5));

        Double zdsy = calcWeight + calcWeight2 + calcWeight3 + calcWeight5;
        log.info("-- >> 变压器绝缘试验--诊断性试验-分项和计算结果: [{}]", zdsy);
        step += 1;
        setStep(jsonArray, step, "变压器绝缘试验--诊断性试验-分项和计算", "", String.valueOf(zdsy));

        Map<String, Object> map1 = Maps.newConcurrentMap();
        map1.put("step", step);
        map1.put("zdsy", zdsy);
        return map1;
    }


    /**
     * @Title: calcRoutineTest
     * @Description: 变压器绝缘试验-例行试验  各分项和
     * @createDate: Sep 5, 2019 11:15:07 AM
     * @param    vo  评测数据
     * @param    map 分析参数
     * @return Double
     */
    public Map<String, Object> calcRoutineTest(TransformerEvaluateDataVo vo, Map<String, BusiParamTransformerVo> map, JSONArray jsonArray, int step) {
        //极化指数
        String polarizatioIndex = vo.getPolarizatioIndex();
        //局放放电量
        String partialDischarge = vo.getPartialDischarge();
        //绝缘电阻(MΩ)
        String insulationResistance = vo.getInsulationResistance();
        //绝缘电阻吸收比
        String insulationResistanceAbsorptionRatio = vo.getInsulationResistanceAbsorptionRatio();
        //绕组直流电阻相间差(%)
        String phaseDifferenceDcResistance = vo.getPhaseDifferenceDcResistance();
        //绕组直流电阻线间差(%)
        String lineDifferenceDcResistance = vo.getLineDifferenceDcResistance();
        //绕组绝缘介损
        String windingInsulationDielectricLoss = vo.getWindingInsulationDielectricLoss();
        //铁芯绝缘电阻（MΩ）
        String coreInsulationResistance = vo.getCoreInsulationResistance();
        //末屏绝缘电阻（MΩ）
        String endScreenInsulationResistance = vo.getEndScreenInsulationResistance();
        //套管介损
        String casingloss = vo.getCasingDielectricLoss();
        //套管H2
        String casingh2 = vo.getCasingH2();
        //套管CH4
        String casingCh4 = vo.getCasingCh4();
        //套管C2H2
        String casingC2h2 = vo.getCasingC2h2();

        BusiParamTransformerVo tmp = this.getEvaluateObject(EvaluateConstant.LXSY_JHZS, map);
        Double calcWeight = this.calcWeight(polarizatioIndex, tmp);
        log.info("-- >> 变压器绝缘试验--例行试验--极化指数计算结果: [{}]", calcWeight);
        step += 1;
        setStep(jsonArray, step, "变压器绝缘试验--例行试验--极化指数计算", calculateModel(polarizatioIndex, tmp), String.valueOf(calcWeight));

        BusiParamTransformerVo tmp2 = this.getEvaluateObject(EvaluateConstant.LXSY_JFFDL, map);
        Double calcWeight2 = this.calcWeight(partialDischarge, tmp2);
        log.info("-- >> 变压器绝缘试验--例行试验--局放放电量计算结果: [{}]", calcWeight2);
        step += 1;
        setStep(jsonArray, step, "变压器绝缘试验--例行试验--局放放电量计算", calculateModel(partialDischarge, tmp2), String.valueOf(calcWeight2));

        BusiParamTransformerVo tmp3 = this.getEvaluateObject(EvaluateConstant.LXSY_JYDZ, map);
        Double calcWeight3 = this.calcWeight(insulationResistance, tmp3);
        log.info("-- >> 变压器绝缘试验--例行试验--绝缘电阻(MΩ)计算结果: [{}]", calcWeight3);
        step += 1;
        setStep(jsonArray, step, "变压器绝缘试验--例行试验--绝缘电阻(MΩ)计算", calculateModel(insulationResistance, tmp3), String.valueOf(calcWeight3));

        BusiParamTransformerVo tmp4 = this.getEvaluateObject(EvaluateConstant.LXSY_JYDZ_SHB, map);
        Double calcWeight4 = this.calcWeight(insulationResistanceAbsorptionRatio, tmp4);
        log.info("-- >> 变压器绝缘试验--例行试验--绝缘电阻吸收比计算结果: [{}]", calcWeight4);
        step += 1;
        setStep(jsonArray, step, "变压器绝缘试验--例行试验--绝缘电阻吸收比计算", calculateModel(insulationResistanceAbsorptionRatio, tmp4), String.valueOf(calcWeight4));

        BusiParamTransformerVo tmp5 = this.getEvaluateObject(EvaluateConstant.LXSY_RZZL_DZXJC, map);
        Double calcWeight5 = this.calcWeight(phaseDifferenceDcResistance, tmp5);
        log.info("-- >> 变压器绝缘试验--例行试验--绕组直流电阻相间差(%)计算结果: [{}]", calcWeight5);
        step += 1;
        setStep(jsonArray, step, "变压器绝缘试验--例行试验--绕组直流电阻相间差(%)计算", calculateModel(phaseDifferenceDcResistance, tmp5), String.valueOf(calcWeight5));

        BusiParamTransformerVo tmp6 = this.getEvaluateObject(EvaluateConstant.LXSY_RZZL_DZXJC2, map);
        Double calcWeight6 = this.calcWeight(lineDifferenceDcResistance, tmp6);
        log.info("-- >> 变压器绝缘试验--例行试验--绕组直流电阻线间差(%)计算结果: [{}]", calcWeight6);
        step += 1;
        setStep(jsonArray, step, "变压器绝缘试验--例行试验--绕组直流电阻线间差(%)计算", calculateModel(lineDifferenceDcResistance, tmp6), String.valueOf(calcWeight6));

        BusiParamTransformerVo tmp7 = this.getEvaluateObject(EvaluateConstant.LXSY_RZJYJS, map);
        Double calcWeight7 = this.calcWeight(windingInsulationDielectricLoss, tmp7);
        log.info("-- >> 变压器绝缘试验--例行试验--绕组绝缘介损计算结果: [{}]", calcWeight7);
        step += 1;
        setStep(jsonArray, step, "变压器绝缘试验--例行试验--绕组绝缘介损计算", calculateModel(windingInsulationDielectricLoss, tmp7), String.valueOf(calcWeight7));

        BusiParamTransformerVo tmp8 = this.getEvaluateObject(EvaluateConstant.LXSY_TXJDDZ, map);
        Double calcWeight8 = this.calcWeight(coreInsulationResistance, tmp8);
        log.info("-- >> 变压器绝缘试验--例行试验--铁芯绝缘电阻（MΩ）计算结果: [{}]", calcWeight8);
        step += 1;
        setStep(jsonArray, step, "变压器绝缘试验--例行试验--铁芯绝缘电阻（MΩ）计算", calculateModel(coreInsulationResistance, tmp8), String.valueOf(calcWeight8));

        BusiParamTransformerVo tmp9 = this.getEvaluateObject(EvaluateConstant.LXSY_MPJYDZ, map);
        Double calcWeight9 = this.calcWeight(endScreenInsulationResistance, tmp9);
        log.info("-- >> 变压器绝缘试验--例行试验--末屏绝缘电阻（MΩ）计算结果: [{}]", calcWeight9);
        step += 1;
        setStep(jsonArray, step, "变压器绝缘试验--例行试验--末屏绝缘电阻（MΩ）计算", calculateModel(endScreenInsulationResistance, tmp9), String.valueOf(calcWeight9));

        BusiParamTransformerVo tmp10 = this.getEvaluateObject(EvaluateConstant.FJTG_TGJS, map);
        Double calcWeight10 = this.calcWeight(casingloss, tmp10);
        log.info("-- >> 变压器绝缘试验--例行试验--套管介损计算结果: [{}]", calcWeight10);
        step += 1;
        setStep(jsonArray, step, "变压器绝缘试验--例行试验--套管介损计算", calculateModel(casingloss, tmp10), String.valueOf(calcWeight10));

        BusiParamTransformerVo tmp11 = this.getEvaluateObject(EvaluateConstant.FJTG_TGH2, map);
        Double calcWeight11 = this.calcWeight(casingh2, tmp11);
        log.info("-- >> 变压器绝缘试验--例行试验--套管H2计算结果: [{}]", calcWeight11);
        step += 1;
        setStep(jsonArray, step, "变压器绝缘试验--例行试验--套管H2计算", calculateModel(casingh2, tmp11), String.valueOf(calcWeight11));

        BusiParamTransformerVo tmp12 = this.getEvaluateObject(EvaluateConstant.FJTG_TGCH4, map);
        Double calcWeight12 = this.calcWeight(casingCh4, tmp12);
        log.info("-- >> 变压器绝缘试验--例行试验--套管CH4计算结果: [{}]", calcWeight12);
        step += 1;
        setStep(jsonArray, step, "变压器绝缘试验--例行试验--套管CH4计算", calculateModel(casingCh4, tmp12), String.valueOf(calcWeight12));

        BusiParamTransformerVo tmp13 = this.getEvaluateObject(EvaluateConstant.FJTG_TGC2H2, map);
        Double calcWeight13 = this.calcWeight(casingC2h2, tmp13);
        log.info("-- >> 变压器绝缘试验--例行试验--套管C2H2计算结果: [{}]", calcWeight13);
        step += 1;
        setStep(jsonArray, step, "变压器绝缘试验--例行试验--套管C2H2计算", calculateModel(casingC2h2, tmp13), String.valueOf(calcWeight13));

        Double lxsy = calcWeight + calcWeight2 + calcWeight3 + calcWeight4 + calcWeight5 + calcWeight6
                + calcWeight7 + calcWeight8 + calcWeight9 + calcWeight10 + calcWeight11 + calcWeight12 + calcWeight13;
        log.info("-- >> 变压器绝缘试验--例行试验-分项和计算结果: [{}]", lxsy);
        step += 1;
        setStep(jsonArray, step, "变压器绝缘试验--例行试验-分项和计算", "", String.valueOf(lxsy));

        Map<String, Object> map1 = Maps.newConcurrentMap();
        map1.put("step", step);
        map1.put("lxsy", lxsy);
        return map1;
    }

    /**
     * @Title: getEvaluateWeight
     * @Description: 获取评测权重
     * @createDate: Sep 4, 2019 4:04:29 PM
     * @param    key
     * @return Double
     */
    public Double getEvaluateWeight(String key, Map<String, BusiParamTransformerVo> map) {
        if (map.containsKey(key)) {
            return map.get(key).getValue().doubleValue();
        }
        return 0d;
    }

    /**
     * @Title: calcWeight
     * @Description: 计算权重
     * @createDate: Sep 6, 2019 3:28:47 PM
     * @param
     * @return Double
     * @throws
     */
    public Double calcWeight(double value, BusiParamTransformerVo vo) {
        if (vo.getIsAttend().equals("1")) {
            double weight = vo.getValue().doubleValue();
            double d = value * weight;
            return new BigDecimal(d).setScale(4, RoundingMode.HALF_UP).doubleValue();
        }
        return 0d;
    }

    /**
     * @Title: getEvaluateObject
     * @Description: 获取评测对象
     * @createDate: Sep 4, 2019 4:04:29 PM
     * @param    key
     * @return BusiParamTransformerVo
     */
    public BusiParamTransformerVo getEvaluateObject(String key, Map<String, BusiParamTransformerVo> map) {
        if (map.containsKey(key)) {
            return map.get(key);
        }
        return null;
    }


    /**
     * @Title: calcWeight
     * @Description: 计算权重
     * @createDate: Sep 4, 2019 5:53:23 PM
     * @param    testValue  测试值
     * @return Double
     */
    public Double calcWeight(String testValue, BusiParamTransformerVo vo) {
        if (StringUtils.isBlank(testValue)) {
            return 0d;
        }
        Double aValue = vo.getAValue().doubleValue();
        Double bValue = vo.getBValue().doubleValue();
        ;
        Double weight = vo.getValue().doubleValue();
        ;
        String isAttend = vo.getIsAttend();
        String model = vo.getModel();
        Double value = Double.valueOf(testValue);
        //评分模型：1：升   2:降
        if ("1".equals(model)) {
            return transformerFormulaCalInstance.clacFormulaAsc(aValue, bValue, value, weight, isAttend);
        } else if ("2".equals(model)) {
            return transformerFormulaCalInstance.clacFormulaDesc(aValue, bValue, value, weight, isAttend);
        }
        return 0d;
    }


    /**
     * @Title: calcDefectWeight
     * @Description: 计算缺陷权重
     * @createDate: Sep 11, 2019 10:45:51 AM
     * @param    mainEquipmentId
     * @param    map
     * @return Double
     */
    public Map<String, Object> calcDefectWeight(String mainEquipmentId, Map<String, BusiParamTransformerVo> map, JSONArray jsonArray, int step) {
        // 缺陷风险
        // 分接开关
        BusiParamTransformerVo byq_fjkg = this.getEvaluateObject(EvaluateConstant.BYQ_FJKG, map);
        // 套管
        BusiParamTransformerVo byq_tg = this.getEvaluateObject(EvaluateConstant.BYQ_TG, map);
        // 非电量保护装置
        BusiParamTransformerVo byq_fdlbhzz = this.getEvaluateObject(EvaluateConstant.BYQ_FDLBHZZ, map);
        // 冷却系统
        BusiParamTransformerVo byq_lqxt = this.getEvaluateObject(EvaluateConstant.BYQ_LQXT, map);
        // 变压器本体
        BusiParamTransformerVo byq_bt = this.getEvaluateObject(EvaluateConstant.BYQ_BT, map);

        List<EpaEvaluatRepairDataVo> repairlist = this.getTotalRepair(mainEquipmentId);
        List<Double> list = new ArrayList<>();
        if (CollectionUtils.isEmpty(repairlist)) {
            this.calcNoRepairWeight(byq_fjkg, list);
            this.calcNoRepairWeight(byq_tg, list);
            this.calcNoRepairWeight(byq_fdlbhzz, list);
            this.calcNoRepairWeight(byq_lqxt, list);
            this.calcNoRepairWeight(byq_bt, list);
        } else {
            Map<String, Object> map1 = this.calcRepairWeight(byq_bt, repairlist, list, jsonArray, step);
            step = Integer.valueOf(map1.get("step").toString());

            Map<String, Object> map2 = this.calcRepairWeight(byq_lqxt, repairlist, list, jsonArray, step);
            step = Integer.valueOf(map2.get("step").toString());

            Map<String, Object> map3 = this.calcRepairWeight(byq_fjkg, repairlist, list, jsonArray, step);
            step = Integer.valueOf(map3.get("step").toString());

            Map<String, Object> map4 = this.calcRepairWeight(byq_fdlbhzz, repairlist, list, jsonArray, step);
            step = Integer.valueOf(map4.get("step").toString());

            Map<String, Object> map5 = this.calcRepairWeight(byq_tg, repairlist, list, jsonArray, step);
            step = Integer.valueOf(map5.get("step").toString());
        }

        Map<String, Object> map1 = Maps.newConcurrentMap();
        map1.put("step", step);
        if (!list.isEmpty()) {
            Collections.sort(list);
            Double tmp = list.get(0);
            log.info("--->> 缺陷风险健康指数[{}]", tmp);
            map1.put("tmp", tmp);
            return map1;
        }
        map1.put("tmp", 1d);
        return map1;
    }


    /**
     * @Title: calcRepairWeight
     * @Description: 计算有维修时的权重
     * @createDate: Sep 11, 2019 10:12:24 AM
     * @param    vo
     * @return void
     */
    private Map<String, Object> calcRepairWeight(BusiParamTransformerVo vo, List<EpaEvaluatRepairDataVo> repairlist, List<Double> list, JSONArray jsonArray, int step) {
        Double R2 = 1d;
        /** @Fields parts : 缺陷部件：1(本体) 2:冷却系统、3:分接开关、4:非电量保护装置、5:套管*/
        if (vo.getIsAttend().equals("1")) {
            Double R = vo.getValue().doubleValue();
            Double P = this.calcR(R);
            String type = "";
            List<EpaEvaluatRepairDataVo> partsRepairlist = null;
            if (EvaluateConstant.BYQ_BT.equals(vo.getName())) {
                type = "本体";
                partsRepairlist = this.getDefectPartsRepair("1", repairlist);
            } else if (EvaluateConstant.BYQ_LQXT.equals(vo.getName())) {
                type = "冷却系统";
                partsRepairlist = this.getDefectPartsRepair("2", repairlist);
            } else if (EvaluateConstant.BYQ_FJKG.equals(vo.getName())) {
                type = "分接开关";
                partsRepairlist = this.getDefectPartsRepair("3", repairlist);
            } else if (EvaluateConstant.BYQ_FDLBHZZ.equals(vo.getName())) {
                type = "非电量保护装置";
                partsRepairlist = this.getDefectPartsRepair("4", repairlist);
            } else if (EvaluateConstant.BYQ_TG.equals(vo.getName())) {
                type = "套管";
                partsRepairlist = this.getDefectPartsRepair("5", repairlist);
            }

            Double RA = this.CalcRA(P, partsRepairlist);
            step += 1;
            setStep(jsonArray, step, type + "风险得分计算", "", String.valueOf(RA));
            Double R1 = transformerFormulaCalInstance.defectRiskCorrection(RA);
            step += 1;
            setStep(jsonArray, step, type + "缺陷风险得分计算", String.valueOf(RA), String.valueOf(R1));
            Double X = R * R1 * R2;
            step += 1;
            setStep(jsonArray, step, type + "风险健康指数计算", "", String.valueOf(X));

            if (EvaluateConstant.BYQ_BT.equals(vo.getName())) {
                log.info("--->>本体缺陷风险健康指数[{}]", X);
            } else if (EvaluateConstant.BYQ_LQXT.equals(vo.getName())) {
                log.info("--->>冷却系统缺陷风险健康指数[{}]", X);
            } else if (EvaluateConstant.BYQ_FJKG.equals(vo.getName())) {
                log.info("--->>分接开关缺陷风险健康指数[{}]", X);
            } else if (EvaluateConstant.BYQ_FDLBHZZ.equals(vo.getName())) {
                log.info("--->>非电量保护装置风险健康指数[{}]", X);
            } else if (EvaluateConstant.BYQ_TG.equals(vo.getName())) {
                log.info("--->>套管风险健康指数[{}]", X);
            }
            list.add(X);
        }

        Map<String, Object> map = Maps.newConcurrentMap();
        map.put("step", step);
        return map;
    }

    /**
     * @Title: calcNoRepairWeight
     * @Description: 计算为维修权重
     * @createDate: Sep 11, 2019 10:11:54 AM
     * @param    vo
     * @return void
     */
    public void calcNoRepairWeight(BusiParamTransformerVo vo, List<Double> list) {
        if (vo.getIsAttend().equals("1")) {
            double X = vo.getValue().doubleValue();
            if (EvaluateConstant.BYQ_BT.equals(vo.getName())) {
                log.info("--->> 本体缺陷风险健康指数[{}]", X);
            } else if (EvaluateConstant.BYQ_LQXT.equals(vo.getName())) {
                log.info("--->> 冷却系统缺陷风险健康指数[{}]", X);
            } else if (EvaluateConstant.BYQ_FJKG.equals(vo.getName())) {
                log.info("--->> 分接开关缺陷风险健康指数[{}]", X);
            } else if (EvaluateConstant.BYQ_FDLBHZZ.equals(vo.getName())) {
                log.info("--->> 非电量保护装置风险健康指数[{}]", X);
            } else if (EvaluateConstant.BYQ_TG.equals(vo.getName())) {
                log.info("--->> 套管风险健康指数[{}]", X);
            }
            list.add(X);
        }
    }


    /**
     * @Title: getTotalRepair
     * @Description: 获取维修数据
     * @createDate: Sep 6, 2019 5:57:12 PM
     * @param    mainEquipmentId
     * @return List<EpaEvaluatRepairDataVo>
     */
    public List<EpaEvaluatRepairDataVo> getTotalRepair(String mainEquipmentId) {
        Date end = new Date();
        Date begin = DateUtil.getIntervalDate(end, 8);
        return busiOfflineTransformerRepairMapper.getEvaluatRepairData(mainEquipmentId, begin, end);
    }

    /**
     * @Title: getDefectPartsRepair
     * @Description: 获取每个部件的维修
     * @createDate: Sep 6, 2019 6:00:59 PM
     * @param
     * @return List<EpaEvaluatRepairDataVo>
     */
    public List<EpaEvaluatRepairDataVo> getDefectPartsRepair(String type, List<EpaEvaluatRepairDataVo> list) {
        return list.stream().filter(vo -> vo.getParts().equalsIgnoreCase(type)).collect(Collectors.toList());
    }


    /**
     * @Title: calcR
     * @Description: 计算可靠性指标
     * @createDate: Sep 6, 2019 4:37:00 PM
     * @param    value  失效概率
     * @return Double
     */
    public Double calcR(Double value) {
        double R = new BigDecimal("1").subtract(new BigDecimal(value)).doubleValue();
        return R;
    }

    /**
     * @Title: CalcRA
     * @Description: 计算风险得分
     * @createDate: Sep 6, 2019 5:56:28 PM
     * @param
     * @return Double
     * @throws
     */
    public Double CalcRA(double value, List<EpaEvaluatRepairDataVo> list) {
        if (CollectionUtils.isEmpty(list)) {
            return 0d;
        }
        Integer t1 = 0;
        Integer t2 = 0;
        Integer t3 = 0;
        for (EpaEvaluatRepairDataVo vo : list) {
            if ("1".equals(vo.getType())) {
                t1 += 1;
            } else if ("2".equals(vo.getType())) {
                t2 += 1;
            } else if ("3".equals(vo.getType())) {
                t3 += 1;
            }
        }
        Integer total = t1 * 1 + t2 * 3 + t3 * 5;
        double RA = Double.valueOf(total) * value;
        return RA;
    }

    /**
     * @Title: calcK2
     * @Description: 计算过负荷/过热修正系数
     * @createDate: Sep 11, 2019 4:14:52 PM
     * @param    mainEquipmentId  主设备id
     * @return Double
     */
    public Map<String, Object> calcK2(String mainEquipmentId, JSONArray jsonArray, int step) {
        double value = this.calcOverheatedTime(mainEquipmentId);
        step += 1;
        setStep(jsonArray, step, "变压器过负荷/过热时间计算", "", String.valueOf(value));
        log.info("--->> 变压器过负荷/过热时间：[{}小时] ", value);

        double L = transformerFormulaCalInstance.calcL(value);
        step += 1;
        setStep(jsonArray, step, "计算监测时间内寿命损失率", String.valueOf(value), String.valueOf(L));

        double tmp = 1d - L;
        step += 1;
        setStep(jsonArray, step, "", "", String.valueOf(tmp));

        double K2 = 1d / tmp;
        K2 = new BigDecimal(K2).setScale(10, RoundingMode.HALF_UP).doubleValue();
        step += 1;
        setStep(jsonArray, step, "", "", String.valueOf(K2));

        Map<String, Object> map = Maps.newConcurrentMap();
        map.put("step", step);
        map.put("K2", K2);
        return map;
    }

    /**
     * @Title: calcOverheatedTime
     * @Description: 计算过持续时间 (小时)
     * @createDate: Sep 11, 2019 4:47:52 PM
     * @param    mainEquipmentId  设备ID
     * @return Double
     */
    public Double calcOverheatedTime(String mainEquipmentId) {
        Double value = 0d;
        Date start = DateUtil.getStartDate();
        Date end = DateUtil.getEndDate();
        List<BusiTransfromTemperatureExcess> list = busiTransfromTemperatureExcessService.getEvalatuData(mainEquipmentId, start, end);
        if (CollectionUtil.isNotEmpty(list)) {
            Long total = 0L;
            for (BusiTransfromTemperatureExcess entity : list) {
                LocalDateTime beginTime = entity.getBeginTime();
                LocalDateTime endTime = entity.getEndTime();
                if (null != beginTime && null != endTime) {
                    Duration duration = Duration.between(beginTime, endTime);
                    total = total + duration.getSeconds();
                }
            }
            double diff = total.doubleValue() / (1000d * 60d * 60d);
            value = new BigDecimal(diff).setScale(5, RoundingMode.HALF_UP).doubleValue();
        }
        return value;
    }

    /**
     * @Title: calcNaturalAgingRate
     * @Description: 计算自然老化率
     * @createDate: Sep 11, 2019 2:58:40 PM
     * @param    vo
     * @return double
     */
    public double calcNaturalAgingRate(EpaEvaluateDataVo vo) {
        String co = vo.getCo();
        String co2 = vo.getCo2();
        Double tmp1 = Double.valueOf(co2) * 0.65;
        Double tmp2 = Double.valueOf(co);
        Double double1 = tmp1 / tmp2;
        return new BigDecimal(double1).setScale(4, RoundingMode.HALF_UP).doubleValue();
    }

    /**
     * @Title: ShortCircuitCorrectionValue
     * @Description: 计算短路修正值.
     * @createDate: Sep 11, 2019 2:24:09 PM
     * @param    mainTreeId 站点树ID
     * @return Double
     */
    public Double ShortCircuitCorrectionValue(String mainTreeId) {
        Double K1 = 1d;
        Date startTime = DateUtil.getStartDate();
        Date endTime = DateUtil.getEndDate();
        List<IecBreakerParamEvaluateVo> list = iecBreakerParamMapper.getEvaluateData(mainTreeId, startTime, endTime);
        if (!CollectionUtils.isEmpty(list)) {
            K1 = this.calcK1ByShortCircuit(list);
        }
        return K1;
    }

    /**
     *
     * 	百分比		次数		修正值
     * 	90%~100%	1		0.9     	短路冲击电流90%以上，按次扣分  eg: 1次 90%  2次 90%*90%
     * 	70%~90%		2		0.95 		短路冲击电流70%~90%，按次扣分  eg: 1次 0.95  2次 0.95%*0.95%
     * 	50%~70%		6		0.98		短路冲击电流50%~70%累积6次以上，0.98
     *
     */
    /**
     * @Title: calcK1ByShortCircuit
     * @Description: 计算短路修正值
     * @createDate: Sep 11, 2019 2:22:29 PM
     * @param    list
     * @return Double
     */
    public Double calcK1ByShortCircuit(List<IecBreakerParamEvaluateVo> list) {
        Double k1 = 1d;
        Integer L1 = 0;
        Integer L2 = 0;
        Integer L3 = 0;
        for (IecBreakerParamEvaluateVo vo : list) {
            String faildRate = vo.getFaildRate();
            if (StringUtil.isNotEmpty(faildRate)) {
                Double tmp = Double.valueOf(faildRate) * 100d;
                if (tmp >= 50d && tmp < 70d) {
                    L3 = L3 + 1;
                } else if (tmp >= 70d && tmp < 90d) {
                    L2 = L2 + 1;
                } else if (tmp >= 90d && tmp < 100d) {
                    L1 = L1 + 1;
                }
            }
        }
        if (L3 > 6) {
            k1 = k1 * 0.98;
        }
        if (L2 > 0) {
            double pow = Math.pow(0.95, L2.doubleValue());
            k1 = k1 * pow;
        }
        if (L1 > 0) {
            double pow = Math.pow(0.90, L1.doubleValue());
            k1 = k1 * pow;
        }
        return new BigDecimal(k1).setScale(4, RoundingMode.HALF_UP).doubleValue();
    }

	/*

	 *
	 * 	评分	      [85,100]	 [60,85)	 [40,60)	[20,40)	  [0,20)
		状态描述	 	优秀			良好			一般			差		极差
		检修策略	    正常运行	 延期检修	计划检修		尽快检修		立即检修

	 *
	 * */


    public void tansfrerMsg(TransformerEvaluationResults result, double value, JSONArray jsonArray, int step) {
        double tmp = value * 100;
        if (tmp > 100) {
            result.setHealthIndex("优秀");
            result.setAdvice("正常运行");
        } else if (tmp >= 85 && tmp <= 100) {
            result.setHealthIndex("优秀");
            result.setAdvice("正常运行");
        } else if (tmp >= 60 && tmp < 85) {
            result.setHealthIndex("良好");
            result.setAdvice("延期检修");
        } else if (tmp >= 40 && tmp < 60) {
            result.setHealthIndex("一般");
            result.setAdvice("计划检修");
        } else if (tmp >= 20 && tmp < 40) {
            result.setHealthIndex("差");
            result.setAdvice("尽快检修");
        } else if (tmp >= 0 && tmp < 20) {
            result.setHealthIndex("极差");
            result.setAdvice("立即检修");
        } else {
            result.setHealthIndex("极差");
            result.setAdvice("立即检修");
        }

        com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
        jsonObject.put("healthIndex", result.getHealthIndex());
        jsonObject.put("advice", result.getAdvice());
        step += 1;
        setStep(jsonArray, step, "变压器评分计算", String.valueOf(tmp), jsonObject.toJSONString());
    }

    public static void main(String[] args) throws IOException {
        // 创建document对象
        Document document = DocumentHelper.createDocument();
        //创建根节点evaluate
        Element evaluate = document.addElement("evaluate");
        // 节点添加属性
        evaluate.addAttribute("name", "result");
        evaluate.addAttribute("value", "true");
        evaluate.addAttribute("desc", "评测成功");

        Element transformer = evaluate.addElement("transformer");
        transformer.setText("#1变压器");
        Element evaluatetime = evaluate.addElement("evaluatetime");
        evaluatetime.setText("2012-08-10");

        Element healthy = evaluate.addElement("healthy");
        healthy.addAttribute("name", "finalIndex");
        healthy.addAttribute("value", "0.709");
        healthy.addAttribute("desc", "最终健康水平指数");

        //component_defect_risk_health_index  部件缺陷风险健康指数
        //insulation_operation_health_index  绝缘运行状态健康指数
        //aging_health_status_of_main_insulation   主绝缘老化健康状态

        Element atrrIndex1 = healthy.addElement("atrr");
        atrrIndex1.addAttribute("name", "mainInsulationIndex");
        atrrIndex1.addAttribute("value", "0.8898");
        atrrIndex1.addAttribute("desc", "主绝缘老化健康状态");

        Element atrrIndex2 = healthy.addElement("atrr");
        atrrIndex2.addAttribute("name", "runInsulationIndex");
        atrrIndex2.addAttribute("value", "0.7303");
        atrrIndex2.addAttribute("desc", "绝缘运行状态健康指数");

        createAttr(atrrIndex2, "oilChromatogramTest", "0.5887", "油色谱试验");
        createAttr(atrrIndex2, "furfural", "0.8577", "糠醛");
        createAttr(atrrIndex2, "oilQualityTest", "0.9686", "油质试验");
        createAttr(atrrIndex2, "insulatingPaperTest", "0.715", "绝缘纸试验");
        createAttr(atrrIndex2, "routineTest", "0.6755", "例行试验");
        createAttr(atrrIndex2, "diagnosticTest", "0.6527", "诊断性试验");


        Element atrrIndex3 = healthy.addElement("atrr");
        atrrIndex3.addAttribute("name", "componentDefectIndex");
        atrrIndex3.addAttribute("value", "0.4848");
        atrrIndex3.addAttribute("desc", "部件缺陷风险健康指数");

        Element result = evaluate.addElement("result");
        createAttr(result, "designLife", "30", "设计寿命(年)");
        createAttr(result, "expectLife", "20", "变压器预期寿命(年)");
        createAttr(result, "score", "85", "健康评分");
        createAttr(result, "agingRate", "32%", "变压器老化程度");
        createAttr(result, "advice", "计划检修", "检修策略");
        createAttr(result, "healthIndex", "一般", "变压器健康评估状态");
        createAttr(result, "futureFailureRate", "23.78%", "今后故障发生概率(%)");

        // 设置生成xml的格式
        OutputFormat format = OutputFormat.createPrettyPrint();
        // 设置编码格式
        format.setEncoding("UTF-8");
        // 生成xml文件
        File file = new File("d:/xmlTest.xml");
        XMLWriter writer = new XMLWriter(new FileOutputStream(file), format);
        // 设置是否转义，默认使用转义字符
        writer.setEscapeText(false);
        writer.write(document);
        writer.close();
    }

    public static void createAttr(Element parenet, String name, String value, String desc) {
        Element result = parenet.addElement("attr");
        result.addAttribute("name", name);
        result.addAttribute("value", value);
        result.addAttribute("desc", desc);
    }

    /**
     * 计算步骤
     * @param jsonArray
     * @param stepId 步骤编号->第几步
     * @param stepName 每个步骤名称
     * @param inputParam 入参
     * @param calculateResult 计算结果
     */
    private void setStep(JSONArray jsonArray, int stepId, String stepName, String inputParam, String calculateResult) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("stepId", stepId);
        jsonObject.put("stepName", stepName);
        jsonObject.put("inputParam", inputParam);
        jsonObject.put("calculateResult", calculateResult);
        jsonArray.add(jsonObject);
    }

    private String calculateModel(String v, BusiParamTransformerVo tmp) {
        com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
        jsonObject.put("aValue", tmp.getAValue().doubleValue());
        jsonObject.put("bValue", tmp.getBValue().doubleValue());
        jsonObject.put("weight", tmp.getValue().doubleValue());
        jsonObject.put("isAttend", tmp.getIsAttend());
        jsonObject.put("model", tmp.getModel());
        jsonObject.put("value", v);
        return jsonObject.toJSONString();
    }

    private String calcWeight(double weight, double temp) {
        com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
        jsonObject.put("weight", weight);
        jsonObject.put("tmp", temp);
        return jsonObject.toJSONString();
    }
}
