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

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.huatek.busi.common.SiteConstants;
import com.huatek.busi.entity.*;
import com.huatek.busi.service.ICalculateStepService;
import com.huatek.busi.service.ILabReportMarkStatisticService;
import com.huatek.busi.service.IecBreakerParamService;
import com.huatek.busi.service.gis.*;
import com.huatek.busi.service.impl.gis.gisAssessment.*;
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.util.uuid.Uuid;
import lombok.extern.slf4j.Slf4j;
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 java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

    @Reference(check = false)
    ICalculateStepService calculateStepService;

    @Autowired
    private BusiParamGisService busiParamGisService;

    @Autowired
    private GisMechanicalPropertiesService gisMechanicalPropertiesService;

    @Autowired
    private BusiOfflineGisBrandService busiOfflineGisBrandService;

    @Autowired
    private BusiOfflineGisRepairService busiOfflineGisRepairService;

    @Autowired
    private IecBreakerParamService iecBreakerParamService;

    @Autowired
    private SubstationMicGisService substationMicGisService;

    @Autowired
    private RptGisMonitorSf6ChartsService rptGisMonitorSf6ChartsService;

    @Autowired
    private TransformerPdStatisticsService transformerPdStatisticsService;

    @Autowired
    private GisAssessmentResultService gisAssessmentResultService;

    @Autowired
    private GisAssessmentResultDataService gisAssessmentResultDataService;


    @Reference(check = false)
    ILabReportMarkStatisticService labReportMarkStatisticService;

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

    public static GisFormulaCal gisFormulaCalInstance = GisFormulaCal.getInstance();

    @Override
    public GisAssessmentResult assessmentByGis(String siteId, String mainTreeId) {

        // Gis评估结果
        GisAssessmentResult gisAssessmentResult = new GisAssessmentResult();

        // 通过systemCode查找 GIS标牌信息
        BusiOfflineGisBrandVo busiOfflineGisBrandVo = busiOfflineGisBrandService.findBusiOfflineGISBrand(siteId, mainTreeId);
        if (busiOfflineGisBrandVo != null) {
            String gisId = busiOfflineGisBrandVo.getId();
            String gisName = busiOfflineGisBrandVo.getGisName();
            // 组织文件名
            DateTimeFormatter dateTimeFormater2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate localDate = LocalDate.now();
            String date = dateTimeFormater2.format(localDate);
            String fileName = gisName + "_" + date + ".xml";
            log.info("--->> GIS名称：{}, id：{}", gisName, gisId);

            // 获取Gis的权重系数维护表
            Map<String, BusiParamTransformerVo> busiParamGisMap = new HashMap<>();
            String number = null;
            List<BusiParamTransformerVo> busiParamGisVo = busiParamGisService.findBusiParamGisManual(siteId, mainTreeId);
            if (!busiParamGisVo.isEmpty()) {
                busiParamGisMap = GisAssessUtilsNew.busiParamGisList2Map(busiParamGisVo);
                number = busiParamGisVo.get(0).getNumber().toString();
            }

            // 根据主设备编号查询打标信息数据表
//                List<LabReportMarkStatistic> labReportMarkStatisticList = labReportMarkStatisticService.findMainTreeId(mainTreeId);
            List<LabReportMarkStatistic> labReportMarkStatisticList = labReportMarkStatisticService.findAllManualAssessmentData(mainTreeId);
            if (CollectionUtil.isNotEmpty(labReportMarkStatisticList)) {
                int step = 0;

                CalculateStep calculateStep = new CalculateStep();
                calculateStep.setId(Uuid.getUUID());
                calculateStep.setSiteId(siteId);
                calculateStep.setEquipmentType(SiteConstants.GIS);
                calculateStep.setMainEquipmentId(mainTreeId);
                calculateStep.setExecuteMode(Integer.valueOf(Constants.DEFAULT_NO));
                calculateStep.setCreateTime(LocalDateTime.now());
                calculateStep.setNumber(number);
                Map<String, String> gisDataMap = GisAssessmentCalculate.getAllData(labReportMarkStatisticList);

                /*************************************开断磨损计算**************************************/
                Map<String, String> kdmsResult = GisKDMSCalculate.calculateManualKDMS(busiParamGisMap, busiOfflineGisBrandVo, gisDataMap, step);
                step = Integer.parseInt(kdmsResult.get("step"));

                /*************************************运行数据计算**************************************/
                Map<String, String> yxsjResult = GisYXSJCalculate.calculateManualYXSJ(busiParamGisMap, gisDataMap, step);
                step = Integer.parseInt(yxsjResult.get("step"));

                /*************************************运行数据-电气试验计算**************************************/
                Map<String, String> yxsjdqsyResult = GisYXSJDQSYCalculate.calculateYXSJDQSY(busiParamGisMap, gisDataMap, step, "1");
                step = Integer.parseInt(yxsjdqsyResult.get("step"));

                /*************************************绝缘介质-SF6在线数据计算**************************************/
                Map<String, String> sf6Result = GisSf6Calculate.calculateManualSf6(busiParamGisMap, gisDataMap, step);
                step = Integer.parseInt(sf6Result.get("step"));

                /*************************************运行参数计算**************************************/
                Map<String, String> yxcsResult = GisYXCSCalculate.calculateManualYXCS(busiParamGisMap, gisDataMap, busiOfflineGisBrandVo, step);
                step = Integer.parseInt(yxcsResult.get("step"));

                String score = "100";
                if (busiParamGisVo.size() > 11) {
                    score = Math.round(Double.parseDouble(new BigDecimal(kdmsResult.get(GisCreateUtil.BREAKING_WEAR)).add(new BigDecimal(yxsjResult.get(GisCreateUtil.OPERATIONAL_DATA)))
                            .add(new BigDecimal(yxsjdqsyResult.get(GisCreateUtil.OPERATION_PARAMETERS_DQSY))).add(new BigDecimal(sf6Result.get(GisCreateUtil.INSULATING_MEDIUM)))
                            .add(new BigDecimal(yxcsResult.get(GisCreateUtil.OPERATION_PARAMETERS))).multiply(BigDecimal.valueOf(100)).setScale(4, RoundingMode.HALF_UP) + "")) + "";
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("开断磨损", new BigDecimal(kdmsResult.get(GisCreateUtil.BREAKING_WEAR)).setScale(4, RoundingMode.HALF_UP).toString());
                    jsonObject.put("运行数据", new BigDecimal(yxsjResult.get(GisCreateUtil.OPERATIONAL_DATA)).setScale(4, RoundingMode.HALF_UP).toString());
                    jsonObject.put("运行数据-电气试验", new BigDecimal(yxsjdqsyResult.get(GisCreateUtil.OPERATION_PARAMETERS_DQSY)).setScale(4, RoundingMode.HALF_UP).toString());
                    jsonObject.put("绝缘介质-SF6在线数据", new BigDecimal(sf6Result.get(GisCreateUtil.INSULATING_MEDIUM)).setScale(4, RoundingMode.HALF_UP).toString());
                    jsonObject.put("运行参数", new BigDecimal(yxcsResult.get(GisCreateUtil.OPERATION_PARAMETERS)).setScale(4, RoundingMode.HALF_UP).toString());

                    // step 18 结果
                    step += 1;
                    EvaluationNameUtil.setSpecialStep(step, null, score + "%", jsonObject, "最终结果");
                    log.info("score::" + score);
                }

                Map<String, String> healthResult = GisAssessmentCalculate.formHealthResult(Convert.str2BigDecimal(score));

                String uuid = Uuid.getUUID();
                // 14-累计断开次数
                String sydkcs = new BigDecimal("14").subtract(new BigDecimal(kdmsResult.get(GisCreateUtil.CUMULATIVE_ACTION_TIMES))).toString();
                log.info("预期剩余断开次数：" + sydkcs);
                log.info("健康水平：" + healthResult.get("gisStatus"));
                log.info("检修建议：" + healthResult.get("jxjy"));
                log.info("健康水平说明：" + healthResult.get("healthLevelExplain"));
                gisAssessmentResult = GisAssessmentCalculate.formGisAssessmentResult(uuid, siteId, mainTreeId, score, healthResult.get("gisStatus"), healthResult.get("healthLevelExplain"), kdmsResult, busiOfflineGisBrandVo, sydkcs, healthResult.get("jxjy"),"1");
                gisAssessmentResultService.saveGisAssessmentResult(gisAssessmentResult);

                GisAssessmentResultData result = GisAssessmentCalculate.formResult(kdmsResult, yxsjResult, sf6Result, yxcsResult, uuid, gisId, gisName, score, healthResult.get("gisStatus"), sydkcs, healthResult.get("jxjy"));
                gisAssessmentResultDataService.save(result);

                // 临时注释，调测后放开
                GisCreateUtil.createFile(result, true, basePath2, GisCreateUtil.FILE_PATH, fileName, date);

                // 新增算法步骤
                calculateStep.setStepJson(EvaluationNameUtil.listToJson());
                calculateStep.setPId(uuid);
                calculateStepService.insert(calculateStep);
                EvaluationNameUtil.cleanList();
            }
        }
        return gisAssessmentResult;
    }
}
