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

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import com.google.common.collect.Maps;
import com.huatek.busi.common.BusiConstant;
import com.huatek.busi.common.SiteConstants;
import com.huatek.busi.common.util.DateUtil;
import com.huatek.busi.dao.HotSpotTemperatureResultDao;
import com.huatek.busi.entity.*;
import com.huatek.busi.mapper.*;
import com.huatek.busi.service.*;
import com.huatek.busi.service.param.BusiParamTransformerService;
import com.huatek.busi.service.transformer.BusiOfflineTransformerBrandService;
import com.huatek.busi.service.transformer.TransformerEvaluateDataService;
import com.huatek.busi.service.transformer.TransformerEvaluationIntermediateValueService;
import com.huatek.busi.service.transformer.TransformerEvaluationResultsService;
import com.huatek.busi.task.transformer.utils.CommonUtils;
import com.huatek.busi.task.transformer.utils.accessories.*;
import com.huatek.busi.task.transformer.utils.insulationtest.*;
import com.huatek.busi.util.*;
import com.huatek.busi.vo.*;
import com.huatek.busi.vo.epa.*;
import com.huatek.frame.base.util.Constants;
import com.huatek.torch.util.uuid.Uuid;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

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

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

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

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

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

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


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

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

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

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

    public static TransformerFormulaSingleton instance = TransformerFormulaSingleton.getInstance();

    public static TransformerFormulaCal transformerFormulaCalInstance = TransformerFormulaCal.getInstance();

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

    @Resource
    private BusiSiteTreeService busiSiteTreeService;

    @Resource
    private ICalculateStepService calculateStepService;

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

    @Autowired
    private HotSpotTemperatureResultDao hotSpotTemperatureResultDao;

    @Autowired
    private TransformerMeteorologicalStatisticsMapper transformerMeteorologicalStatisticsMapper;

    @Autowired
    private TransformerDateOnlineService transformerDateOnlineService;

    @Resource
    private XTransformerEvaluateDataMapper xTransformerEvaluateDataMapper;

    @Autowired
    private SoundVibrationParamsMapper soundVibrationParamsMapper;

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

    @Autowired
    private BusiEqmWarningService busiEqmWarningService;

    @Autowired
    public BusiSemiAutomaticEvaluateConfigService busiSemiAutomaticEvaluateConfigService;
    @Autowired
    public BusiSemiAutomaticEvaluateDataService busiSemiAutomaticEvaluateDataService;

    private static final int INTERVAL_DAY = 15;
    // 报告路径
    private String filePath = "transformer";

    public void execute() {
        List<BusiOfflineTransformerBrand> transformerlist = this.getTransformerlist();
        doExecute(transformerlist);
    }

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

            for (BusiOfflineTransformerBrand brand : transformerlist) {
                try {
                    //mainTreeId  busi_site_tree 站点树id
                    String mainTreeId = brand.getMainEquipmentId();
                    String siteId = brand.getSiteId();
                    String name = brand.getTransformerName();
                    //主设备id
                    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());

                    if(isSemiAuto()){
                        BusiSemiAutomaticEvaluateDataVo latest = busiSemiAutomaticEvaluateDataService.getLatest(BusiConstant.EqType.EQ_TYPE1, brand.getMainEquipmentId(), brand.getSiteId());
                        if (latest == null) {
                            log.error("--->> 变压器:[{}],未录入半自动评测数据", name);
                            intermediateValue.setFailureRreasons("未录入半自动评测数据");
                            transformerEvaluationIntermediateValueService.save(intermediateValue);
                            TransfromerCreateUtil.createFile(intermediateValue, false, basePath, filePath, fileName, date);
                            transformerDateOnlineService.warringEvaluating(SiteConstants.BYQ, BusiConstant.GzType.GZ_TYPE25, "变压器评测-未录入半自动评测数据", mainTreeId, name);
                            continue;
                        }else {
                            LocalDateTime createTime = latest.getCreateTime();
                            LocalDateTime now = LocalDateTime.now();
                            LocalDateTime plusDays = createTime.plusDays(INTERVAL_DAY);
                            if (plusDays.isBefore(now)) {
                                log.error("--->> 变压器:[{}],超过15天未录入半自动评测数据", name);
                                TransformerEvaluationIntermediateValue intermediateValueCopy = new TransformerEvaluationIntermediateValue();
                                BeanUtils.copyProperties(intermediateValue,intermediateValueCopy);
                                intermediateValueCopy.setId(Uuid.getUUID());
                                intermediateValueCopy.setFailureRreasons("超过15天未录入半自动评测数据");
                                transformerEvaluationIntermediateValueService.save(intermediateValueCopy);
                                TransfromerCreateUtil.createFile(intermediateValueCopy, false, basePath, filePath, fileName, date);
                                transformerDateOnlineService.warringEvaluating(SiteConstants.BYQ, BusiConstant.GzType.GZ_TYPE25, "变压器评测-超过15天未录入半自动评测数据", mainTreeId, name);
                            }
                        }
                    }

                    TransformerEvaluateDataVo evaluateData = transformerDateOnlineService.getTransformerEvaluateDataVo(mainTreeId);
                    if (null == evaluateData) {
                        log.error("--->> 变压器:[{}],未导入试验报告", name);
                        intermediateValue.setFailureRreasons("未导入试验报告");
                        transformerEvaluationIntermediateValueService.save(intermediateValue);
                        TransfromerCreateUtil.createFile(intermediateValue, false, basePath, filePath, fileName, date);
                        transformerDateOnlineService.warringEvaluating(SiteConstants.BYQ, BusiConstant.GzType.GZ_TYPE25, "变压器评测-未导入试验报告", mainTreeId, name);
                        continue;
                    }

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

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

                    if (fristLevelMap.size() == 0 || secondLevelMap.size() == 0 || threeLevelMap.size() == 0) {
                        log.error("--->>变压器评测-变压器评估参数为空");
                        intermediateValue.setFailureRreasons("变压器评估参数为空");
                        transformerEvaluationIntermediateValueService.save(intermediateValue);
                        TransfromerCreateUtil.createFile(intermediateValue, false, basePath, filePath, fileName, date);
                        continue;
                    }

                    EpaEvaluateDataVo epaEvaluateData = null;
                    EpaPdDataVo pdEvaluateData = null;
                    EpaIcgeDataVo epaIcgeDataVo = null;
                    EpaSoundVibrationVo soundEvaluateData = null;
                    EpaCapacitanceDataVo epaCapacitanceDataVo = null;
                    EpaInfraredMonitorDataVo epaInfraredMonitorDataVo = null;
                    EpaRunStatusDataVo runStatusEvaluateData = null;
                    EpaEnvironmentDataVo epaEnvironmentDataVo = null;


                    // 查询油色谱在线数据
                    BusiParamTransformerVo yspParams = secondLevelMap.get(EvaluateConstant.YSP);
                    if (null != yspParams && yspParams.getIsAttend().equals("1")) {
                        String sensorCode = this.getEpaSensorCode(id);
                        epaEvaluateData = transformerDateOnlineService.getEpaEvaluateData(id, sensorCode);
                        if (null == epaEvaluateData) {
                            log.error("--->>变压器评测-油色谱数据为空");
                            intermediateValue.setFailureRreasons("变压器评测-油色谱数据为空");
                            transformerEvaluationIntermediateValueService.save(intermediateValue);
                            TransfromerCreateUtil.createFile(intermediateValue, false, basePath, filePath, fileName, date);
                            transformerDateOnlineService.warringEvaluating(SiteConstants.BYQ, BusiConstant.GzType.GZ_TYPE25, "变压器评测-油色谱数装置未安装或未采集到数据", mainTreeId, name);
                            continue;
                        }
                    }

                    //局放放电量（PC）在线数据
                    BusiParamTransformerVo jfParams = threeLevelMap.get(EvaluateConstant.LXSY_JFFDL);
                    if (null != jfParams && jfParams.getIsAttend().equals("1")) {
                        pdEvaluateData = transformerDateOnlineService.getPdEvaluateData(mainTreeId);
                        if (null == pdEvaluateData) {
                            log.error("--->>变压器评测-局放放电量在线数据为空");
                            intermediateValue.setFailureRreasons("变压器评测-局放放电量在线数据为空");
                            transformerEvaluationIntermediateValueService.save(intermediateValue);
                            TransfromerCreateUtil.createFile(intermediateValue, false, basePath, filePath, fileName, date);
                            transformerDateOnlineService.warringEvaluating(SiteConstants.BYQ, BusiConstant.GzType.GZ_TYPE25, "变压器评测-局放放电量装置未安装或未采集到数据", mainTreeId, name);
                            continue;
                        }
                    }

                    // 铁芯接地在线数据
                    BusiParamTransformerVo txjdParams = threeLevelMap.get(EvaluateConstant.ZDXSY_TXJDDL);
                    if (null != txjdParams && txjdParams.getIsAttend().equals("1")) {
                        epaIcgeDataVo = transformerDateOnlineService.getIcgeEvaluateData(id);
                        if (null == epaIcgeDataVo) {
                            log.error("--->>变压器评测-铁芯接地在线数据为空");
                            intermediateValue.setFailureRreasons("变压器评测-铁芯接地在线数据为空");
                            transformerEvaluationIntermediateValueService.save(intermediateValue);
                            TransfromerCreateUtil.createFile(intermediateValue, false, basePath, filePath, fileName, date);
                            transformerDateOnlineService.warringEvaluating(SiteConstants.BYQ, BusiConstant.GzType.GZ_TYPE25, "变压器评测-铁芯接地装置未安装或未采集到数据", mainTreeId, name);
                            continue;
                        }
                    }

                    //声级振动在线数据
                    BusiParamTransformerVo sjzdParams = secondLevelMap.get(EvaluateConstant.BYQ_SJZD);
                    if (null != sjzdParams && sjzdParams.getIsAttend().equals("1")) {
                        soundEvaluateData = transformerDateOnlineService.getSoundEvaluateData(mainTreeId);
                        if (null == soundEvaluateData) {
                            log.error("--->>变压器评测-声级振动在线数据为空");
                            intermediateValue.setFailureRreasons("变压器评测-声级振动在线数据为空");
                            transformerEvaluationIntermediateValueService.save(intermediateValue);
                            TransfromerCreateUtil.createFile(intermediateValue, false, basePath, filePath, fileName, date);
                            transformerDateOnlineService.warringEvaluating(SiteConstants.BYQ, BusiConstant.GzType.GZ_TYPE25, "变压器评测-声级振动装置未安装或未采集到数据", mainTreeId, name);
                            continue;
                        }
                    }
                    //噪声
                    BusiParamTransformerVo zsParams = threeLevelMap.get(EvaluateConstant.BYQ_BT_BYQZS);
                    if (null != zsParams && zsParams.getIsAttend().equals("1")) {
                        soundEvaluateData = transformerDateOnlineService.getSoundEvaluateData(mainTreeId);
                        if (null == soundEvaluateData) {
                            log.error("--->>变压器评测-噪声在线数据为空");
                            intermediateValue.setFailureRreasons("变压器评测-噪声在线数据为空");
                            transformerEvaluationIntermediateValueService.save(intermediateValue);
                            TransfromerCreateUtil.createFile(intermediateValue, false, basePath, filePath, fileName, date);
                            transformerDateOnlineService.warringEvaluating(SiteConstants.BYQ, BusiConstant.GzType.GZ_TYPE25, "变压器评测-噪声在线装置未安装或未采集到数据", mainTreeId, name);
                            continue;
                        }
                    }

                    // 容性设备 全电流（mA） 容性电流
                    BusiParamTransformerVo qParams = threeLevelMap.get(EvaluateConstant.BYQ_TG_QDL);
                    BusiParamTransformerVo rParams = threeLevelMap.get(EvaluateConstant.BYQ_TG_MPJYDR);
                    if ((null != qParams && qParams.getIsAttend().equals("1"))
                            || (null != rParams && rParams.getIsAttend().equals("1"))) {
                        epaCapacitanceDataVo = transformerDateOnlineService.getCapacitanceEvaluateData(mainTreeId);
                        if (null == epaCapacitanceDataVo) {
                            log.error("--->>变压器评测-绝缘介质在线数据为空");
                            intermediateValue.setFailureRreasons("变压器评测-绝缘介质在线数据为空");
                            transformerEvaluationIntermediateValueService.save(intermediateValue);
                            TransfromerCreateUtil.createFile(intermediateValue, false, basePath, filePath, fileName, date);
                            transformerDateOnlineService.warringEvaluating(SiteConstants.BYQ, BusiConstant.GzType.GZ_TYPE25, "变压器评测-绝缘介质装置未安装或未采集到数据", mainTreeId, name);
                            continue;
                        }
                    }
                    //红外温度在线数据
                    BusiParamTransformerVo hwwdParams = threeLevelMap.get(EvaluateConstant.BYQ_TG_HWWD);
                    if (null != hwwdParams && hwwdParams.getIsAttend().equals("1")) {
                        epaInfraredMonitorDataVo = transformerDateOnlineService.getInfraredMonitorEvaluateData(mainTreeId);
                        if (null == epaInfraredMonitorDataVo) {
                            log.error("--->>变压器评测-红外温度在线数据为空");
                            intermediateValue.setFailureRreasons("变压器评测-红外温度在线数据为空");
                            transformerEvaluationIntermediateValueService.save(intermediateValue);
                            TransfromerCreateUtil.createFile(intermediateValue, false, basePath, filePath, fileName, date);
                            transformerDateOnlineService.warringEvaluating(SiteConstants.BYQ, BusiConstant.GzType.GZ_TYPE25, "变压器评测-红外温度装置未安装或未采集到数据", mainTreeId, name);
                            continue;
                        }
                    }
                    // 104-运行工况 水温  水压
                    BusiParamTransformerVo swParams = threeLevelMap.get(EvaluateConstant.BYQ_LQXT_SW);
                    BusiParamTransformerVo syParams = threeLevelMap.get(EvaluateConstant.BYQ_LQXT_SY);
                    if ((null != swParams && swParams.getIsAttend().equals("1"))
                            || (null != syParams && syParams.getIsAttend().equals("1"))) {
                        runStatusEvaluateData = transformerDateOnlineService.getRunStatusEvaluateData(mainTreeId);
                        if (null == runStatusEvaluateData) {
                            log.error("--->>变压器评测-104运行工况在线数据为空");
                            intermediateValue.setFailureRreasons("变压器评测-104运行工况在线数据为空");
                            transformerEvaluationIntermediateValueService.save(intermediateValue);
                            TransfromerCreateUtil.createFile(intermediateValue, false, basePath, filePath, fileName, date);
                            transformerDateOnlineService.warringEvaluating(SiteConstants.BYQ, BusiConstant.GzType.GZ_TYPE25, "变压器评测-104运行工况在线数据为空", mainTreeId, name);
                            continue;
                        }

                    }
                    //环境温度在线数据
                    BusiParamTransformerVo hjsdParams = threeLevelMap.get(EvaluateConstant.BYQ_LQXT_HJWD);
                    if (null != hjsdParams && hjsdParams.getIsAttend().equals("1")) {
                        epaEnvironmentDataVo = transformerDateOnlineService.getEnvironmentEvaluateData(mainTreeId);
                        if (null == epaEnvironmentDataVo) {
                            log.error("--->>变压器评测-环境温度在线数据为空");
                            intermediateValue.setFailureRreasons("变压器评测-环境温度在线数据为空");
                            transformerEvaluationIntermediateValueService.save(intermediateValue);
                            TransfromerCreateUtil.createFile(intermediateValue, false, basePath, filePath, fileName, date);
                            transformerDateOnlineService.warringEvaluating(SiteConstants.BYQ, BusiConstant.GzType.GZ_TYPE25, "变压器评测-环境温度在线数据为空", mainTreeId, name);
                            continue;
                        }
                    }

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

                    BusiParamTransformerVo weight1Vo = this.getEvaluateObject(EvaluateConstant.DESIGN_BRAND, fristLevelMap);
                    BusiParamTransformerVo weight2Vo = this.getEvaluateObject(EvaluateConstant.INDIVIDUAL_INSULATION, fristLevelMap);
                    BusiParamTransformerVo weight3Vo = this.getEvaluateObject(EvaluateConstant.HEREDITY_RISK, fristLevelMap);

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

                    JSONArray jsonArray = new JSONArray();
                    CalculateStep calculateStep = new CalculateStep();
                    calculateStep.setId(Uuid.getUUID());
                    calculateStep.setSiteId(brand.getSiteId());
                    if (null != busiSiteTree) {
                        calculateStep.setEquipmentType(busiSiteTree.getEquipmentType());
                    } else {
                        calculateStep.setEquipmentType("1");
                    }
                    calculateStep.setMainEquipmentId(mainEquipmentId);
                    calculateStep.setExecuteMode(Integer.valueOf(Constants.DEFAULT_YES));
                    calculateStep.setCreateTime(LocalDateTime.now());

                    int step = 0;

                    // 基本参数计算结果
                    //TODO: 1.变压器主绝缘老化状态健康指数
                    Map<String, Double> map = this.getTransformerAgingHealthIndex(brand, jsonArray, step);
                    Double agingHealthIndex = map.get("agingHealthIndex");
                    // 初始化老化系数
                    Double B0 = map.get("B0");
                    // 预期寿命
                    Double expectlife = map.get("expectlife");
                    // 设计寿命
                    String designLife = brand.getDesignLife();

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

                    Double individualInsulation = individualInsulationMap.get("TOTAL_INDEX");
                    step = Double.valueOf(individualInsulationMap.get("step").toString()).intValue();

                    //  3.部件可靠性计算结果
                    Map<String, Double> annexMap = this.calcDefectWeight(evaluateData, secondLevelMap, threeLevelMap, jsonArray, step, epaInfraredMonitorDataVo, runStatusEvaluateData, epaEnvironmentDataVo, soundEvaluateData, epaCapacitanceDataVo);
                    Double defectWeight = annexMap.get("TOTAL_INDEX");
                    step = Double.valueOf(annexMap.get("step").toString()).intValue();

                    //4. 糠醛指标
                    Map<String, Object> map3 = FurfuralTndexTest.calcFurIndexWeight(evaluateData, fristLevelMap, secondLevelMap, jsonArray, step);
                    Double kqzb = Double.valueOf(map3.get(CommonUtils.TOTAL).toString());
                    step = Integer.parseInt(map3.get(CommonUtils.STEP).toString());

                    //5. 绝缘纸实验
                    Map<String, Object> map4 = InsulationPaperTest.calcInsulationPaperWeight(evaluateData, fristLevelMap, secondLevelMap, jsonArray, step);
                    Double jyz = Double.valueOf(map4.get(CommonUtils.TOTAL).toString());
                    step = Integer.parseInt(map4.get(CommonUtils.STEP).toString());


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

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

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

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

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

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


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

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

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

                    // 绕组测温数据 TODO
                    List<TransformerWindingTemperatureVo> winding = this.getWindingTempreature(mainEquipmentId);
                    double naturalAgingRate = 0;
                    JSONArray jsonArray2 = new JSONArray();
                    com.alibaba.fastjson.JSONObject jsonObject2 = new com.alibaba.fastjson.JSONObject();
                    HotSpotTemperatureResult temperatureResult = new HotSpotTemperatureResult();
                    temperatureResult.setId(Uuid.getUUID());
                    temperatureResult.setResult(Uuid.getUUID());
                    temperatureResult.setMainTreeId(mainTreeId);
                    temperatureResult.setType("2"); //自动
                    temperatureResult.setAssessTime(LocalDateTime.now());
                    temperatureResult.setSiteId(siteId);
                    if (winding == null || winding.isEmpty()) {
                        // 老算法 CO2/CO
                        naturalAgingRate = this.calcNaturalAgingRate(epaEvaluateData);
                        log.info("--->> 变压器自然老化率：[{}] ", naturalAgingRate);
                        jsonObject.clear();
                        jsonObject.put("co", epaEvaluateData.getCo());
                        jsonObject.put("co2", Double.valueOf(epaEvaluateData.getCo2()) * 0.65);
                        step += 1;

                        temperatureResult.setCo2(String.valueOf(Double.parseDouble(epaEvaluateData.getCo2()) * 0.65));
                        temperatureResult.setCo(String.valueOf(epaEvaluateData.getCo()));
                        temperatureResult.setArithmeticType("2");
                        jsonObject2.put("co2", Double.parseDouble(epaEvaluateData.getCo2()) * 0.65);
                        jsonObject2.put("co", epaEvaluateData.getCo());
                    } else {
                        double t = 0;
                        double v = 0;
                        for (TransformerWindingTemperatureVo transformerWindingTemperatureVo : winding) {
                            String temperature = transformerWindingTemperatureVo.getMaxTmp();
                            BigDecimal h = BigDecimal.valueOf(Double.parseDouble(temperature));
                            Double v1 = transformerFormulaCalInstance.calculateWindingTemp(h, epaEvaluateData);
                            v += v1;
                            t += Double.parseDouble(temperature);
                        }
                        naturalAgingRate = v / winding.size();
                        temperatureResult.setAgingCoefficient(String.valueOf(B));
                        temperatureResult.setWindingTemperature(String.valueOf(t / winding.size()));
                        temperatureResult.setArithmeticType("3");
                        jsonObject2.put("自然老化率", naturalAgingRate);
                        jsonObject2.put("绕组最高温度", String.valueOf(t / winding.size()));
                    }
                    temperatureResult.setResult(String.valueOf(naturalAgingRate));
                    temperatureResult.setCalculationStep(jsonArray2.toString());
                    hotSpotTemperatureResultDao.add(temperatureResult);
                    double surplus = transformerFormulaCalInstance.calcSurplus(correctionThealthyIndex, B);
                    log.info("--->> 变压器剩余寿命：[{}] ", surplus);
                    jsonObject.clear();
                    jsonObject.put("correctionThealthyIndex", correctionThealthyIndex);
                    jsonObject.put("B", B);
                    step += 1;

                    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("2");
                    this.tansfrerMsg(result, correctionThealthyIndex, jsonArray, step);
                    TransformerEvaluationDescUtil.evaluatDesc(result);
                    transformerEvaluationResultsService.save(result);

                    /*******************************评估中间变量******************************************/

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


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

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

                    // 新增算法步骤
                    calculateStep.setStepJson(EvaluationNameUtil.listToJson());
                    calculateStep.setPId(result.getId());
                    try {
                        Runnable runnable = () -> {
                            calculateStepService.insert(calculateStep);
                            EvaluationNameUtil.cleanList();
                        };
                        new Thread(runnable).start();
                    } catch (Exception e1) {

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

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

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

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


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

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

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

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

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

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

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

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


    /**
     * @Description: 计算个体绝缘
     * @param transformerEvaluateDataVo 评测参数
     * @param soundEvaluateData  声级振动值
     * @param epaEvaluateData   油色谱值
     * @param secondLevelMap
     * @param threeLevelMap
     * @param jsonArray
     * @param step
     * @Return: java.util.Map<java.lang.String, java.lang.Double>
     */
    public Map<String, Double> calcIndividualInsulation(TransformerEvaluateDataVo transformerEvaluateDataVo,
                                                        EpaSoundVibrationVo soundEvaluateData,
                                                        EpaEvaluateDataVo epaEvaluateData,
                                                        Map<String, BusiParamTransformerVo> secondLevelMap,
                                                        Map<String, BusiParamTransformerVo> threeLevelMap,
                                                        JSONArray jsonArray,
                                                        int step,
                                                        EpaPdDataVo pdEvaluateData,
                                                        EpaIcgeDataVo epaIcgeDataVo) {

        Map<String, Double> map = new HashMap<>();
        double total = 0d;
        //油色谱
        Map<String, Object> map1 = OilTest.calcOilChromatographicTestWeight(epaEvaluateData, secondLevelMap, threeLevelMap, jsonArray, step);
        if (null != map1) {
            Double value = Double.valueOf(map1.get(CommonUtils.TOTAL).toString());
            step = Integer.parseInt(map1.get(CommonUtils.STEP).toString());
            total = total + value;
        }

        //油质试验
        Map<String, Object> map2 = OilQualityTest.calcOilQualityWeight(transformerEvaluateDataVo, secondLevelMap, threeLevelMap, jsonArray, step);
        if (null != map2) {
            Double value = Double.valueOf(map2.get(CommonUtils.TOTAL).toString());
            step = Integer.valueOf(map2.get(CommonUtils.STEP).toString());
            total = total + value;
        }
//        //-糠醛指标
//        Map<String, Object> map3 = FurfuralTndexTest.calcFurIndexWeight(transformerEvaluateDataVo, secondLevelMap, threeLevelMap, jsonArray, step);
//        if (null != map3) {
//            Double value = Double.valueOf(map3.get(CommonUtils.TOTAL).toString());
//            step = Integer.valueOf(map3.get(CommonUtils.STEP).toString());
//            total = total + value;
//        }
//
//        //绝缘纸实验
//        Map<String, Object> map4 = InsulationPaperTest.calcInsulationPaperWeight(transformerEvaluateDataVo, secondLevelMap, threeLevelMap, jsonArray, step);
//        if (null != map4) {
//            Double value = Double.valueOf(map4.get(CommonUtils.TOTAL).toString());
//            step = Integer.valueOf(map4.get(CommonUtils.STEP).toString());
//            total = total + value;
//        }

        //例行试验
        Map<String, Object> map6 = RoutineTest.calcRoutineTestWeight(transformerEvaluateDataVo, secondLevelMap, threeLevelMap, jsonArray, step, pdEvaluateData);
        if (null != map6) {
            Double value = Double.valueOf(map6.get(CommonUtils.TOTAL).toString());
            step = Integer.valueOf(map6.get(CommonUtils.STEP).toString());
            total = total + value;
        }

        //诊断性试验
        Map<String, Object> map5 = DiagnosticTest.calcDiagnosticTestWeight(transformerEvaluateDataVo, secondLevelMap, threeLevelMap, jsonArray, step, epaIcgeDataVo);
        if (null != map5) {
            Double value = Double.valueOf(map5.get(CommonUtils.TOTAL).toString());
            step = Integer.valueOf(map5.get(CommonUtils.STEP).toString());
            total = total + value;
        }

        //声级振动
        Map<String, Object> map7 = SoundLevelVibration.calcSoundLevelVibrationWeight(soundEvaluateData, secondLevelMap, threeLevelMap, jsonArray, step);
        if (null != map7) {
            Double value = Double.valueOf(map7.get(CommonUtils.TOTAL).toString());
            step = Integer.valueOf(map7.get(CommonUtils.STEP).toString());
            total = total + value;
        }
        log.info("-->>变压器绝缘试验: [{}]", total);
        step += 1;
        map.put("TOTAL_INDEX", total);
        map.put("step", Double.valueOf(step));
        return map;
    }

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


    public Map<String, Double> calcDefectWeight(TransformerEvaluateDataVo epaEvaluateData,
                                                Map<String, BusiParamTransformerVo> secondLevelMap,
                                                Map<String, BusiParamTransformerVo> threeLevelMap,
                                                JSONArray jsonArray,
                                                int step,
                                                EpaInfraredMonitorDataVo epaInfraredMonitorDataVo,
                                                EpaRunStatusDataVo runStatusEvaluateData,
                                                EpaEnvironmentDataVo epaEnvironmentDataVo,
                                                EpaSoundVibrationVo soundEvaluateData,
                                                EpaCapacitanceDataVo epaCapacitanceDataVo) {
        Map<String, Double> map = new HashMap<>();
        double total = 0d;

        //变压器器身
        Map<String, Object> map1 = TransformerBody.calcTransformerBodyWeight(epaEvaluateData, secondLevelMap, threeLevelMap, jsonArray, step, soundEvaluateData);
        if (null != map1) {
            Double value = Double.valueOf(map1.get(CommonUtils.TOTAL).toString());
            step = Integer.valueOf(map1.get(CommonUtils.STEP).toString());
            total = total + value;
        }

        //变压器冷却系统
        Map<String, Object> map2 = TransformerCoolingSystem.calcTransformerCoolingWeight(epaEvaluateData, secondLevelMap, threeLevelMap, jsonArray, step, runStatusEvaluateData, epaEnvironmentDataVo);
        if (null != map2) {
            Double value = Double.valueOf(map2.get(CommonUtils.TOTAL).toString());
            step = Integer.valueOf(map2.get(CommonUtils.STEP).toString());
            total = total + value;
        }
        //分接开关
        Map<String, Object> map3 = TapChanger.calcTapChangerWeight(epaEvaluateData, secondLevelMap, threeLevelMap, jsonArray, step);
        if (null != map3) {
            Double value = Double.valueOf(map3.get(CommonUtils.TOTAL).toString());
            step = Integer.valueOf(map3.get(CommonUtils.STEP).toString());
            total = total + value;
        }

        //非电量保护装置
        Map<String, Object> map4 = NonElectricQuantityProtectionDevice.calcNonElectricQuantityWeight(epaEvaluateData, secondLevelMap, threeLevelMap, jsonArray, step);
        if (null != map4) {
            Double value = Double.valueOf(map4.get(CommonUtils.TOTAL).toString());
            step = Integer.valueOf(map4.get(CommonUtils.STEP).toString());
            total = total + value;
        }

        //变压器高压套管
        Map<String, Object> map5 = TransformerHighVoltageBushing.calcHighVoltageWeight(epaEvaluateData, secondLevelMap, threeLevelMap, jsonArray, step, epaInfraredMonitorDataVo, epaCapacitanceDataVo);
        if (null != map5) {
            Double value = Double.valueOf(map5.get(CommonUtils.TOTAL).toString());
            step = Integer.valueOf(map5.get(CommonUtils.STEP).toString());
            total = total + value;
        }

        log.info("-->>变压器附件计算结果:[{}]", total);
        step += 1;
        map.put("TOTAL_INDEX", total);
        map.put("step", Double.valueOf(step));
        return map;
    }

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

        double L = transformerFormulaCalInstance.calcL(value);
        step += 1;

        double tmp = 1d - L;
        step += 1;

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

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

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

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

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

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

	/*

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

	 *
	 * */


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

        com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
        jsonObject.put("healthIndex", result.getHealthIndex());
        jsonObject.put("advice", result.getAdvice());
        step += 1;
    }


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


    public BusiParamTransformerVo getEvaluateObject(String key, Map<String, BusiParamTransformerVo> map) {
        if (map.containsKey(key)) {
            return map.get(key);
        }
        return null;
    }

    private boolean isSemiAuto(){
        BusiSemiAutomaticEvaluateConfigVo newestConfig = busiSemiAutomaticEvaluateConfigService.findNewestConfig();
        return newestConfig != null && newestConfig.getMark().equals("1");
    }

    /**
     * 计算负荷率根据录入的数据
     * @return 负荷率
     */
    private Double getLoad(BusiOfflineTransformerBrand brand){
        BusiSemiAutomaticEvaluateDataVo latest = busiSemiAutomaticEvaluateDataService.getLatest(BusiConstant.EqType.EQ_TYPE1, brand.getMainEquipmentId(), brand.getSiteId());
        String ratedCapacity = brand.getRatedCapacity();
        double totalCapacity = Double.parseDouble(ratedCapacity) * 1000d * 1000d * 24d * 60d * 60d;
        double current = Double.parseDouble(latest.getCurrent());
        double voltage = Double.parseDouble(latest.getVoltage());
        double duration = latest.getDuration().multiply(new BigDecimal("3600")).doubleValue();
        double total  = duration * current * voltage;
        double loadRate = total / totalCapacity;
        return new BigDecimal(loadRate).setScale(4, RoundingMode.UP).doubleValue();
    }
}
