package com.huatek.busi.service.impl.arrester;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Maps;
import com.huatek.busi.common.GisAssessEnum;
import com.huatek.busi.common.ParamEnum;
import com.huatek.busi.common.SiteConstants;
import com.huatek.busi.common.util.ComputeUtil;
import com.huatek.busi.dto.BusiOfflineGisRepairDto;
import com.huatek.busi.dto.BusiOutlineGisExperimentDataDto;
import com.huatek.busi.dto.LightningrodImDto;
import com.huatek.busi.entity.*;
import com.huatek.busi.mapper.BusiParamArresterMapper;
import com.huatek.busi.mapper.BusiParamTempletMapper;
import com.huatek.busi.mapper.LightningrodImMapper;
import com.huatek.busi.service.*;
import com.huatek.busi.service.BusiOutlineGisExperimentDataService;
import com.huatek.busi.service.arrester.BusiOfflineArresterBrandService;
import com.huatek.busi.service.arrester.LightningrodImService;
import com.huatek.busi.service.gis.*;
import com.huatek.busi.service.param.BusiParamArresterService;
import com.huatek.busi.service.param.BusiParamGisService;
import com.huatek.busi.service.substation.SubstationMicGisService;
import com.huatek.busi.service.transformer.TransformerPdStatisticsService;
import com.huatek.busi.util.*;
import com.huatek.busi.vo.*;
import com.huatek.frame.base.util.Constants;
import com.huatek.torch.frame.exception.OwlException;
import com.huatek.torch.util.uuid.Uuid;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.ObjectUtils;
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.CollectionUtils;

import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

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

    @Reference(check = false)
    ICalculateStepService calculateStepService;

    @Autowired
    private BusiParamArresterService busiParamArresterService;

    @Autowired
    private BusiParamArresterMapper busiParamArresterMapper;

    @Autowired
    private BusiOutlineGisExperimentDataService busiOutlineGisExperimentdataService;

    @Autowired
    private BusiOfflineArresterBrandService busiOfflineArresterBrandService;

    @Autowired
    private BusiOfflineGisRepairService busiOfflineGisRepairService;

    @Autowired
    private IecBreakerParamService iecBreakerParamService;

    @Autowired
    private SubstationMicGisService substationMicGisService;

    @Autowired
    private LightningrodImMapper lightningrodImMapper;

    @Autowired
    private RptGisMonitorSf6ChartsService rptGisMonitorSf6ChartsService;

    @Autowired
    private TransformerPdStatisticsService transformerPdStatisticsService;

    @Autowired
    private ArresterAssessmentResultService arresterAssessmentResultService;

    @Autowired
    private GisAssessmentResultDataService gisAssessmentResultDataService;
    @Autowired
    private BusiEqmWarningService busiEqmWarningService;

    @Autowired
    private BusiParamTempletMapper busiParamTempletMapper;

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

    public static GisFormulaCal gisFormulaCalInstance = GisFormulaCal.getInstance();

    /**
     * 计算
     * @param siteId
     * @param mainTreeId
     * @param type
     * @param x1  绝缘电阻
     * @param x2  泄漏电流
     * @param x3  阻性电流
     * @param x4  容性电流
     * @param x5  雷击次数
     * @param x6   环境温度
     * @param ω
     * @param β
     * @return
     */
    @Override
    public ArresterAssessmentResult assessmentForArrester(String siteId, String mainTreeId, String type, BigDecimal x1,BigDecimal x2,BigDecimal x3,BigDecimal x4,
                                                          BigDecimal x5,BigDecimal x6,BigDecimal ω,BigDecimal β) {
        int step = 0;
        BigDecimal x11=BigDecimal.ZERO;
        BigDecimal x21=BigDecimal.ZERO;
        BigDecimal x31=BigDecimal.ZERO;
        BigDecimal x41=BigDecimal.ZERO;
        BigDecimal x51=BigDecimal.ZERO;
        BigDecimal x61=BigDecimal.ZERO;
        net.sf.json.JSONArray jsonArray = new net.sf.json.JSONArray();
        CalculateStep calculateStep = new CalculateStep();
        calculateStep.setId(Uuid.getUUID());
        calculateStep.setSiteId(siteId);
        calculateStep.setEquipmentType(SiteConstants.BLQ);
        calculateStep.setMainEquipmentId(mainTreeId);
        calculateStep.setExecuteMode(Integer.valueOf(Constants.DEFAULT_YES));
        calculateStep.setCreateTime(LocalDateTime.now());

        com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
        // 避雷器评估结果
        ArresterAssessmentResult arresterAssessmentResult = new ArresterAssessmentResult();
        BusiParamArresterVo numberPojo = busiParamArresterMapper.findFirstLevelNumber(siteId, mainTreeId);
        if(ObjectUtils.isEmpty(numberPojo)){
            busiParamArresterService.initBusiParams("",siteId, mainTreeId);
            numberPojo = busiParamArresterMapper.findFirstLevelNumber(siteId, mainTreeId);
        }
        //x计算
        List<BusiParamArresterVo> busiParamArresterVos = busiParamArresterService.findBusiParamGisWeights(siteId, mainTreeId, numberPojo.getNumber());
        if(CollectionUtils.isEmpty(busiParamArresterVos)){
            log.info("没有初始化数据！");
            return arresterAssessmentResult;
        }
        BigDecimal temp;
        for (BusiParamArresterVo busiParamArresterVo : busiParamArresterVos) {
            switch (busiParamArresterVo.getName()) {
                case "jydz":
                    x11 = ArresterCal.clacFormulaAsc(busiParamArresterVo.getAValue().doubleValue(), busiParamArresterVo.getBValue().doubleValue(), x1.doubleValue(), busiParamArresterVo.getValue().doubleValue(), busiParamArresterVo.getIsAttend());
                    step += 1;
                    jsonObject.clear();
                    jsonObject.put("绝缘电阻 检测值", x1.setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                    jsonObject.put("绝缘电阻 a值", busiParamArresterVo.getAValue().setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                    jsonObject.put("绝缘电阻 b值", busiParamArresterVo.getBValue().setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                    jsonObject.put("绝缘电阻 人工打分", new BigDecimal(busiParamArresterVo.getCalculatedValue()).setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                    jsonObject.put("绝缘电阻 权重", busiParamArresterVo.getValue().setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                    GisAssessUtilsNew.setStep(jsonArray, step, "绝缘电阻 计算", jsonObject.toJSONString(), String.valueOf(x11.setScale(4, BigDecimal.ROUND_HALF_UP)));
                    break;
                case "xldl":
                    x21 = ArresterCal.clacFormulaDesc(busiParamArresterVo.getAValue().doubleValue(), busiParamArresterVo.getBValue().doubleValue(), x2.doubleValue(), busiParamArresterVo.getValue().doubleValue(), busiParamArresterVo.getIsAttend());
                    step += 1;
                    jsonObject.clear();
                    jsonObject.put("泄漏电流 检测值", x2.setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                    jsonObject.put("泄漏电流 a值", busiParamArresterVo.getAValue().setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                    jsonObject.put("泄漏电流 b值", busiParamArresterVo.getBValue().setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                    jsonObject.put("泄漏电流 人工打分", new BigDecimal(busiParamArresterVo.getCalculatedValue()).setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                    jsonObject.put("泄漏电流 权重", busiParamArresterVo.getValue().setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                    GisAssessUtilsNew.setStep(jsonArray, step, "泄漏电流 计算", jsonObject.toJSONString(), String.valueOf(x21.setScale(4, BigDecimal.ROUND_HALF_UP)));

                    break;
                case "zxdl":
                    x31 = ArresterCal.clacFormulaDesc(busiParamArresterVo.getAValue().doubleValue(), busiParamArresterVo.getBValue().doubleValue(), x3.doubleValue(), busiParamArresterVo.getValue().doubleValue(), busiParamArresterVo.getIsAttend());
                    step += 1;
                    jsonObject.clear();
                    jsonObject.put("阻性电流 检测值", x3.setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                    jsonObject.put("阻性电流 a值", busiParamArresterVo.getAValue().setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                    jsonObject.put("阻性电流 b值", busiParamArresterVo.getBValue().setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                    jsonObject.put("阻性电流 人工打分", new BigDecimal(busiParamArresterVo.getCalculatedValue()).setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                    jsonObject.put("阻性电流 权重", busiParamArresterVo.getValue().setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                    GisAssessUtilsNew.setStep(jsonArray, step, "阻性电流 计算", jsonObject.toJSONString(), String.valueOf(x31.setScale(4, BigDecimal.ROUND_HALF_UP)));
                    break;
                case "rxdl":
                    x41 = ArresterCal.clacFormulaDesc(busiParamArresterVo.getAValue().doubleValue(), busiParamArresterVo.getBValue().doubleValue(), x4.doubleValue(), busiParamArresterVo.getValue().doubleValue(), busiParamArresterVo.getIsAttend());
                    step += 1;
                    jsonObject.clear();
                    jsonObject.put("容性电流 检测值", x4.setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                    jsonObject.put("容性电流 a值", busiParamArresterVo.getAValue().setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                    jsonObject.put("容性电流 b值", busiParamArresterVo.getBValue().setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                    jsonObject.put("容性电流 人工打分", new BigDecimal(busiParamArresterVo.getCalculatedValue()).setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                    jsonObject.put("容性电流 权重", busiParamArresterVo.getValue().setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                    GisAssessUtilsNew.setStep(jsonArray, step, "容性电流 计算", jsonObject.toJSONString(), String.valueOf(x41.setScale(4, BigDecimal.ROUND_HALF_UP)));
                    break;
                case "ljcs":
                    x51 = ArresterCal.clacFormulaDesc(busiParamArresterVo.getAValue().doubleValue(), busiParamArresterVo.getBValue().doubleValue(), x5.doubleValue(), busiParamArresterVo.getValue().doubleValue(), busiParamArresterVo.getIsAttend());
                    step += 1;
                    jsonObject.clear();
                    jsonObject.put("雷击次数 检测值", x5.setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                    jsonObject.put("雷击次数 a值", busiParamArresterVo.getAValue().setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                    jsonObject.put("雷击次数 b值", busiParamArresterVo.getBValue().setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                    jsonObject.put("雷击次数 人工打分", new BigDecimal(busiParamArresterVo.getCalculatedValue()).setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                    jsonObject.put("雷击次数 权重", busiParamArresterVo.getValue().setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                    GisAssessUtilsNew.setStep(jsonArray, step, "雷击次数 计算", jsonObject.toJSONString(), String.valueOf(x51.setScale(4, BigDecimal.ROUND_HALF_UP)));
                    break;
                case "hjwd":
                    x61 = ArresterCal.clacFormulaDesc(busiParamArresterVo.getAValue().doubleValue(), busiParamArresterVo.getBValue().doubleValue(), x6.doubleValue(), busiParamArresterVo.getValue().doubleValue(), busiParamArresterVo.getIsAttend());
                    step += 1;
                    jsonObject.clear();
                    jsonObject.put("环境温度 检测值", x6.setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                    jsonObject.put("环境温度 a值", busiParamArresterVo.getAValue().setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                    jsonObject.put("环境温度 b值", busiParamArresterVo.getBValue().setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                    jsonObject.put("环境温度 人工打分", new BigDecimal(busiParamArresterVo.getCalculatedValue()).setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                    jsonObject.put("环境温度 权重", busiParamArresterVo.getValue().setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                    GisAssessUtilsNew.setStep(jsonArray, step, "环境温度 计算", jsonObject.toJSONString(), String.valueOf(x61.setScale(4, BigDecimal.ROUND_HALF_UP)));

                    break;
                default:
                    break;
            }
        }
            BigDecimal x = x11.add(x21).add(x31).add(x41).add(x51).add(x61);
             step += 1;
            jsonObject.clear();
            GisAssessUtilsNew.setStep(jsonArray, step, "计算安全系数 计算", jsonObject.toJSONString(), String.valueOf(x.setScale(4, BigDecimal.ROUND_HALF_UP)));
            BigDecimal w = ω;
            step += 1;
            jsonObject.clear();
            GisAssessUtilsNew.setStep(jsonArray, step, "投运时间 计算", jsonObject.toJSONString(), String.valueOf(ω.setScale(4, BigDecimal.ROUND_HALF_UP)));

            step += 1;
            jsonObject.clear();
            GisAssessUtilsNew.setStep(jsonArray, step, "计算健康指数 计算", jsonObject.toJSONString(), String.valueOf(β.setScale(4, BigDecimal.ROUND_HALF_UP)));

            if(BigDecimal.ZERO.equals(w)){
                log.error("投运时间未超一个月！");
                throw new OwlException("投运时间未超一个月！");
            }
            //故障率
            BigDecimal futureFailureRate = ArresterCal.calFutureFailureRate(x, β, w).setScale(6, BigDecimal.ROUND_HALF_UP);
            step += 1;
            jsonObject.clear();
            GisAssessUtilsNew.setStep(jsonArray, step, "设备未来故障概率 计算", jsonObject.toJSONString(), String.valueOf(futureFailureRate.setScale(4, BigDecimal.ROUND_HALF_UP)));
            arresterAssessmentResult.setSafetyFactor( x.toString());
            arresterAssessmentResult.setId(Uuid.getUUID());
            arresterAssessmentResult.setSiteId(siteId);
            arresterAssessmentResult.setMainTreeId(mainTreeId);
            arresterAssessmentResult.setFutureFailureRate(futureFailureRate.toString());
            arresterAssessmentResult.setOperationTime(w.toString());
            arresterAssessmentResult.setHealthLevel(β.toString());
            arresterAssessmentResult.setAssessTime(LocalDateTime.now());
            arresterAssessmentResult.setType(type);
            arresterAssessmentResultService.saveArresterAssessmentResult(arresterAssessmentResult);
            calculateStep.setNumber(numberPojo.getNumber().toString());
            calculateStep.setPId(arresterAssessmentResult.getId());
            calculateStep.setStepJson(jsonArray.toString());
            calculateStepService.insert(calculateStep);
            return arresterAssessmentResult;


    }
}
