package com.huatek.busi.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import com.google.common.collect.Maps;
import com.huatek.busi.common.SiteConstants;
import com.huatek.busi.common.TransformerAssessEnum;
import com.huatek.busi.common.util.DateUtil;
import com.huatek.busi.dao.*;
import com.huatek.busi.dto.BusiDrivepipeEvaluationResultsDto;
import com.huatek.busi.entity.*;
import com.huatek.busi.mapper.*;
import com.huatek.busi.service.*;
import com.huatek.busi.service.impl.transformerCalUtils.AgingHealthIndexUtil;
import com.huatek.busi.service.param.BusiParamTransformerService;
import com.huatek.busi.service.transformer.BusiOfflineTransformerBrandService;
import com.huatek.busi.service.transformer.SoundVibrationParamsService;
import com.huatek.busi.service.transformer.TransformerEvaluationIntermediateValueService;
import com.huatek.busi.service.transformer.TransformerEvaluationResultsService;
import com.huatek.busi.task.transformer.TransformerEvaluationTask;
import com.huatek.busi.task.transformer.TransfromerCreateUtil;
import com.huatek.busi.util.*;
import com.huatek.busi.vo.*;
import com.huatek.busi.vo.epa.EpaEvaluatRepairDataVo;
import com.huatek.busi.vo.epa.EpaEvaluateDataVo;
import com.huatek.busi.vo.epa.IecBreakerParamEvaluateVo;
import com.huatek.frame.base.util.Constants;
import com.huatek.torch.frame.exception.OwlException;
import com.huatek.torch.frame.tools.ConstantUtil;
import com.huatek.torch.frame.tools.ResultUtil;
import com.huatek.torch.sql.beans.WherePrams;
import com.huatek.torch.util.uuid.Uuid;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
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;

@Slf4j
@Component
@Service(interfaceClass = ITransformerEvaluationService.class)
@Transactional(rollbackFor = Exception.class)
public class TransformerEvaluationServiceImpl implements ITransformerEvaluationService {

    @Reference(check = false)
    BusiOfflineTransformerBrandService busiOfflineTransformerBrandService;

    @Reference(check = false)
    ITransformerEvaluateDataService iTransformerEvaluateDataService;

    @Reference(check = false)
    ILabReportMarkStatisticService labReportMarkStatisticService;

    @Reference(check = false)
    TransformerEvaluationIntermediateValueService transformerEvaluationIntermediateValueService;

    @Reference(check = false)
    BusiParamTransformerService busiParamTransformerService;

    @Reference(check = false)
    BusiTransformerLoadService busiTransformerLoadService;

    @Reference(check = false)
    BusiTransfromTemperatureExcessService busiTransfromTemperatureExcessService;

    @Reference(check = false)
    TransformerEvaluationResultsService transformerEvaluationResultsService;

    @Reference(check = false)
    BusiSiteTreeService busiSiteTreeService;

    @Reference(check = false)
    ICalculateStepService calculateStepService;

    @Autowired
    private BusiDrivepipeEvaluationResultsDao busiDrivepipeEvaluationResultsDao;

    @Autowired
    private BusiTransformerExperimentDao busiTransformerExperimentDao;

    @Reference(check = false)
    ITransformerEpaOfflineDataService transformerEpaOfflineDataService;

    @Resource
    private BusiOfflineTransformerRepairMapper busiOfflineTransformerRepairMapper;

    @Resource
    private LabReportMarkStatisticMapper labReportMarkStatisticMapper;

    @Resource
    private IecBreakerParamMapper iecBreakerParamMapper;

    @Resource
    private BusiOfflineTransformerBrandMapper busiOfflineTransformerBrandMapper;

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

    @Autowired
    private AppendixAssessService appendixAssessService;


    @Autowired
    private BusiParamAppendixMapper busiParamAppendixMapper;

    @Autowired
    private TransformerInfraredMonitoringStatisticsDao transformerInfraredMonitoringStatisticsDao;

    @Autowired
    private CapacitanceEquipmentImDao capacitanceEquipmentImDao;

    @Autowired
    private TransformerRunStatusStatisticsDao transformerRunStatusStatisticsDao;

    @Autowired
    protected TransformerRunStatusMapper transformerRunStatusMapper;

    @Autowired
    private SubstationMicStatisticsDao substationMicStatisticsDao;

    @Autowired
    private SoundVibrationParamsService soundVibrationParamsService;


    @Autowired
    private TransformerEvaluationTask transformerEvaluationTask;

    public static TransformerFormulaCal transformerFormulaCalInstance = TransformerFormulaCal.getInstance();

    public static TransformerFormulaSingleton instance = TransformerFormulaSingleton.getInstance();

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

    @Override
    public Map<String, Object> transformerEvaluation(String token, String siteId, String mainTreeId) {
        // 查询变压器标牌信息
        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));

            BusiOfflineTransformerBrandVo brand = busiOfflineTransformerBrandService.getBusiOfflineTransformerBrandVo(siteId, mainTreeId);
            if (ObjectUtil.isEmpty(brand)) {
                throw new OwlException("变压器标牌信息为空");
            }
            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 (ObjectUtil.isEmpty(evaluateData)) {
                log.error("--->> 变压器:[{}],未导入试验报告", name);
                throw new OwlException("变压器:" + name + ",未导入试验报告");
            }

            List<BusiParamTransformerVo> params = this.getTransformerParams(siteId, mainTreeId);
            if (CollectionUtils.isEmpty(params)) {
                log.error("--->> 变压器:[{}],未设置分析参数", name);
                throw new OwlException("变压器:" + name + ",未设置分析参数");
            }
            String number = params.get(0).getNumber().toString();

            EpaEvaluateDataVo epaEvaluateData = this.getEpaEvaluateData(mainTreeId);
            if (ObjectUtil.isEmpty(epaEvaluateData)) {
                log.error("--->> 变压器:[{}],未导入油色谱数据", name);
                throw new OwlException("变压器:" + name + ",未导入油色谱数据");
            }

            // 变压器的权重系数维护表
            Map<String, BusiParamTransformerVo> fristLevelMap = this.convertParams("1", params);
            Map<String, BusiParamTransformerVo> secondLevelMap = this.convertParams("2", params);
            Map<String, BusiParamTransformerVo> threeLevelMap = this.convertParams("3", params);
            if (fristLevelMap.size() == 0 || secondLevelMap.size() == 0 || threeLevelMap.size() == 0) {
                log.error("--->> 变压器:[{}],变压器评估参数为空", name);
                throw new OwlException("变压器:" + name + ",变压器评估参数为空");
            }

//            double load = getTransformerLoad(siteId, id);
            double load = AgingHealthIndexUtil.getTransformerLoad(brand, evaluateData);
            log.info("--->  变压器:{}, 变压器负荷率：{}", name, load);

            BusiParamTransformerVo weight1Vo = this.getEvaluateObject(EvaluateConstant.INDIVIDUAL_INSULATION, fristLevelMap);
            BusiParamTransformerVo weight2Vo = this.getEvaluateObject(EvaluateConstant.HEREDITY_RISK, fristLevelMap);
            BusiParamTransformerVo weight3Vo = this.getEvaluateObject(EvaluateConstant.DESIGN_BRAND, fristLevelMap);
            Double weight1 = this.getEvaluateWeight(EvaluateConstant.INDIVIDUAL_INSULATION, fristLevelMap);
            Double weight2 = this.getEvaluateWeight(EvaluateConstant.HEREDITY_RISK, fristLevelMap);
            Double weight3 = this.getEvaluateWeight(EvaluateConstant.DESIGN_BRAND, fristLevelMap);

            CalculateStep calculateStep = new CalculateStep();
            calculateStep.setId(Uuid.getUUID());
            calculateStep.setSiteId(brand.getSiteId());
            calculateStep.setEquipmentType(SiteConstants.BYQ);
            calculateStep.setMainEquipmentId(brand.getMainEquipmentId());
            calculateStep.setNumber(number);
            calculateStep.setExecuteMode(Integer.valueOf(Constants.DEFAULT_NO));
            calculateStep.setCreateTime(LocalDateTime.now());

            int step = 0;

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

            // 套管未来故障概率
//            Map<String, Object> drivepipeResult = this.drivepipeEvaluation(mainEquipmentId, evaluateData, threeLevelMap);

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

            Double individualInsulation = individualInsulationMap.get("TOTAL_INDEX");
            String a = individualInsulation.toString();
            BigDecimal individualInsulation1 = new BigDecimal(a).setScale(4, RoundingMode.HALF_UP);

            step = Double.valueOf(individualInsulationMap.get("step").toString()).intValue();
//                    Map<String, Object> map1 = this.calcDefectWeight(mainTreeId, secondLevelMap, jsonArray, step);
            // 附件计算结果
            Map<String, Double> map1 = this.calcAttachmentWeight(evaluateData, secondLevelMap, threeLevelMap, step);
            Double defectWeight = map1.get("tmp");
            String b = defectWeight.toString();
            BigDecimal defectWeight1 = new BigDecimal(b).setScale(4, RoundingMode.HALF_UP);
            step = map1.get("step").intValue();

            double val = agingHealthIndex * weight3;
            Double tmp1 = new BigDecimal(val).setScale(4, RoundingMode.HALF_UP).doubleValue();
            log.info("--->> 计算绝缘老化状态健康指数： 老化系数[{}], 权重[{}], 健康指数[{}]", agingHealthIndex, weight3, tmp1);
            step += 1;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("环境等级", brand.getEnvironmentLevel());
            jsonObject.put("设备投运时间", brand.getEquipmentDeliveryTime());
            jsonObject.put("变压器设计、标牌、运行环境、负荷权重", weight3.toString());
            EvaluationNameUtil.setSpecialStep(step, weight3Vo, String.valueOf(tmp1), jsonObject, null);

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

            EvaluationNameUtil.setStep(step, weight1Vo, String.valueOf(tmp2), individualInsulation1.setScale(4, RoundingMode.HALF_UP).toString());

            double val3 = defectWeight * weight2;
            Double tmp3 = new BigDecimal(val3).setScale(4, RoundingMode.HALF_UP).doubleValue();
            log.info("--->> 计算变压器附件健康指数： 指数[{}], 权重[{}], 健康指数[{}]", defectWeight, weight2, tmp3);
            step += 1;
            EvaluationNameUtil.setStep(step, weight2Vo, String.valueOf(tmp3), defectWeight1.setScale(4, RoundingMode.HALF_UP).toString());

            //-糠醛指标
            Map<String, Object> map3 = this.calcFurIndexWeight(evaluateData, fristLevelMap, secondLevelMap, step);
            Double kqzbWeight = Double.valueOf(map3.get("kqzb").toString());
            step = Integer.parseInt(map3.get("step").toString());
//                step += 1;
//                EvaluationNameUtil.setStep(step, weight4Vo, kqzbWeight.toString(), map3.get("tmp").toString());
            log.info("--->> 变压器糠醛指标：[{}] ", kqzbWeight);

            //绝缘纸实验
            Map<String, Object> map4 = this.calcInsulationPaperWeight(evaluateData, fristLevelMap, secondLevelMap, step);
            Double juzsyWeight = Double.valueOf(map4.get("jyz").toString());
            step = Integer.parseInt(map4.get("step").toString());
//                step += 1;
//                EvaluationNameUtil.setStep(step, weight5Vo, juzsyWeight.toString(), map4.get("tmp").toString());
            log.info("--->> 变压器绝缘纸实验：[{}] ", juzsyWeight);

            double val4 = tmp3 + tmp2 + tmp1 + kqzbWeight + juzsyWeight;
            Double healthyIndex = new BigDecimal(val4).setScale(4, RoundingMode.HALF_UP).doubleValue();
            log.info("--->> 变压器状态最终健康指数：[{}] ", healthyIndex);
            step += 1;
            JSONObject jsonObject2 = new JSONObject();
            jsonObject2.put("变压器设计、标牌、运行环境、负荷最终结果", tmp1.toString());
            jsonObject2.put("变压器绝缘试验最终结果", tmp2.toString());
            jsonObject2.put("变压器糠醛指标最终结果", kqzbWeight.toString());
            jsonObject2.put("变压器绝缘纸最终结果", juzsyWeight.toString());
            jsonObject2.put("变压器附件最终结果", tmp3.toString());
            EvaluationNameUtil.setSpecialStep(step, null, String.valueOf(healthyIndex), jsonObject2, "变压器状态最终健康指数计算");

            Double K1 = this.ShortCircuitCorrectionValue(mainTreeId);
            log.info("--->> 进出口区短路修正指数：[{}] ", K1);

            double val5 = K1 * healthyIndex;
            Double correctionThealthyIndex = new BigDecimal(val5).setScale(4, RoundingMode.HALF_UP)
                    .doubleValue();
            log.info("--->> 变压器状态修正后最终健康指数：[{}] ", correctionThealthyIndex);

            double futureFailureRate = transformerFormulaCalInstance.clacFutureFailureRate(correctionThealthyIndex);
            log.info("--->> 变压器未来故障率：[{}] ", futureFailureRate);

            // CO2/CO = 老化率
            //绕组测温老化率算法
            double naturalAgingRate = this.calcNaturalAgingRate(epaEvaluateData);
            log.info("--->> 变压器自然老化率：[{}] ", naturalAgingRate);

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

            Double B = K2 * B0;
            JSONObject jsonObject3 = new JSONObject();
            step += 1;
            jsonObject3.put("初始老化系数", B0.toString());
            jsonObject3.put("变压器过负荷/过热修正系数", K2.toString());
            jsonObject3.put("修正后老化系数", B.toString());
            BusiParamTransformerVo vo = new BusiParamTransformerVo();
            vo.setWeightLevel("1");
            vo.setName("elderIndex");
            vo.setDescription("老化系数计算");
            EvaluationNameUtil.setSpecialStep(step, vo, String.valueOf(B), jsonObject3, null);

            log.info("--->> 变压器最终老化系数：[{}] ", B);

            double surplus = transformerFormulaCalInstance.calcSurplus(correctionThealthyIndex, B);
            log.info("--->> 变压器剩余寿命：[{}] ", surplus);

            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.parseDouble(designLife));
            result.setType("1");
            this.tansfrerMsg(result, correctionThealthyIndex, step);
            TransformerEvaluationDescUtil.evaluatDesc(result);
            transformerEvaluationResultsService.save(result);

            /*******************************评估中间变量******************************************/
            intermediateValue.setOilChromatogramTest(individualInsulationMap.get("YSP_INDEX").toString());
            intermediateValue.setFurfural(kqzbWeight.toString());
            intermediateValue.setOilQualityTest(individualInsulationMap.get("YZSY_INDEX").toString());
            intermediateValue.setInsulatingPaper(juzsyWeight.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);

            // 新增算法步骤
            TransformerEvaluationResultsVo newResult = transformerEvaluationResultsService.findLatestResult(mainTreeId);
            log.info("--->> result表id：[{}] ", newResult.getId());
            String pid = newResult.getId();
            calculateStep.setStepJson(EvaluationNameUtil.listToJson());
            calculateStep.setPId(pid);
            Runnable runnable = () -> {
                calculateStepService.insert(calculateStep);
                EvaluationNameUtil.cleanList();
            };
            new Thread(runnable).start();

            ////临时注释，调测后放开
            TransfromerCreateUtil.createFile(intermediateValue, true, basePath, filePath, fileName, date);
//                } catch (Exception e) {
//                    log.error("-->> 评测异常[{}]", e.getMessage());
//                    return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "BUSINESS.QUERY.FAIL", null);
//                }   08-18
        }
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "BUSINESS.QUERY.SUCCESS", null);
    }

    private Map<String, Double> calcAttachmentWeight(TransformerEvaluateDataVo vo, Map<String, BusiParamTransformerVo> secondLevelMap, Map<String, BusiParamTransformerVo> threeLevelMap, int step) {
        Map<String, Double> map = new HashMap<>();
        log.info("-----------变压器附件-开始计算-----------");
        //变压器器身
        Map<String, Object> map1 = this.calcBodyTestWeight(vo, secondLevelMap, threeLevelMap, step);
        Double bodyWeight = Double.valueOf(map1.get("byqzs").toString());
        step = Integer.parseInt(map1.get("step").toString());

        //变压器冷却系统
        Map<String, Object> map2 = this.calcCoolingWeight(vo, secondLevelMap, threeLevelMap, step);
        Double coolingWeight = Double.valueOf(map2.get("byqlqxt").toString());
        step = Integer.parseInt(map2.get("step").toString());

        //分接开关
        Map<String, Object> map3 = this.calcSwitchWeight(vo, secondLevelMap, threeLevelMap, step);
        Double switchWeight = Double.valueOf(map3.get("byqfjkg").toString());
        step = Integer.parseInt(map3.get("step").toString());

        //非电量保护装置
        Map<String, Object> map4 = this.calcNonElectricityWeight(vo, secondLevelMap, threeLevelMap, step);
        Double nonElectricityWeight = Double.valueOf(map4.get("byqfdlbh").toString());
        step = Integer.parseInt(map4.get("step").toString());

        //变压器高压套管
        Map<String, Object> map5 = this.calcHighTensionWeight(vo, secondLevelMap, threeLevelMap, step);
        Double highTensionWeight = Double.valueOf(map5.get("byqgytg").toString());
        step = Integer.parseInt(map5.get("step").toString());


        double total = bodyWeight + coolingWeight + switchWeight + nonElectricityWeight + highTensionWeight;
        BigDecimal total1 = new BigDecimal(total).setScale(4, RoundingMode.HALF_UP);
        log.info("-- >>  变压器附件计算结果: [{}]", total1);
        map.put("tmp", Double.valueOf(total1.toString()));
        map.put("step", (double) step);
        return map;
    }

    private Map<String, Object> calcHighTensionWeight(TransformerEvaluateDataVo vo, Map<String, BusiParamTransformerVo> secondLevelMap, Map<String, BusiParamTransformerVo> threeLevelMap, int step) {
        double byqgytg = 0d;
        log.info("-----------变压器附件-变压器高压套管开始计算-----------");
        BusiParamTransformerVo tg = this.getEvaluateObject(EvaluateConstant.BYQ_TG, secondLevelMap);
        if (null != tg && "1".equals(tg.getIsAttend())) {
            Map<String, Object> map = this.calcHighTensionTest(vo, threeLevelMap, step);
            Double tmp = Double.valueOf(map.get("tg").toString());
            step = Integer.parseInt(map.get("step").toString());
            byqgytg = this.calcWeight(tmp, tg);
            BigDecimal body = new BigDecimal(byqgytg).setScale(4, RoundingMode.HALF_UP);
            step += 1;
            EvaluationNameUtil.setStep(step, tg, String.valueOf(body), tmp.toString());
        }
        log.info("-- >>  变压器附件-变压器高压套管权重计算结果: [{}]", byqgytg);

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

    private Map<String, Object> calcHighTensionTest(TransformerEvaluateDataVo vo, Map<String, BusiParamTransformerVo> threeLevelMap, int step) {
        List<BusiParamTransformerVo> list = new ArrayList<>();
        //末屏绝缘电阻
        BusiParamTransformerVo tmp1 = this.getEvaluateObject(EvaluateConstant.BYQ_TG_MPJYDZ, threeLevelMap);
        tmp1.setTestValue(vo.getEndScreenInsulationResistance());
        list.add(tmp1);
        //全电流
        BusiParamTransformerVo tmp2 = this.getEvaluateObject(EvaluateConstant.BYQ_TG_QDL, threeLevelMap);
        tmp2.setTestValue(vo.getTotalCurrent());
        list.add(tmp2);
        //容性电流
        BusiParamTransformerVo tmp3 = this.getEvaluateObject(EvaluateConstant.BYQ_TG_RXDL, threeLevelMap);
        tmp3.setTestValue(vo.getCapacitiveCurrent());
        list.add(tmp3);
        //阻性电流
        BusiParamTransformerVo tmp4 = this.getEvaluateObject(EvaluateConstant.BYQ_TG_ZXDL, threeLevelMap);
        tmp4.setTestValue(vo.getResistiveCurrent());
        list.add(tmp4);
        //红外温度
        BusiParamTransformerVo tmp5 = this.getEvaluateObject(EvaluateConstant.BYQ_TG_HWWD, threeLevelMap);
        tmp5.setTestValue(vo.getInfraredTemperature());
        list.add(tmp5);
        //末屏介损
        BusiParamTransformerVo tmp6 = this.getEvaluateObject(EvaluateConstant.BYQ_TG_MPJS, threeLevelMap);
        tmp6.setTestValue(vo.getEndScreenDielectricDamage());
        list.add(tmp6);
        //末屏绝缘电容
        BusiParamTransformerVo tmp7 = this.getEvaluateObject(EvaluateConstant.BYQ_TG_MPJYDR, threeLevelMap);
        tmp7.setTestValue(vo.getFinalScreenInsulationCapacitance());
        list.add(tmp7);
        //套管介损
        BusiParamTransformerVo tmp8 = this.getEvaluateObject(EvaluateConstant.BYQ_TG_TGJS, threeLevelMap);
        tmp8.setTestValue(vo.getCasingDielectricLoss());
        list.add(tmp8);
        //套管H2
        BusiParamTransformerVo tmp9 = this.getEvaluateObject(EvaluateConstant.BYQ_TG_TGH2, threeLevelMap);
        tmp9.setTestValue(vo.getCasingH2());
        list.add(tmp9);
        //套管CH4
        BusiParamTransformerVo tmp10 = this.getEvaluateObject(EvaluateConstant.BYQ_TG_TGCH4, threeLevelMap);
        tmp10.setTestValue(vo.getCasingCh4());
        list.add(tmp10);
        //套管C2H2
        BusiParamTransformerVo tmp11 = this.getEvaluateObject(EvaluateConstant.BYQ_TG_TGC2H2, threeLevelMap);
        tmp11.setTestValue(vo.getCasingC2h2());
        list.add(tmp11);
        //电容量
        BusiParamTransformerVo tmp12 = this.getEvaluateObject(EvaluateConstant.BYQ_TG_DRL, threeLevelMap);
        tmp12.setTestValue(vo.getCapacitance());
        list.add(tmp12);

        double tg = 0d;
        for (BusiParamTransformerVo tmp : list) {
            if ("1".equals(tmp.getIsAttend()) && null == tmp.getTestValue()) {
                throw new OwlException("缺少变压器-变压器高压套管-" + tmp.getDescription() + "-相关参数");
            }
            if ("1".equals(tmp.getIsAttend())) {
                Double calcWeight = this.calcWeight(tmp.getTestValue(), tmp);
                log.info("-- >> 变压器绝缘试验-变压器高压套管-- {} 计算结果: [{}]", tmp.getDescription(), calcWeight);
                step += 1;
                tg += calcWeight;
                EvaluationNameUtil.setStep(step, tmp, String.valueOf(calcWeight), tmp.getTestValue());
            }
        }
        log.info("-- >> 变压器附件-变压器高压套管-分项和计算结果: [{}]", tg);
        Map<String, Object> map1 = Maps.newConcurrentMap();
        map1.put("tg", tg);
        map1.put("step", step);
        return map1;
    }

    private Map<String, Object> calcNonElectricityWeight(TransformerEvaluateDataVo vo, Map<String, BusiParamTransformerVo> secondLevelMap, Map<String, BusiParamTransformerVo> threeLevelMap, int step) {
        double nonElectricity = 0d;
        log.info("-----------变压器附件-变压器非电量保护装置开始计算-----------");
        BusiParamTransformerVo fdl = this.getEvaluateObject(EvaluateConstant.BYQ_FDLBHZZ, secondLevelMap);
        if (null != fdl && "1".equals(fdl.getIsAttend())) {
            Map<String, Object> map = this.calcnonElectricityTest(vo, threeLevelMap, step);
            Double tmp = Double.valueOf(map.get("nonElectricity").toString());
            step = Integer.parseInt(map.get("step").toString());
            nonElectricity = this.calcWeight(tmp, fdl);
            BigDecimal body = new BigDecimal(nonElectricity).setScale(4, BigDecimal.ROUND_HALF_UP);
            step += 1;
            EvaluationNameUtil.setStep(step, fdl, String.valueOf(body), tmp.toString());
        }
        log.info("-- >>  变压器附件-非电量保护装置权重计算结果: [{}]", nonElectricity);

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

    private Map<String, Object> calcnonElectricityTest(TransformerEvaluateDataVo vo, Map<String, BusiParamTransformerVo> threeLevelMap, int step) {
        List<BusiParamTransformerVo> list = new ArrayList<>();
        //继电器动作
        BusiParamTransformerVo tmp1 = this.getEvaluateObject(EvaluateConstant.BYQ_FDLBHZZ_JDQDZ, threeLevelMap);
        tmp1.setTestValue(vo.getRelayAction());
        list.add(tmp1);
        //压力释放阀动作
        BusiParamTransformerVo tmp2 = this.getEvaluateObject(EvaluateConstant.BYQ_FDLBHZZ_YLSFDZ, threeLevelMap);
        tmp2.setTestValue(vo.getReliefValveAction());
        list.add(tmp2);

        double nonElectricity = 0d;
        for (BusiParamTransformerVo tmp : list) {
            if ("1".equals(tmp.getIsAttend()) && null == tmp.getTestValue()) {
                throw new OwlException("缺少变压器-非电量保护装置-" + tmp.getDescription() + "-相关参数");
            }
            if ("1".equals(tmp.getIsAttend())) {
                Double calcWeight = this.calcWeight(tmp.getTestValue(), tmp);
                log.info("-- >> 变压器-非电量保护装置-- {} 计算结果: [{}]", tmp.getDescription(), calcWeight);
                step += 1;
                nonElectricity += calcWeight;
                EvaluationNameUtil.setStep(step, tmp, String.valueOf(calcWeight), tmp.getTestValue());
            }
        }
        log.info("-- >> 变压器附件-非电量保护装置-分项和计算结果: [{}]", nonElectricity);
        Map<String, Object> map1 = Maps.newConcurrentMap();
        map1.put("nonElectricity", nonElectricity);
        map1.put("step", step);
        return map1;
    }


    private Map<String, Object> calcSwitchWeight(TransformerEvaluateDataVo vo, Map<String, BusiParamTransformerVo> secondLevelMap, Map<String, BusiParamTransformerVo> threeLevelMap, int step) {
        double byqfjkg = 0d;
        log.info("-----------变压器附件-变压器分接开关开始计算-----------");
        BusiParamTransformerVo fjkg = this.getEvaluateObject(EvaluateConstant.BYQ_FJKG, secondLevelMap);
        if (null != fjkg && "1".equals(fjkg.getIsAttend())) {
            Map<String, Object> map = this.calcSwitchTest(vo, threeLevelMap, step);
            Double tmp = Double.valueOf(map.get("fjkg").toString());
            step = Integer.parseInt(map.get("step").toString());
            byqfjkg = this.calcWeight(tmp, fjkg);
            BigDecimal body = new BigDecimal(byqfjkg).setScale(4, RoundingMode.HALF_UP);
            step += 1;
            EvaluationNameUtil.setStep(step, fjkg, String.valueOf(body), tmp.toString());
        }
        log.info("-- >>  变压器附件-分接开关权重计算结果: [{}]", byqfjkg);

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

    private Map<String, Object> calcSwitchTest(TransformerEvaluateDataVo vo, Map<String, BusiParamTransformerVo> threeLevelMap, int step) {
        List<BusiParamTransformerVo> list = new ArrayList<>();
        // 油击穿电压变化率
        BusiParamTransformerVo tmp1 = this.getEvaluateObject(EvaluateConstant.BYQ_FJKG_YJCDYBHL, threeLevelMap);
        tmp1.setTestValue(vo.getOilPuncture());
        list.add(tmp1);
        //传动机构有无问题
        BusiParamTransformerVo tmp2 = this.getEvaluateObject(EvaluateConstant.BYQ_FJKG_CDJGYWWT, threeLevelMap);
        tmp2.setTestValue(vo.getTransmissionGear());
        list.add(tmp2);

        double fjkg = 0d;
        for (BusiParamTransformerVo tmp : list) {
            if ("1".equals(tmp.getIsAttend()) && null == tmp.getTestValue()) {
                throw new OwlException("缺少变压器-分接开关-" + tmp.getDescription() + "-相关参数");
            }
            if ("1".equals(tmp.getIsAttend())) {
                Double calcWeight = this.calcWeight(tmp.getTestValue(), tmp);
                log.info("-- >> 变压器-分接开关-- {} 计算结果: [{}]", tmp.getDescription(), calcWeight);
                step += 1;
                fjkg += calcWeight;
                EvaluationNameUtil.setStep(step, tmp, String.valueOf(calcWeight), tmp.getTestValue());
            }
        }
        log.info("-- >> 变压器附件-分接开关-分项和计算结果: [{}]", fjkg);
        Map<String, Object> map1 = Maps.newConcurrentMap();
        map1.put("fjkg", fjkg);
        map1.put("step", step);
        return map1;
    }


    private Map<String, Object> calcCoolingWeight(TransformerEvaluateDataVo vo, Map<String, BusiParamTransformerVo> secondLevelMap, Map<String, BusiParamTransformerVo> threeLevelMap, int step) {
        double byqlqxt = 0d;
        log.info("-----------变压器附件-变压器冷却系统开始计算-----------");
        BusiParamTransformerVo lqxt = this.getEvaluateObject(EvaluateConstant.BYQ_LQXT, secondLevelMap);
        if (null != lqxt && "1".equals(lqxt.getIsAttend())) {
            Map<String, Object> map = this.calcLqxtTest(vo, threeLevelMap, step);
            Double tmp = Double.valueOf(map.get("lqxt").toString());
            step = Integer.parseInt(map.get("step").toString());
            byqlqxt = this.calcWeight(tmp, lqxt);
            BigDecimal body = new BigDecimal(byqlqxt).setScale(4, RoundingMode.HALF_UP);
            step += 1;
            EvaluationNameUtil.setStep(step, lqxt, String.valueOf(body), tmp.toString());
        }
        log.info("-- >>  变压器附件-变压器冷却系统权重计算结果: [{}]", byqlqxt);

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

    private Map<String, Object> calcLqxtTest(TransformerEvaluateDataVo vo, Map<String, BusiParamTransformerVo> threeLevelMap, int step) {
        List<BusiParamTransformerVo> list = new ArrayList<>();
        //水温
        BusiParamTransformerVo tmp1 = this.getEvaluateObject(EvaluateConstant.BYQ_LQXT_SW, threeLevelMap);
        tmp1.setTestValue(vo.getWaterTemperature());
        list.add(tmp1);
        //水压
        BusiParamTransformerVo tmp2 = this.getEvaluateObject(EvaluateConstant.BYQ_LQXT_SY, threeLevelMap);
        tmp2.setTestValue(vo.getWaterPressure());
        list.add(tmp2);
        //环境温度
        BusiParamTransformerVo tmp3 = this.getEvaluateObject(EvaluateConstant.BYQ_LQXT_HJWD, threeLevelMap);
        tmp3.setTestValue(vo.getEnvironmentTemperature());
        list.add(tmp3);
        //风机损坏检修次数
        BusiParamTransformerVo tmp4 = this.getEvaluateObject(EvaluateConstant.BYQ_LQXT_FJSHJXCS, threeLevelMap);
        tmp4.setTestValue(vo.getMaintenanceCount());
        list.add(tmp4);

        double lqxt = 0d;
        for (BusiParamTransformerVo tmp : list) {
            if ("1".equals(tmp.getIsAttend()) && null == tmp.getTestValue()) {
                throw new OwlException("缺少变压器-变压器冷却系统-" + tmp.getDescription() + "-相关参数");
            }
            if ("1".equals(tmp.getIsAttend())) {
                Double calcWeight = this.calcWeight(tmp.getTestValue(), tmp);
                log.info("-- >> 变压器-变压器冷却系统-- {} 计算结果: [{}]", tmp.getDescription(), calcWeight);
                step += 1;
                lqxt += calcWeight;
                EvaluationNameUtil.setStep(step, tmp, String.valueOf(calcWeight), tmp.getTestValue());
            }
        }
        log.info("-- >> 变压器附件-变压器冷却系统-分项和计算结果: [{}]", lqxt);
        Map<String, Object> map1 = Maps.newConcurrentMap();
        map1.put("lqxt", lqxt);
        map1.put("step", step);
        return map1;
    }


    private Map<String, Object> calcBodyTestWeight(TransformerEvaluateDataVo vo, Map<String, BusiParamTransformerVo> secondLevelMap, Map<String, BusiParamTransformerVo> threeLevelMap, int step) {
        double byqzs = 0d;
        log.info("-----------变压器附件-变压器器身开始计算-----------");
        BusiParamTransformerVo bt = this.getEvaluateObject(EvaluateConstant.BYQ_BT, secondLevelMap);
        if (null != bt && "1".equals(bt.getIsAttend())) {
            Map<String, Object> map = this.calcBodyTest(vo, threeLevelMap, step);
            Double tmp = Double.valueOf(map.get("body").toString());
            step = Integer.parseInt(map.get("step").toString());
            byqzs = this.calcWeight(tmp, bt);
            step += 1;
            BigDecimal body = new BigDecimal(byqzs).setScale(4, RoundingMode.HALF_UP);
            EvaluationNameUtil.setStep(step, bt, String.valueOf(body), tmp.toString());
        }
        log.info("-- >>  变压器附件-变压器器身权重计算结果: [{}]", byqzs);

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

    private Map<String, Object> calcBodyTest(TransformerEvaluateDataVo evaluateDataVo, Map<String, BusiParamTransformerVo> threeLevelMap, int step) {
        List<BusiParamTransformerVo> list = new ArrayList<>();
        // 油位下降
        BusiParamTransformerVo tmp1 = this.getEvaluateObject(EvaluateConstant.BYQ_BT_YWXJ, threeLevelMap);
        tmp1.setTestValue(evaluateDataVo.getOilLevelDrop());
        list.add(tmp1);
        // 漏油次数
        BusiParamTransformerVo tmp2 = this.getEvaluateObject(EvaluateConstant.BYQ_BT_LYCS, threeLevelMap);
        tmp2.setTestValue(evaluateDataVo.getOilLeaksCount());
        list.add(tmp2);
        // 变压器噪声
        BusiParamTransformerVo tmp3 = this.getEvaluateObject(EvaluateConstant.BYQ_BT_BYQZS, threeLevelMap);
        tmp3.setTestValue(evaluateDataVo.getTransformerNoise());
        list.add(tmp3);

        double body = 0d;
        for (BusiParamTransformerVo tmp : list) {
            if ("1".equals(tmp.getIsAttend()) && null == tmp.getTestValue()) {
                throw new OwlException("缺少变压器器身-变压器器身-" + tmp.getDescription() + "-相关参数");
            }
            if ("1".equals(tmp.getIsAttend())) {
                Double calcWeight = this.calcWeight(tmp.getTestValue(), tmp);
                log.info("-- >> 变压器器身-- {} 计算结果: [{}]", tmp.getDescription(), calcWeight);
                step += 1;
                body += calcWeight;
                EvaluationNameUtil.setStep(step, tmp, String.valueOf(calcWeight), tmp.getTestValue());
            }
        }
        log.info("-- >> 变压器附件-变压器器身-分项和计算结果: [{}]", body);
        Map<String, Object> map1 = Maps.newConcurrentMap();
        map1.put("body", body);
        map1.put("step", step);
        return map1;
    }


    /*
	 *
	 * 	评分	      [85,100]	 [60,85)	 [40,60)	[20,40)	  [0,20)
		状态描述	 	优秀			良好			一般			差		极差
		检修策略	    正常运行	 延期检修	计划检修		尽快检修		立即检修
	 *
	 * */
    public void tansfrerMsg(TransformerEvaluationResults result, double value, 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("立即检修");
        }
    }

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

        double L = transformerFormulaCalInstance.calcL(value);

        double tmp = 1d - L;

        double K2 = 1d / tmp;
        K2 = new BigDecimal(K2).setScale(10, RoundingMode.HALF_UP).doubleValue();

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

    /**
     * @param mainEquipmentId 设备ID
     * @return Double
     * @Title: calcOverheatedTime
     * @Description: 计算过持续时间 (小时)
     * @createDate: Sep 11, 2019 4:47:52 PM
     */
    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;
    }

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

    /**
     * @param mainTreeId 站点树ID
     * @return Double
     * @Title: ShortCircuitCorrectionValue
     * @Description: 计算短路修正值.
     * @createDate: Sep 11, 2019 2:24:09 PM
     */
    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
     *
     */
    /**
     * @param list
     * @return Double
     * @Title: calcK1ByShortCircuit
     * @Description: 计算短路修正值
     * @createDate: Sep 11, 2019 2:22:29 PM
     */
    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();
    }

    /**
     * @param mainTreeId
     * @param map
     * @return Double
     * @Title: calcDefectWeight
     * @Description: 计算缺陷权重
     * @createDate: Sep 11, 2019 10:45:51 AM
     */
    public Map<String, Object> calcDefectWeight(String mainTreeId, Map<String, BusiParamTransformerVo> map, 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 = labReportMarkStatisticMapper.countTimes(mainTreeId);

        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, step);
            step = Integer.parseInt(map1.get("step").toString());

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

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

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

            Map<String, Object> map5 = this.calcRepairWeight(byq_tg, repairlist, list, step);
            step = Integer.parseInt(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;
    }

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

            Double RA = this.CalcRA(P, partsRepairlist);
            Double R1 = transformerFormulaCalInstance.defectRiskCorrection(RA);
            Double X = R * R1 * R2;
            BigDecimal X1 = new BigDecimal(X).setScale(4, RoundingMode.HALF_UP);
            JSONObject jsonObject = new JSONObject();
            for (EpaEvaluatRepairDataVo A : partsRepairlist) {
                jsonObject.put(type + "检修次数", A.getTotal());
                jsonObject.put(type + "缺陷等级", A.getType());
                jsonObject.put(type + "权重", R);
            }
            step += 1;
            EvaluationNameUtil.setSpecialStep(step, vo, X1.toString(), jsonObject, null);

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

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

    /**
     * @param
     * @return Double
     * @throws
     * @Title: CalcRA
     * @Description: 计算风险得分
     * @createDate: Sep 6, 2019 5:56:28 PM
     */
    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.0".equals(vo.getType())) {
                t1 += 1;
            } else if ("2.0".equals(vo.getType())) {
                t2 += 1;
            } else if ("3.0".equals(vo.getType())) {
                t3 += 1;
            }
        }
        Integer total = t1 * 1 + t2 * 3 + t3 * 5;
        return Double.valueOf(total) * value;
    }

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

    /**
     * @param vo
     * @return void
     * @Title: calcNoRepairWeight
     * @Description: 计算为维修权重
     * @createDate: Sep 11, 2019 10:11:54 AM
     */
    public void calcNoRepairWeight(BusiParamTransformerVo vo, List<Double> list) {
        if ("1".equals(vo.getIsAttend())) {
            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);
        }
    }

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

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

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

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

    /**
     * @param mainEquipmentId 主设备id
     * @return EpaEvaluateDataVo
     * @Title: getEpaEvaluateData
     * @Description: 获取油色谱评测数据
     * @createDate: Sep 6, 2019 2:37:34 PM
     */
    public EpaEvaluateDataVo getEpaEvaluateData(String mainEquipmentId) {
        EpaEvaluateDataVo vo = transformerEpaOfflineDataService.findByMainEquipmentId(mainEquipmentId);
        log.info("-- >> 油色谱评测数据:[{}]", vo);
        return vo;
    }

    /**
     * @param level 等级
     * @param list  参数
     * @return Map<String, BusiParamTransformerVo>
     * @Title: convertParams
     * @Description: 转换参数形式
     * @createDate: Sep 4, 2019 3:56:05 PM
     */
    public Map<String, BusiParamTransformerVo> convertParams(String level, List<BusiParamTransformerVo> list) {
        List<BusiParamTransformerVo> convertorlist;
        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;
    }

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

    /**
     * @param transformerId 变压器ID
     * @return Double
     * @Title: getTransformerLoad
     * @Description: 获取变压器负荷
     * @createDate: Aug 30, 2019 2:28:10 PM
     */
    private Double getTransformerLoad(String siteId, String transformerId) {
//        LocalDate localDate5 = LocalDate.parse("20200629", DateTimeFormatter.BASIC_ISO_DATE);
        LocalDate localDate5 = LocalDate.now().minusDays(1);
        //获取变压器负荷
        BusiTransformerLoad load = busiTransformerLoadService.getLoaByEquipmentIdAndDate(siteId, transformerId, localDate5);
        if (null != load) {
            return Double.parseDouble(load.getLoadRate()) * 100d;
        }
        return 30d;
    }

    /**
     * @return Double
     * @Title: calcIndividualInsulation
     * @Description: 变压器绝缘试验
     * @createDate: Sep 6, 2019 3:40:54 PM
     */
    public Map<String, Double> calcIndividualInsulation(TransformerEvaluateDataVo vo,
                                                        EpaEvaluateDataVo epaEvaluateData,
                                                        Map<String, BusiParamTransformerVo> secondLevelMap,
                                                        Map<String, BusiParamTransformerVo> threeLevelMap,
                                                        int step) {

        Map<String, Double> map = new HashMap<>();
        if (null != vo) {
            log.info("-----------变压器绝缘试验-开始计算-----------");
            //油色谱
            Map<String, Object> map1 = this.calcOilChromatographicTestWeight(epaEvaluateData, secondLevelMap, threeLevelMap, step);
            Double yspWeight = Double.valueOf(map1.get("ysp").toString());
            step = Integer.parseInt(map1.get("step").toString());

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

//            //-糠醛指标
//            Map<String, Object> map3 = this.calcFurIndexWeight(vo, secondLevelMap, threeLevelMap, step);
//            Double kqzbWeight = Double.valueOf(map3.get("kqzb").toString());
//            step = Integer.parseInt(map3.get("step").toString());
//
//            //绝缘纸实验
//            Map<String, Object> map4 = this.calcInsulationPaperWeight(vo, secondLevelMap, threeLevelMap, step);
//            Double juzsyWeight = Double.valueOf(map4.get("jyz").toString());
//            step = Integer.parseInt(map4.get("step").toString());

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

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

            //声级振动
            Map<String, Object> map7 = this.calcVibrationWeight(vo, secondLevelMap, threeLevelMap, step);
            Double sjzdWeight = Double.valueOf(map7.get("sjzd").toString());
            step = Integer.parseInt(map7.get("step").toString());
//            double total = yspWeight + yzsyWeight + sjzdWeight + kqzbWeight + juzsyWeight + zdssyWeight + lxsyWeight;
            double total = yspWeight + yzsyWeight + sjzdWeight + zdssyWeight + lxsyWeight;
            log.info("-- >>  变压器绝缘试验计算结果: [{}]", total);

            map.put("YSP_INDEX", yspWeight);
            map.put("YZSY_INDEX", yzsyWeight);
            map.put("SJZD_INDEX", sjzdWeight);
//            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) step);
        }
        return map;
    }

    /**
     * @param secondLevelMap 二级分析参数
     * @param threeLevelMap  三级分析参数
     * @return Double
     * @Title: calcOilChromatographicTestWeight
     * @Description: 变压器绝缘试验-油色谱  权重计算
     * @createDate: Sep 4, 2019 6:24:47 PM
     */
    private Map<String, Object> calcOilChromatographicTestWeight(EpaEvaluateDataVo epaEvaluateData, Map<String, BusiParamTransformerVo> secondLevelMap,
                                                                 Map<String, BusiParamTransformerVo> threeLevelMap, int step) {
        log.info("-----------变压器绝缘试验-油色谱开始计算-----------");
        double ysp = 0d;
        BusiParamTransformerVo YSP = this.getEvaluateObject(EvaluateConstant.YSP, secondLevelMap);
        if (null != YSP) {
            Map<String, Object> map = this.calcOilChromatographicTest(epaEvaluateData, threeLevelMap, step);
            Double tmp = Double.valueOf(map.get("ysp").toString());
            step = Integer.parseInt(map.get("step").toString());
            ysp = this.calcWeight(tmp, YSP);
            BigDecimal ysp1 = new BigDecimal(ysp).setScale(4, RoundingMode.HALF_UP);
            step += 1;
            EvaluationNameUtil.setStep(step, YSP, String.valueOf(ysp1), tmp.toString());
        }
        log.info("-- >>  变压器绝缘试验-油色谱权重计算结果: [{}]", ysp);

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

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

    /**
     * @param vo             报告导入数据
     * @param secondLevelMap 二级分析参数
     * @param threeLevelMap  三级分析参数
     * @return Double
     * @Title: calcVibrationWeight
     * @Description: 变压器绝缘试验-声级震动 权重计算
     * @createDate: Sep 4, 2019 6:24:47 PM
     */
    private Map<String, Object> calcVibrationWeight(TransformerEvaluateDataVo vo, Map<String, BusiParamTransformerVo> secondLevelMap,
                                                    Map<String, BusiParamTransformerVo> threeLevelMap, int step) {
        double sjzd = 0d;
        log.info("-----------变压器绝缘试验-声级震动开始计算-----------");
        BusiParamTransformerVo SJZD = this.getEvaluateObject(EvaluateConstant.BYQ_SJZD, secondLevelMap);
        if (null != SJZD && "1".equals(SJZD.getIsAttend())) {
            Map<String, Object> map = this.calcVibrationSoundLevel(vo, threeLevelMap, step);
            Double tmp = Double.parseDouble(map.get("sjzd").toString());
            step = Integer.parseInt(map.get("step").toString());

            sjzd = this.calcWeight(tmp, SJZD);
            BigDecimal sjzd1 = new BigDecimal(sjzd).setScale(4, RoundingMode.HALF_UP);
            step += 1;
            EvaluationNameUtil.setStep(step, SJZD, String.valueOf(sjzd1), Double.toString(tmp));
        }
        log.info("-- >> 变压器绝缘试验-声级震动权重计算结果: [{}]", sjzd);

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

    /**
     * @param vo  报告导入数据
     * @param map 分析参数
     * @return Double
     * @Title: calcVibrationSoundLevel
     * @Description: 变压器绝缘试验-声级振动计算
     * @createDate: Sep 4, 2019 6:02:20 PM
     */
    public Map<String, Object> calcVibrationSoundLevel(TransformerEvaluateDataVo vo, Map<String, BusiParamTransformerVo> map, int step) {
        List<BusiParamTransformerVo> list = new ArrayList<>();
        // 中性点电流
        BusiParamTransformerVo tmp1 = this.getEvaluateObject(EvaluateConstant.SJZD_ZXDDL, map);
        tmp1.setTestValue(vo.getNeutralPointCurrent());
        list.add(tmp1);
        // 噪声
        BusiParamTransformerVo tmp2 = this.getEvaluateObject(EvaluateConstant.SJZD_ZS, map);
        tmp2.setTestValue(vo.getNoise());
        list.add(tmp2);
        // 原边振动
        BusiParamTransformerVo tmp3 = this.getEvaluateObject(EvaluateConstant.SJZD_YBZD, map);
        tmp3.setTestValue(vo.getPrimaryVibration());
        list.add(tmp3);
        // 副边振动
        BusiParamTransformerVo tmp4 = this.getEvaluateObject(EvaluateConstant.SJZD_FBZD, map);
        tmp4.setTestValue(vo.getSecondaryVibration());
        list.add(tmp4);

        double sjzd = 0d;
        for (BusiParamTransformerVo tmp : list) {
            if ("1".equals(tmp.getIsAttend()) && null == tmp.getTestValue()) {
                throw new OwlException("缺少变压器绝缘试验-声级振动-" + tmp.getDescription() + "-相关参数");
            }
            if ("1".equals(tmp.getIsAttend())) {
                Double calcWeight = this.calcWeight(tmp.getTestValue(), tmp);
                log.info("-- >> 变压器绝缘试验-声级振动-- {} 计算结果: [{}]", tmp.getDescription(), calcWeight);
                step += 1;
                sjzd += calcWeight;
                EvaluationNameUtil.setStep(step, tmp, String.valueOf(calcWeight), tmp.getTestValue());
            }
        }
        log.info("-- >> 变压器绝缘试验-声级振动-分项和计算结果: [{}]", sjzd);
        Map<String, Object> map1 = Maps.newConcurrentMap();
        map1.put("sjzd", sjzd);
        map1.put("step", step);
        return map1;
    }

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

            yzsy = this.calcWeight(tmp, YZSY);
            BigDecimal yzsy1 = new BigDecimal(yzsy).setScale(4, BigDecimal.ROUND_HALF_UP);
            step += 1;
            EvaluationNameUtil.setStep(step, YZSY, String.valueOf(yzsy1), tmp.toString());
        }
        log.info("-- >> 变压器绝缘试验-油质试验权重计算结果: [{}]", yzsy);

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

    /**
     * @param vo  评测数据
     * @param map 分析参数
     * @return Double
     * @Title: calcOilQualityTest
     * @Description: 变压器绝缘试验-油质试验计算
     * @createDate: Sep 4, 2019 6:02:20 PM
     */
    public Map<String, Object> calcOilQualityTest(TransformerEvaluateDataVo vo, Map<String, BusiParamTransformerVo> map, int step) {
        List<BusiParamTransformerVo> list = new ArrayList<>();
        BusiParamTransformerVo tmp1 = this.getEvaluateObject(EvaluateConstant.YZSY_WS, map);
        tmp1.setTestValue(vo.getWaterInOil());
        list.add(tmp1);
        BusiParamTransformerVo tmp2 = this.getEvaluateObject(EvaluateConstant.YZSY_YJS, map);
        tmp2.setTestValue(vo.getOillMedium());
        list.add(tmp2);
        BusiParamTransformerVo tmp3 = this.getEvaluateObject(EvaluateConstant.YZSY_YJCDY, map);
        tmp3.setTestValue(vo.getOilBreakdownVoltage());
        list.add(tmp3);

        double yzsy = 0d;
        for (BusiParamTransformerVo tmp : list) {
            if ("1".equals(tmp.getIsAttend()) && null == tmp.getTestValue()) {
                throw new OwlException("缺少变压器绝缘试验-油质试验-" + tmp.getDescription() + "-相关参数");
            }
            if ("1".equals(tmp.getIsAttend())) {
                Double calcWeight = this.calcWeight(tmp.getTestValue(), tmp);
                log.info("-- >> 变压器绝缘试验-油质试验-- {} 计算结果: [{}]", tmp.getDescription(), calcWeight);
                step += 1;
                yzsy += calcWeight;
                EvaluationNameUtil.setStep(step, tmp, String.valueOf(calcWeight), tmp.getTestValue());
            }
        }
        log.info("-- >> 变压器绝缘试验-油质试验-分项和计算结果: [{}]", yzsy);
        Map<String, Object> map1 = Maps.newConcurrentMap();
        map1.put("yzsy", yzsy);
        map1.put("step", step);
        return map1;
    }

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

            kqzb = this.calcWeight(tmp, KQZB);
            BigDecimal kqzb1 = new BigDecimal(kqzb).setScale(4, RoundingMode.HALF_UP);
            step += 1;
            log.info("-- >>  变压器绝缘试验-糠醛指标输入值: [{}]", vo.getFurfural());
            EvaluationNameUtil.setStep(step, KQZB, String.valueOf(kqzb1), tmp.toString());
        }
        log.info("-- >>  变压器绝缘试验-糠醛指标权重计算结果: [{}]", kqzb);

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

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

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

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

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

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

            zdxsy = this.calcWeight(tmp, ZDXSY);
            BigDecimal zdxsy1 = new BigDecimal(zdxsy).setScale(4, BigDecimal.ROUND_HALF_UP);
            step += 1;
            EvaluationNameUtil.setStep(step, ZDXSY, String.valueOf(zdxsy1), Double.toString(tmp));
        }
        log.info("-- >>  变压器绝缘试验-诊断性试验权重计算结果: [{}]", zdxsy);

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

    /**
     * @param vo  评测数据
     * @param map 分析参数
     * @return Double
     * @Title: calcDiagnosticTest
     * @Description: 变压器绝缘试验-诊断性试验    各分项和
     * @createDate: Sep 5, 2019 10:27:22 AM
     */
    public Map<String, Object> calcDiagnosticTest(TransformerEvaluateDataVo vo, Map<String, BusiParamTransformerVo> map, int step) {
        List<BusiParamTransformerVo> list = new ArrayList<>();
        //绝缘纸含水量
        BusiParamTransformerVo tmp1 = this.getEvaluateObject(EvaluateConstant.ZDXSY_YJZHSL, map);
        tmp1.setTestValue(vo.getWaterContentOfInsulatingPaper());
        list.add(tmp1);
        //空载电流、空载损耗变化率（%）
        BusiParamTransformerVo tmp2 = this.getEvaluateObject(EvaluateConstant.ZDXSY_KZDL_KZSHL, map);
        tmp2.setTestValue(vo.getNoloadCurrentAndNoloadLossRate());
        list.add(tmp2);
        //短路阻抗变化率(%)
        BusiParamTransformerVo tmp3 = this.getEvaluateObject(EvaluateConstant.ZDXSY_DLZKBHL, map);
        tmp3.setTestValue(vo.getShortCircuitImpedanceChangeRate());
        list.add(tmp3);
        //铁芯接地电流
        BusiParamTransformerVo tmp4 = this.getEvaluateObject(EvaluateConstant.ZDXSY_TXJDDL, map);
        tmp4.setTestValue(vo.getCoreGroundCurrent());
        list.add(tmp4);
        //绕组直流泄漏电流（变化率%）
        BusiParamTransformerVo tmp5 = this.getEvaluateObject(EvaluateConstant.ZDXSY_RZZL_XLDL, map);
        tmp5.setTestValue(vo.getDcLeakageCurrentWinding());
        list.add(tmp5);

        double zdsy = 0d;
        for (BusiParamTransformerVo tmp : list) {
            if ("1".equals(tmp.getIsAttend()) && null == tmp.getTestValue()) {
                throw new OwlException("缺少变压器绝缘试验-诊断性试验-" + tmp.getDescription() + "-相关参数");
            }
            if ("1".equals(tmp.getIsAttend())) {
                Double calcWeight = this.calcWeight(tmp.getTestValue(), tmp);
                log.info("-- >> 变压器绝缘试验-诊断性试验-- {} 计算结果: [{}]", tmp.getDescription(), calcWeight);
                step += 1;
                zdsy += calcWeight;
                EvaluationNameUtil.setStep(step, tmp, String.valueOf(calcWeight), tmp.getTestValue());
            }
        }
        log.info("-- >> 变压器绝缘试验--诊断性试验-分项和计算结果: [{}]", zdsy);
        Map<String, Object> map1 = Maps.newConcurrentMap();
        map1.put("step", step);
        map1.put("zdsy", zdsy);
        return map1;
    }

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

            lxsy = this.calcWeight(tmp, LXSY);
            BigDecimal lxsy1 = new BigDecimal(lxsy).setScale(4, RoundingMode.HALF_UP);
            step += 1;
            EvaluationNameUtil.setStep(step, LXSY, String.valueOf(lxsy1), Double.toString(tmp));
        }
        log.info("-- >>  变压器绝缘试验-例行试验权重计算结果: [{}]", lxsy);

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

    /**
     * @param vo  评测数据
     * @param map 分析参数
     * @return Double
     * @Title: calcRoutineTest
     * @Description: 变压器绝缘试验-例行试验  各分项和
     * @createDate: Sep 5, 2019 11:15:07 AM
     */
    public Map<String, Object> calcRoutineTest(TransformerEvaluateDataVo vo, Map<String, BusiParamTransformerVo> map, int step) {
        List<BusiParamTransformerVo> list = new ArrayList<>();
        BusiParamTransformerVo tmp1 = this.getEvaluateObject(EvaluateConstant.LXSY_JHZS, map);
        tmp1.setTestValue(vo.getPolarizatioIndex());
        list.add(tmp1);
        //局放放电量
        BusiParamTransformerVo tmp2 = this.getEvaluateObject(EvaluateConstant.LXSY_JFFDL, map);
        tmp2.setTestValue(vo.getPartialDischarge());
        list.add(tmp2);
        //绝缘电阻(MΩ)
        BusiParamTransformerVo tmp3 = this.getEvaluateObject(EvaluateConstant.LXSY_JYDZ, map);
        tmp3.setTestValue(vo.getInsulationResistance());
        list.add(tmp3);
        //绝缘电阻吸收比
        BusiParamTransformerVo tmp4 = this.getEvaluateObject(EvaluateConstant.LXSY_JYDZ_SHB, map);
        tmp4.setTestValue(vo.getInsulationResistanceAbsorptionRatio());
        list.add(tmp4);
        //绕组直流电阻相间差(%)
        BusiParamTransformerVo tmp5 = this.getEvaluateObject(EvaluateConstant.LXSY_RZZL_DZXJC, map);
        tmp5.setTestValue(vo.getPhaseDifferenceDcResistance());
        list.add(tmp5);
        //绕组直流电阻线间差(%)
        BusiParamTransformerVo tmp6 = this.getEvaluateObject(EvaluateConstant.LXSY_RZZL_DZXJC2, map);
        tmp6.setTestValue(vo.getLineDifferenceDcResistance());
        list.add(tmp6);
        //绕组绝缘介损
        BusiParamTransformerVo tmp7 = this.getEvaluateObject(EvaluateConstant.LXSY_RZJYJS, map);
        tmp7.setTestValue(vo.getWindingInsulationDielectricLoss());
        list.add(tmp7);
        //铁芯接地电阻（MΩ）
        BusiParamTransformerVo tmp8 = this.getEvaluateObject(EvaluateConstant.LXSY_TXJDDZ, map);
        tmp8.setTestValue(vo.getCoreInsulationResistance());
        list.add(tmp8);

        double lxsy = 0d;
        for (BusiParamTransformerVo tmp : list) {
            if ("1".equals(tmp.getIsAttend()) && null == tmp.getTestValue()) {
                throw new OwlException("缺少变压器绝缘试验-例行试验-" + tmp.getDescription() + "-相关参数");
            }
            if ("1".equals(tmp.getIsAttend())) {
                Double calcWeight = this.calcWeight(tmp.getTestValue(), tmp);
                log.info("-- >> 变压器绝缘试验-例行试验-- {} 计算结果: [{}]", tmp.getDescription(), calcWeight);
                step += 1;
                lxsy += calcWeight;
                EvaluationNameUtil.setStep(step, tmp, String.valueOf(calcWeight), tmp.getTestValue());
            }
        }
        log.info("-- >> 变压器绝缘试验--例行试验-分项和计算结果: [{}]", lxsy);
        Map<String, Object> map1 = Maps.newConcurrentMap();
        map1.put("step", step);
        map1.put("lxsy", lxsy);
        return map1;
    }

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

    /**
     * @param vo  油色谱评测数据
     * @param map 分析参数
     * @return Double
     * @Title: calcoilChromatographicTest
     * @Description: 变压器绝缘试验-油色谱 分项和
     * @createDate: Sep 5, 2019 2:40:38 PM
     */
    public Map<String, Object> calcOilChromatographicTest(EpaEvaluateDataVo vo, Map<String, BusiParamTransformerVo> map, int step) {
        List<BusiParamTransformerVo> list = new ArrayList<>();
        BusiParamTransformerVo tmp1 = this.getEvaluateObject(EvaluateConstant.H2, map);
        tmp1.setTestValue(vo.getH2());
        list.add(tmp1);
        BusiParamTransformerVo tmp2 = this.getEvaluateObject(EvaluateConstant.CO, map);
        tmp2.setTestValue(vo.getCo());
        list.add(tmp2);
        BusiParamTransformerVo tmp3 = this.getEvaluateObject(EvaluateConstant.CO2, map);
        tmp3.setTestValue(vo.getCo2());
        list.add(tmp3);
        BusiParamTransformerVo tmp4 = this.getEvaluateObject(EvaluateConstant.CH4, map);
        tmp4.setTestValue(vo.getCh4());
        list.add(tmp4);
        BusiParamTransformerVo tmp5 = this.getEvaluateObject(EvaluateConstant.C2H2, map);
        tmp5.setTestValue(vo.getC2h2());
        list.add(tmp5);
        BusiParamTransformerVo tmp6 = this.getEvaluateObject(EvaluateConstant.C2H4, map);
        tmp6.setTestValue(vo.getC2h4());
        list.add(tmp6);
        BusiParamTransformerVo tmp7 = this.getEvaluateObject(EvaluateConstant.C2H6, map);
        tmp7.setTestValue(vo.getC2h6());
        list.add(tmp7);
        BusiParamTransformerVo tmp8 = this.getEvaluateObject(EvaluateConstant.ZT, map);
        tmp8.setTestValue(vo.getZt());
        list.add(tmp8);

        double ysp = 0d;
        for (BusiParamTransformerVo tmp : list) {
            if ("1".equals(tmp.getIsAttend()) && null == tmp.getTestValue()) {
                throw new OwlException("缺少变压器绝缘试验-油色谱-" + tmp.getDescription() + "-相关参数");
            }
            if ("1".equals(tmp.getIsAttend())) {
                Double calcWeight = this.calcWeight(tmp.getTestValue(), tmp);
                log.info("-- >> 变压器绝缘试验-油色谱-- {} 计算结果: [{}]", tmp.getDescription(), calcWeight);
                step += 1;
                ysp += calcWeight;
                EvaluationNameUtil.setStep(step, tmp, String.valueOf(calcWeight), tmp.getTestValue());
            }
        }
        log.info("-- >> 变压器绝缘试验-油色谱试验-分项和计算结果: [{}]", ysp);
        Map<String, Object> map1 = Maps.newConcurrentMap();
        map1.put("ysp", ysp);
        map1.put("step", step);
        return map1;
    }

    /**
     * @param testValue 测试值
     * @return Double
     * @Title: calcWeight
     * @Description: 计算权重
     * @createDate: Sep 4, 2019 5:53:23 PM
     */
    public Double calcWeight(String testValue, BusiParamTransformerVo vo) {
        if (StringUtils.isBlank(testValue)) {
//            return 0d ;
            return vo.getValue().doubleValue();
        }

        Double aValue = vo.getAValue() != null ? vo.getAValue().doubleValue() : 0d;
        Double bValue = vo.getBValue() != null ? vo.getBValue().doubleValue() : 0d;
        Double weight = vo.getValue() != null ? vo.getValue().doubleValue() : 0d;
        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;
    }

    /**
     * @param testValue 测试值
     * @return Double
     * @Title: calcWeight
     * @Description: 计算权重
     * @createDate: Sep 4, 2019 5:53:23 PM
     */
    public Double calcWeight2(String testValue, BusiParamTransformerVo vo) {
        if (StringUtils.isBlank(testValue)) {
//            return 0d ;
            return vo.getValue().doubleValue();
        }

        Double aValue = vo.getAValue() != null ? vo.getAValue().doubleValue() : 0d;
        Double bValue = vo.getBValue() != null ? vo.getBValue().doubleValue() : 0d;
        String isAttend = vo.getIsAttend();
        String model = vo.getModel();
        Double value = Double.valueOf(testValue);
        //评分模型：1：升   2:降
        if ("1".equals(model)) {
            return transformerFormulaCalInstance.clacFormulaAsc2(aValue, bValue, value, isAttend);
        } else if ("2".equals(model)) {
            return transformerFormulaCalInstance.clacFormulaDesc2(aValue, bValue, value, isAttend);
        }
        return 0d;
    }

    /**
     * 初始化数据
     */
    public void init(String mainTreeId) {
        // 初始化变压器评测计算数据
        iTransformerEvaluateDataService.delete(mainTreeId);
        // 初始化油色谱离线数据
        transformerEpaOfflineDataService.delete(mainTreeId);
    }

    /**
     * 根据打标规则获取相关数据
     *
     * @param key
     * @param mainTreeId
     */
    private Double getRules(String mainTreeId, String key) {
        labRulesVo rules = labReportMarkStatisticService.findRules(mainTreeId, key);
        if (null == rules) {
            return null;
        }
        Double result;
        if ("X".equals(rules.getTimeRule())) {
            if ("001".equals(rules.getECalcualteRule())) {
                result = labReportMarkStatisticService.findMaxValue(mainTreeId, key);
            } else if ("002".equals(rules.getECalcualteRule())) {
                result = labReportMarkStatisticService.findMinValue(mainTreeId, key);
            } else {
                result = labReportMarkStatisticService.findAverageValue(mainTreeId, key);
            }
        } else {
            if ("001".equals(rules.getECalcualteRule())) {
                result = labReportMarkStatisticService.findMaxValueByLTime(mainTreeId, key);
            } else if ("002".equals(rules.getECalcualteRule())) {
                result = labReportMarkStatisticService.findMinValueByLTime(mainTreeId, key);
            } else {
                result = labReportMarkStatisticService.findAverageValueByLTime(mainTreeId, key);
            }
        }
        return result;
    }

    @Override
    public void initAndSave(String token, String mainTreeId, String siteId) {
        init(mainTreeId);
        List<LabReportMarkStatistic> list = labReportMarkStatisticService.findMainTreeId(mainTreeId);
        // 新增变压器评测计算数据
        saveTransformerEvaluateData(token, list, mainTreeId);
        // 新增获取油色谱离线数据
        saveTransformerEpaOfflineData(token, list, mainTreeId);
        // 保存至例行试验表
        saveTransformerExperimentData(list, mainTreeId, siteId);
    }

    private void saveTransformerExperimentData(List<LabReportMarkStatistic> list, String mainTreeId, String siteId) {
        if (CollectionUtil.isNotEmpty(list)) {
            BusiTransformerExperiment experiment = new BusiTransformerExperiment();
            experiment.setSiteId(siteId);
            BusiOfflineTransformerBrandVo vo = busiOfflineTransformerBrandMapper.getBusiOfflineTransformerBrandVo(siteId, mainTreeId);
            BusiTransformerExperiment bte =  this.selectByMainTreeId(mainTreeId);
            if (!ObjectUtils.isEmpty(bte)){
                experiment.setId(bte.getId());
            }
            experiment.setEquipmentId(vo.getId());
            experiment.setMainTreeId(mainTreeId);
            Double h2 = this.getRules(mainTreeId, TransformerAssessEnum.H2.getKey());
            experiment.setH2(h2 != null ? String.valueOf(h2) : null);

            Double ch4 = this.getRules(mainTreeId, TransformerAssessEnum.CH4.getKey());
            experiment.setCh4(ch4 != null ? String.valueOf(ch4) : null);

            Double c2h2 = this.getRules(mainTreeId, TransformerAssessEnum.C2H2.getKey());
            experiment.setC2h2(c2h2 != null ? String.valueOf(c2h2) : null);

            Double c2h4 = this.getRules(mainTreeId, TransformerAssessEnum.C2H4.getKey());
            experiment.setC2h4(c2h4 != null ? String.valueOf(c2h4) : null);

            Double c2h6 = this.getRules(mainTreeId, TransformerAssessEnum.C2H6.getKey());
            experiment.setC2h6(c2h6 != null ? String.valueOf(c2h6) : null);

            Double co = this.getRules(mainTreeId, TransformerAssessEnum.CO.getKey());
            experiment.setCo(co != null ? String.valueOf(co) : null);

            Double co2 = this.getRules(mainTreeId, TransformerAssessEnum.CO2.getKey());
            experiment.setCo2(co2 != null ? String.valueOf(co2) : null);

            Double zj = this.getRules(mainTreeId, TransformerAssessEnum.ZJ.getKey());
            experiment.setZj(zj != null ? String.valueOf(zj) : null);

            Double o2 = this.getRules(mainTreeId, TransformerAssessEnum.O2.getKey());
            experiment.setCo2(o2 != null ? String.valueOf(o2) : null);

            Double n2 = this.getRules(mainTreeId, TransformerAssessEnum.N2.getKey());
            experiment.setZj(n2 != null ? String.valueOf(n2) : null);
            busiTransformerExperimentDao.saveOrUpdate(experiment);
        }
    }

    private BusiTransformerExperiment selectByMainTreeId(String mainTreeId) {
        BusiTransformerExperiment bte =busiTransformerExperimentDao.get(new WherePrams().where("main_tree_id",mainTreeId).limit(0,1));
        return bte;
    }

    /**
     * 新增变压器评测计算数据
     *
     * @param token
     * @param mainTreeId
     */
    private void saveTransformerEvaluateData(String token, List<LabReportMarkStatistic> list, String mainTreeId) {

        if (CollectionUtil.isNotEmpty(list)) {
            TransformerEvaluateDataVo transformerEvaluateDataVo = new TransformerEvaluateDataVo();
            transformerEvaluateDataVo.setMainTreeId(mainTreeId);

            /**变压器设计、标牌、运行环境、负荷权重**/
//            Double operatingEnvironment = this.getRules(mainTreeId, TransformerAssessEnum.ENVIRONMENTAL_GRADE.getKey());
//            transformerEvaluateDataVo.setOperatingEnvironment(operatingEnvironment != null ? String.valueOf(operatingEnvironment) : null);

            /**油色谱**/
            Double h2 = this.getRules(mainTreeId, TransformerAssessEnum.H2.getKey());
            transformerEvaluateDataVo.setH2(h2 != null ? String.valueOf(h2) : null);

            Double ch4 = this.getRules(mainTreeId, TransformerAssessEnum.CH4.getKey());
            transformerEvaluateDataVo.setCh4(ch4 != null ? String.valueOf(ch4) : null);

            Double c2h2 = this.getRules(mainTreeId, TransformerAssessEnum.C2H2.getKey());
            transformerEvaluateDataVo.setC2h2(c2h2 != null ? String.valueOf(c2h2) : null);

            Double c2h4 = this.getRules(mainTreeId, TransformerAssessEnum.C2H4.getKey());
            transformerEvaluateDataVo.setC2h4(c2h4 != null ? String.valueOf(c2h4) : null);

            Double c2h6 = this.getRules(mainTreeId, TransformerAssessEnum.C2H6.getKey());
            transformerEvaluateDataVo.setC2h6(c2h6 != null ? String.valueOf(c2h6) : null);

            Double co = this.getRules(mainTreeId, TransformerAssessEnum.CO.getKey());
            transformerEvaluateDataVo.setCo(co != null ? String.valueOf(co) : null);

            Double co2 = this.getRules(mainTreeId, TransformerAssessEnum.CO2.getKey());
            transformerEvaluateDataVo.setCo2(co2 != null ? String.valueOf(co2) : null);

            Double zj = this.getRules(mainTreeId, TransformerAssessEnum.ZJ.getKey());
            transformerEvaluateDataVo.setZj(zj != null ? String.valueOf(zj) : null);


            /**油色谱**/
            Double waterInOil = this.getRules(mainTreeId, TransformerAssessEnum.WATER_IN_OIL.getKey());
            transformerEvaluateDataVo.setWaterInOil(waterInOil != null ? String.valueOf(waterInOil) : null);

            Double oillMedium = this.getRules(mainTreeId, TransformerAssessEnum.OILL_MEDIUM.getKey());
            transformerEvaluateDataVo.setOillMedium(oillMedium != null ? String.valueOf(oillMedium) : null);

            Double oilBreakdownVoltage = this.getRules(mainTreeId, TransformerAssessEnum.OIL_BREAKDOWN_VOLTAGE.getKey());
            transformerEvaluateDataVo.setOilBreakdownVoltage(oilBreakdownVoltage != null ? String.valueOf(oilBreakdownVoltage) : null);

            /**糠醛指标**/
            Double furfural = this.getRules(mainTreeId, TransformerAssessEnum.FURFURAL.getKey());
            transformerEvaluateDataVo.setFurfural(furfural != null ? String.valueOf(furfural) : null);

            /**绝缘纸试验**/
            Double degreeCardboard = this.getRules(mainTreeId, TransformerAssessEnum.DEGREE_CARDBOARD.getKey());
            transformerEvaluateDataVo.setDegreeCardboard(degreeCardboard != null ? String.valueOf(degreeCardboard) : null);

            /**例行试验**/
            Double polarizatioIndex = this.getRules(mainTreeId, TransformerAssessEnum.POLARIZATIO_INDEX.getKey());
            transformerEvaluateDataVo.setPolarizatioIndex(polarizatioIndex != null ? String.valueOf(polarizatioIndex) : null);

            Double partialDischarge = this.getRules(mainTreeId, TransformerAssessEnum.PARTIAL_DISCHARGE.getKey());
            transformerEvaluateDataVo.setPartialDischarge(partialDischarge != null ? String.valueOf(partialDischarge) : null);

            Double insulationResistance = this.getRules(mainTreeId, TransformerAssessEnum.INSULATION_RESISTANCE.getKey());
            transformerEvaluateDataVo.setInsulationResistance(insulationResistance != null ? String.valueOf(insulationResistance) : null);

            Double insulationResistanceAbsorptionRatio = this.getRules(mainTreeId, TransformerAssessEnum.INSULATION_RESISTANCE_ABSORPTION_RATIO.getKey());
            transformerEvaluateDataVo.setInsulationResistanceAbsorptionRatio(insulationResistanceAbsorptionRatio != null ? String.valueOf(insulationResistanceAbsorptionRatio) : null);

            Double phaseDifferenceDcResistance = this.getRules(mainTreeId, TransformerAssessEnum.PHASE_DIFFERENCE_DC_RESISTANCE.getKey());
            transformerEvaluateDataVo.setPhaseDifferenceDcResistance(phaseDifferenceDcResistance != null ? String.valueOf(phaseDifferenceDcResistance) : null);

            Double lineDifferenceDcResistance = this.getRules(mainTreeId, TransformerAssessEnum.LINE_DIFFERENCE_DC_RESISTANCE.getKey());
            transformerEvaluateDataVo.setLineDifferenceDcResistance(lineDifferenceDcResistance != null ? String.valueOf(lineDifferenceDcResistance) : null);

            Double windingInsulationDielectricLoss = this.getRules(mainTreeId, TransformerAssessEnum.WINDING_INSULATION_DIELECTRIC_LOSS.getKey());
            transformerEvaluateDataVo.setWindingInsulationDielectricLoss(windingInsulationDielectricLoss != null ? String.valueOf(windingInsulationDielectricLoss) : null);

            Double coreInsulationResistance = this.getRules(mainTreeId, TransformerAssessEnum.CORE_INSULATION_RESISTANCE.getKey());
            transformerEvaluateDataVo.setCoreInsulationResistance(coreInsulationResistance != null ? String.valueOf(coreInsulationResistance) : null);

            /**例行试验**/
            Double waterContentOfInsulatingPaper = this.getRules(mainTreeId, TransformerAssessEnum.WATER_CONTENT_OF_INSULATING_PAPER.getKey());
            transformerEvaluateDataVo.setWaterContentOfInsulatingPaper(waterContentOfInsulatingPaper != null ? String.valueOf(waterContentOfInsulatingPaper) : null);

            Double noloadCurrentAndNoloadLossRate = this.getRules(mainTreeId, TransformerAssessEnum.NOLOAD_CURRENT_AND_NOLOAD_LOSS_RATE.getKey());
            transformerEvaluateDataVo.setNoloadCurrentAndNoloadLossRate(noloadCurrentAndNoloadLossRate != null ? String.valueOf(noloadCurrentAndNoloadLossRate) : null);

            Double shortCircuitImpedanceChangeRate = this.getRules(mainTreeId, TransformerAssessEnum.SHORT_CIRCUIT_IMPEDANCE_CHANGE_RATE.getKey());
            transformerEvaluateDataVo.setShortCircuitImpedanceChangeRate(shortCircuitImpedanceChangeRate != null ? String.valueOf(shortCircuitImpedanceChangeRate) : null);

            Double coreGroundCurrent = this.getRules(mainTreeId, TransformerAssessEnum.CORE_GROUND_CURRENT.getKey());
            transformerEvaluateDataVo.setCoreGroundCurrent(coreGroundCurrent != null ? String.valueOf(coreGroundCurrent) : null);

            Double dcLeakageCurrentWinding = this.getRules(mainTreeId, TransformerAssessEnum.DC_LEAKAGE_CURRENT_WINDING.getKey());
            transformerEvaluateDataVo.setDcLeakageCurrentWinding(dcLeakageCurrentWinding != null ? String.valueOf(dcLeakageCurrentWinding) : null);

            /**声级震动**/
            Double neutralPointCurrent = this.getRules(mainTreeId, TransformerAssessEnum.NEUTRAL_POINT_CURRENT.getKey());
            transformerEvaluateDataVo.setNeutralPointCurrent(neutralPointCurrent != null ? String.valueOf(neutralPointCurrent) : null);

            Double noise = this.getRules(mainTreeId, TransformerAssessEnum.NOISE.getKey());
            transformerEvaluateDataVo.setNoise(noise != null ? String.valueOf(noise) : null);

            Double primaryVibration = this.getRules(mainTreeId, TransformerAssessEnum.PRIMARY_VIBRATION.getKey());
            transformerEvaluateDataVo.setPrimaryVibration(primaryVibration != null ? String.valueOf(primaryVibration) : null);

            Double secondaryVibration = this.getRules(mainTreeId, TransformerAssessEnum.SECONDARY_VIBRATION.getKey());
            transformerEvaluateDataVo.setSecondaryVibration(secondaryVibration != null ? String.valueOf(secondaryVibration) : null);

            /**附件器身**/
            Double oilLevelDrop = this.getRules(mainTreeId, TransformerAssessEnum.OIL_LEVEL_DROP.getKey());
            transformerEvaluateDataVo.setOilLevelDrop(oilLevelDrop != null ? String.valueOf(oilLevelDrop) : null);

            Double number_of_oil_spills = this.getRules(mainTreeId, TransformerAssessEnum.NUMBER_OF_OIL_SPILLS.getKey());
            transformerEvaluateDataVo.setOilLeaksCount(number_of_oil_spills != null ? String.valueOf(number_of_oil_spills) : null);

            Double transformerNoise = this.getRules(mainTreeId, TransformerAssessEnum.TRANSFORMER_NOISE.getKey());
            transformerEvaluateDataVo.setTransformerNoise(transformerNoise != null ? String.valueOf(transformerNoise) : null);

            /**附件冷却系统**/
            Double waterTemperature = this.getRules(mainTreeId, TransformerAssessEnum.WATER_TEMPERATURE.getKey());
            transformerEvaluateDataVo.setWaterTemperature(waterTemperature != null ? String.valueOf(waterTemperature) : null);

            Double waterPressure = this.getRules(mainTreeId, TransformerAssessEnum.HYDRAULIC_PRESSURE.getKey());
            transformerEvaluateDataVo.setWaterPressure(waterPressure != null ? String.valueOf(waterPressure) : null);

            Double environmentTemperature = this.getRules(mainTreeId, TransformerAssessEnum.ENVIRONMENT_TEMPERATURE.getKey());
            transformerEvaluateDataVo.setEnvironmentTemperature(environmentTemperature != null ? String.valueOf(environmentTemperature) : null);

            Double maintenanceCount = this.getRules(mainTreeId, TransformerAssessEnum.FAN_DAMAGE_MAINTENANCE_TIMES.getKey());
            transformerEvaluateDataVo.setMaintenanceCount(maintenanceCount != null ? String.valueOf(maintenanceCount) : null);


            /**附件分接开关**/
            Double oilPuncture = this.getRules(mainTreeId, TransformerAssessEnum.RATE_OF_CHANGE_OF_OIL_BREAKDOWN_VOLTAGE.getKey());
            transformerEvaluateDataVo.setOilPuncture(oilPuncture != null ? String.valueOf(oilPuncture) : null);

            Double transimissionGear = this.getRules(mainTreeId, TransformerAssessEnum.TRANSMISSION_MECHANISM_PROBLEM.getKey());
            transformerEvaluateDataVo.setTransmissionGear(transimissionGear != null ? String.valueOf(transimissionGear) : null);

            /**非电量保护装置**/
            Double relayAction = this.getRules(mainTreeId, TransformerAssessEnum.ACTUATING_OF_RELAY.getKey());
            transformerEvaluateDataVo.setRelayAction(relayAction != null ? String.valueOf(relayAction) : null);

            Double reliefValveAction = this.getRules(mainTreeId, TransformerAssessEnum.PRESSURE_RELEASE_VALVE_ACTION.getKey());
            transformerEvaluateDataVo.setReliefValveAction(reliefValveAction != null ? String.valueOf(reliefValveAction) : null);


            /**附件高压套管**/
            Double finalScreenInsulationResistance = this.getRules(mainTreeId, TransformerAssessEnum.FINAL_SCREEN_INSULATION_RESISTANCE.getKey());
            transformerEvaluateDataVo.setEndScreenInsulationResistance(finalScreenInsulationResistance != null ? String.valueOf(finalScreenInsulationResistance) : null);

            Double totalCurrent = this.getRules(mainTreeId, TransformerAssessEnum.TOTAL_CURRENT.getKey());
            transformerEvaluateDataVo.setTotalCurrent(totalCurrent != null ? String.valueOf(totalCurrent) : null);

            Double capacitativeCurrent = this.getRules(mainTreeId, TransformerAssessEnum.CAPACITATIVE_CURRENT.getKey());
            transformerEvaluateDataVo.setCapacitiveCurrent(capacitativeCurrent != null ? String.valueOf(capacitativeCurrent) : null);

            Double resistiveCurrent = this.getRules(mainTreeId, TransformerAssessEnum.RESISTIVE_CURRENT.getKey());
            transformerEvaluateDataVo.setResistiveCurrent(resistiveCurrent != null ? String.valueOf(resistiveCurrent) : null);

            Double infraredTemperature = this.getRules(mainTreeId, TransformerAssessEnum.INFRARED_TEMPERATURE.getKey());
            transformerEvaluateDataVo.setInfraredTemperature(infraredTemperature != null ? String.valueOf(infraredTemperature) : null);

            Double casingDielectricLoss = this.getRules(mainTreeId, TransformerAssessEnum.ROUTINE_TEST_OF_CASING_DIELECTRIC_DAMAGE.getKey());
            transformerEvaluateDataVo.setCasingDielectricLoss(casingDielectricLoss != null ? String.valueOf(casingDielectricLoss) : null);

            Double endScreenDielectricDamage = this.getRules(mainTreeId, TransformerAssessEnum.FINAL_SCREEN_DIELECTRIC_LOSS.getKey());
            transformerEvaluateDataVo.setEndScreenDielectricDamage(endScreenDielectricDamage != null ? String.valueOf(endScreenDielectricDamage) : null);

            Double finalScreenInsulationCapacitance = this.getRules(mainTreeId, TransformerAssessEnum.LAST_SCREEN_INSULATION_CAPACITANCE.getKey());
            transformerEvaluateDataVo.setFinalScreenInsulationCapacitance(finalScreenInsulationCapacitance != null ? String.valueOf(finalScreenInsulationCapacitance) : null);

            Double casingH2 = this.getRules(mainTreeId, TransformerAssessEnum.HIGH_PRESSURE_CASING_H2.getKey());
            transformerEvaluateDataVo.setCasingH2(casingH2 != null ? String.valueOf(casingH2) : null);

            Double casingCh4 = this.getRules(mainTreeId, TransformerAssessEnum.HIGH_PRESSURE_CASING_CH4.getKey());
            transformerEvaluateDataVo.setCasingCh4(casingCh4 != null ? String.valueOf(casingCh4) : null);

            Double casingC2h2 = this.getRules(mainTreeId, TransformerAssessEnum.HIGH_PRESSURE_CASING_C2H2.getKey());
            transformerEvaluateDataVo.setCasingC2h2(casingC2h2 != null ? String.valueOf(casingC2h2) : null);

            /*****************************************变压器负荷率*****************************************/
            Double workingVoltage = this.getRules(mainTreeId, TransformerAssessEnum.WORKING_VOLTAGE.getKey());
            transformerEvaluateDataVo.setWorkingVoltage(workingVoltage != null ? String.valueOf(workingVoltage) : null);

            Double workingCurrent = this.getRules(mainTreeId, TransformerAssessEnum.WORKING_CURRENT.getKey());
            transformerEvaluateDataVo.setWorkingCurrent(workingCurrent != null ? String.valueOf(workingCurrent) : null);

            Double workingTime = this.getRules(mainTreeId, TransformerAssessEnum.WORKING_TIME.getKey());
            transformerEvaluateDataVo.setWorkingTime(workingTime != null ? String.valueOf(workingTime) : null);

            Double pumpingVoltage = this.getRules(mainTreeId, TransformerAssessEnum.PUMPING_VOLTAGE.getKey());
            transformerEvaluateDataVo.setPumpingVoltage(pumpingVoltage != null ? String.valueOf(pumpingVoltage) : null);

            Double pumpingCurrent = this.getRules(mainTreeId, TransformerAssessEnum.PUMPING_CURRENT.getKey());
            transformerEvaluateDataVo.setPumpingCurrent(pumpingCurrent != null ? String.valueOf(pumpingCurrent) : null);

            Double pumpingTime = this.getRules(mainTreeId, TransformerAssessEnum.PUMPING_TIME.getKey());
            transformerEvaluateDataVo.setPumpingTime(pumpingTime != null ? String.valueOf(pumpingTime) : null);

            Double capacitance = this.getRules(mainTreeId, TransformerAssessEnum.HIGH_PRESSURE_CASING_CAPACITANCE.getKey());
            transformerEvaluateDataVo.setCapacitance(capacitance != null ? String.valueOf(capacitance) : null);

            iTransformerEvaluateDataService.save(token, transformerEvaluateDataVo);
        }
    }

    /**
     * 新增获取油色谱离线数据
     *
     * @param token
     * @param mainTreeId
     */
    private void saveTransformerEpaOfflineData(String token, List<LabReportMarkStatistic> list, String mainTreeId) {
        // 根据主设备编号查询打标信息数据表
        if (CollectionUtil.isNotEmpty(list)) {
            TransformerEpaOfflineData transformerEpaOfflineData = new TransformerEpaOfflineData();
            transformerEpaOfflineData.setId(Uuid.getUUID());
            transformerEpaOfflineData.setMainEquipmentId(mainTreeId);

            Double h2 = this.getRules(mainTreeId, TransformerAssessEnum.H2.getKey());
            transformerEpaOfflineData.setH2(h2 != null ? String.valueOf(h2) : null);

            Double ch4 = this.getRules(mainTreeId, TransformerAssessEnum.CH4.getKey());
            transformerEpaOfflineData.setCh4(ch4 != null ? String.valueOf(ch4) : null);

            Double c2h2 = this.getRules(mainTreeId, TransformerAssessEnum.C2H2.getKey());
            transformerEpaOfflineData.setC2h2(c2h2 != null ? String.valueOf(c2h2) : null);

            Double c2h4 = this.getRules(mainTreeId, TransformerAssessEnum.C2H4.getKey());
            transformerEpaOfflineData.setC2h4(c2h4 != null ? String.valueOf(c2h4) : null);

            Double c2h6 = this.getRules(mainTreeId, TransformerAssessEnum.C2H6.getKey());
            transformerEpaOfflineData.setC2h6(c2h6 != null ? String.valueOf(c2h6) : null);

            Double co = this.getRules(mainTreeId, TransformerAssessEnum.CO.getKey());
            transformerEpaOfflineData.setCo(co != null ? String.valueOf(co) : null);

            Double co2 = this.getRules(mainTreeId, TransformerAssessEnum.CO2.getKey());
            transformerEpaOfflineData.setCo2(co2 != null ? String.valueOf(co2) : null);

            Double zj = this.getRules(mainTreeId, TransformerAssessEnum.ZJ.getKey());
            transformerEpaOfflineData.setZt(zj != null ? String.valueOf(zj) : null);

            transformerEpaOfflineDataService.save(token, transformerEpaOfflineData);
        }
    }

    @Override
    public Map<String, Object> drivepipeDiagnosis(String token, BusiDrivepipeEvaluationResultsDto dto) {
        String mainTreeId = dto.getMainTreeId();
        TransformerEvaluateDataVo vo = new TransformerEvaluateDataVo();
        vo.setCasingDielectricLoss(dto.getCasingDielectricLoss());
        vo.setCasingH2(dto.getCasingH2());
        vo.setCasingCh4(dto.getCasingCh4());
        vo.setCasingC2h2(dto.getCasingC2h2());
        List<BusiParamTransformerVo> params = this.getTransformerParams(dto.getSiteId(), mainTreeId);
        Map<String, BusiParamTransformerVo> map = this.convertParams("3", params);
        Map<String, Object> drivepipeResult = this.drivepipeEvaluation(mainTreeId, vo, map);
        return drivepipeResult;
    }

    /**
     * 对于变压器 ：w投运时间，B是修正后的变压器老化系数，x是初始老化系数  2024/1/9
     * 套管未来故障算法
     * 公式：f(x)=1-exp(-(x/w)^b)
     * x = 套管（H2/C2H2/CH4，绝缘)最终计算健康指数
     * w = 变压器投运后一个月，开始计算的，到今天的运行时间（小时）
     * b = b修正系数=0.98
     */
    public Map<String, Object> drivepipeEvaluation(String mainTreeId, TransformerEvaluateDataVo vo, Map<String, BusiParamTransformerVo> map) {
        //套管介损
        String casingloss = vo.getCasingDielectricLoss();
        //套管H2
        String casingh2 = vo.getCasingH2();
        //套管CH4
        String casingCh4 = vo.getCasingCh4();
        //套管C2H2
        String casingC2h2 = vo.getCasingC2h2();

        Double insulate = null;
        Double H2 = null;
        Double CH4 = null;
        Double C2H2 = null;
        BigDecimal number = BigDecimal.valueOf(0);
        Double b = 0.98;
        Double w = null;
        BigDecimal resultInsulate = BigDecimal.valueOf(0);
        BigDecimal resultH2 = BigDecimal.valueOf(0);
        BigDecimal resultCH4 = BigDecimal.valueOf(0);
        BigDecimal resultC2H2 = BigDecimal.valueOf(0);

        Date startTime = busiOfflineTransformerBrandMapper.getStartTime(mainTreeId);
        Date nowTime = new Date();
        double time = (nowTime.getTime() - startTime.getTime()) / (1000 * 3600 * 24);
        if (time > 30) {
            w = (time - 30) * 24;
        } else {
            log.error("投运时间未超一个月！");
            throw new OwlException("投运时间未超一个月！");
        }

        String insulateA = null;
        String insulateB = null;
        if (casingloss != null) {
            BusiParamTransformerVo tmp = this.getEvaluateObject(EvaluateConstant.FJTG_TGJS, map);
            insulate = this.calcWeight2(casingloss, tmp);
            insulateA = tmp.getAValue().setScale(2, RoundingMode.HALF_UP).toString();
            insulateB = tmp.getBValue().setScale(2, RoundingMode.HALF_UP).toString();
            double step = Math.pow((insulate / w), b);
            double result = 1 - Math.exp(-step);
            resultInsulate = BigDecimal.valueOf(result).setScale(8, RoundingMode.HALF_UP);
            number = number.add(BigDecimal.valueOf(1));
            log.info("-- >> 套管介损计算结果: [{}]", insulate);
        }
        String h2A = null;
        String h2B = null;
        if (casingh2 != null) {
            BusiParamTransformerVo tmp1 = this.getEvaluateObject(EvaluateConstant.FJTG_TGH2, map);
            H2 = this.calcWeight2(casingh2, tmp1);
            h2A = tmp1.getAValue().setScale(2, RoundingMode.HALF_UP).toString();
            h2B = tmp1.getBValue().setScale(2, RoundingMode.HALF_UP).toString();
            double step = Math.pow((H2 / w), b);
            double result = 1 - Math.exp(-step);
            resultH2 = BigDecimal.valueOf(result).setScale(8, RoundingMode.HALF_UP);
            number = number.add(BigDecimal.valueOf(1));
            log.info("-- >> 套管H2计算结果: [{}]", H2);
        }
        String ch4A = null;
        String ch4B = null;
        if (casingCh4 != null) {
            BusiParamTransformerVo tmp2 = this.getEvaluateObject(EvaluateConstant.FJTG_TGCH4, map);
            CH4 = this.calcWeight2(casingCh4, tmp2);
            ch4A = tmp2.getAValue().setScale(2, RoundingMode.HALF_UP).toString();
            ch4B = tmp2.getBValue().setScale(2, RoundingMode.HALF_UP).toString();
            double step = Math.pow((CH4 / w), b);
            double result = 1 - Math.exp(-step);
            resultCH4 = BigDecimal.valueOf(result).setScale(8, RoundingMode.HALF_UP);
            number = number.add(BigDecimal.valueOf(1));
            log.info("-- >> 套管CH4计算结果: [{}]", CH4);
        }
        String c2h2A = null;
        String c2h2B = null;
        if (casingC2h2 != null) {
            BusiParamTransformerVo tmp3 = this.getEvaluateObject(EvaluateConstant.FJTG_TGC2H2, map);
            C2H2 = this.calcWeight2(casingC2h2, tmp3);
            c2h2A = tmp3.getAValue().setScale(2, RoundingMode.HALF_UP).toString();
            c2h2B = tmp3.getBValue().setScale(2, RoundingMode.HALF_UP).toString();
            double step = Math.pow((C2H2 / w), b);
            double result = 1 - Math.exp(-step);
            resultC2H2 = BigDecimal.valueOf(result).setScale(8, RoundingMode.HALF_UP);
            number = number.add(BigDecimal.valueOf(1));
            log.info("-- >> 套管C2H2计算结果: [{}]", C2H2);
        }
        BigDecimal weight = BigDecimal.valueOf(1).divide(number, 4, RoundingMode.HALF_UP);
        BigDecimal result = (resultInsulate.add(resultH2).add(resultCH4).add(resultC2H2)).multiply(weight).multiply(BigDecimal.valueOf(100));

        BusiDrivepipeEvaluationResults resultsData = new BusiDrivepipeEvaluationResults();
        resultsData.setId(Uuid.getUUID());
        resultsData.setBValue(b.toString());
        if (casingloss != null) {
            resultsData.setInsulate(casingloss);
        }
        if (casingh2 != null) {
            resultsData.setH2(casingh2);
        }
        if (casingCh4 != null) {
            resultsData.setCh4(casingCh4);
        }
        if (casingC2h2 != null) {
            resultsData.setC2h2(casingC2h2);
        }
        if (insulate != null) {
            resultsData.setHealthScoreInsulate(insulate.toString());
        }
        if (H2 != null) {
            resultsData.setHealthScoreH2(H2.toString());
        }
        if (CH4 != null) {
            resultsData.setHealthScoreCH4(CH4.toString());
        }
        if (C2H2 != null) {
            resultsData.setHealthScoreC2H2(C2H2.toString());
        }
        if (insulateA != null) {
            resultsData.setInsulateA(insulateA);
        }
        if (h2A != null) {
            resultsData.setH2A(h2A);
        }
        if (ch4A != null) {
            resultsData.setCh4A(ch4A);
        }
        if (c2h2A != null) {
            resultsData.setC2h2A(c2h2A);
        }
        if (insulateB != null) {
            resultsData.setInsulateB(insulateB);
        }
        if (h2B != null) {
            resultsData.setH2B(h2B);
        }
        if (ch4B != null) {
            resultsData.setCh4B(ch4B);
        }
        if (c2h2B != null) {
            resultsData.setC2h2B(c2h2B);
        }
        resultsData.setEvaluateDate(LocalDateTime.now());
        resultsData.setHours(w.toString());
        resultsData.setMainTreeId(mainTreeId);
        resultsData.setResult(result.toString());
        busiDrivepipeEvaluationResultsDao.add(resultsData);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "BUSINESS.QUERY.SUCCESS", result);
    }

    @Override
    public void transformerSemiAutomaticEvaluation(String siteId, String mainEquipmentId) {
        BusiOfflineTransformerBrand brand = busiOfflineTransformerBrandMapper.getBusiOfflineTransformerBrand(siteId, mainEquipmentId);
        transformerEvaluationTask.doExecute(Collections.singletonList(brand));
    }
}
