package com.huatek.busi.task;

import com.huatek.busi.common.BusiConstant;
import com.huatek.busi.common.DateUtils;
import com.huatek.busi.common.SiteConstants;
import com.huatek.busi.dao.RptAretMonitorDao;
import com.huatek.busi.dao.TransformerMeteorologicalDao;
import com.huatek.busi.dto.AppendixCalDto;
import com.huatek.busi.entity.RptAretMonitor;
import com.huatek.busi.entity.TransformerMeteorological;
import com.huatek.busi.mapper.BusiParamAppendixMapper;
import com.huatek.busi.service.*;
import com.huatek.busi.service.arrester.BusiOfflineArresterBrandService;
import com.huatek.busi.service.param.BusiParamAppendixService;
import com.huatek.busi.service.transformer.BusiOfflineTransformerBrandService;
import com.huatek.busi.task.transformer.TransformerDateOnlineService;
import com.huatek.busi.util.AppendixCal;
import com.huatek.busi.util.ArresterCal;
import com.huatek.busi.util.EvaluateConstant;
import com.huatek.busi.vo.*;
import com.huatek.busi.vo.epa.*;
import com.huatek.torch.frame.exception.OwlException;
import com.huatek.torch.sql.beans.WherePrams;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.script.ScriptException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 附件评估定时任务
 */
@Slf4j
@Component("appendixAssessTask")
public class AppendixAssessTask {
    @Autowired
    private BusiSiteTreeService busiSiteTreeService;
    @Autowired
    private AppendixAssessService appendixAssessService;

    @Autowired
    private BusiOfflineTransformerBrandService busiOfflineTransformerBrandService;

    @Autowired
    private TransformerMeteorologicalDao transformerMeteorologicalDao;

    @Autowired
    private TransformerDateOnlineService transformerDateOnlineService;
    @Autowired
    private BusiParamAppendixService busiParamAppendixService;

    @Autowired
    private BusiParamAppendixMapper busiParamAppendixMapper;

    @Autowired
    private ITransformerEvaluateDataService iTransformerEvaluateDataService;
    /**
     * 附件评测任务
     *
     * @throws IOException
     * @throws ScriptException
     * @throws NoSuchMethodException
     * @throws FileNotFoundException
     * @throws Exception
     */
    public void execute() {

        String date = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.addDays(new Date(), -1));
        log.info("附件评测开始时间------------------------------------------------{} start...", date);
        String[] mainEquipments = {SiteConstants.SiteTreeEnum.BYQ_EQM.getValue()};
        List<BusiTreeNodeVo> list = busiSiteTreeService.findMainEquipmentList(mainEquipments);
        for (BusiTreeNodeVo busiTreeNodeVo : list) {
            try {
                TransformerEvaluateDataVo transformerEvaluateDataVo = iTransformerEvaluateDataService.getLastByMainTreeId(busiTreeNodeVo.getId());
                if(ObjectUtils.isEmpty(transformerEvaluateDataVo)){
                    transformerDateOnlineService.warringEvaluating(SiteConstants.FJ, BusiConstant.GzType.GZ_TYPE25,"附件评测-缺少试验数据", busiTreeNodeVo.getId(),busiTreeNodeVo.getName());
                    continue;
                }
                BusiParamAppendixVo numberPojo = busiParamAppendixMapper.findFirstLevelNumber(busiTreeNodeVo.getSiteId(), busiTreeNodeVo.getId());
                if(ObjectUtils.isEmpty(numberPojo)){
                    transformerDateOnlineService.warringEvaluating(SiteConstants.FJ, BusiConstant.GzType.GZ_TYPE25,"附件评测-未设置分析参数",busiTreeNodeVo.getId(),busiTreeNodeVo.getName());
                    continue;
                }
                BusiOfflineTransformerBrandVo busiOfflineTransformerBrandVo = busiOfflineTransformerBrandService.getBusiOfflineTransformerBrandVo(busiTreeNodeVo.getSiteId(), busiTreeNodeVo.getId());
                if(null == busiOfflineTransformerBrandVo.getEquipmentDeliveryTime()){
                    transformerDateOnlineService.warringEvaluating(SiteConstants.FJ, BusiConstant.GzType.GZ_TYPE25,"附件评测-未配置投运时间",busiTreeNodeVo.getId(),busiTreeNodeVo.getName());
                    log.error("附件评测出错【站点：{};设备Code：{}】,错误信息如下:{}", busiTreeNodeVo.getSiteId(), busiTreeNodeVo.getId(), "没有设置运行时间");
                    continue;
                }
                List<BusiParamAppendixVo> params = busiParamAppendixService.findParams(busiTreeNodeVo.getSiteId(), busiTreeNodeVo.getId());
                Map<String, BusiParamAppendixVo> threeLevelMap = this.convertParams("3", params);
                //噪声
                BusiParamAppendixVo zsParams = threeLevelMap.get("byqzs");
                if (null != zsParams && zsParams.getIsAttend().equals("1")) {
                    EpaSoundVibrationVo soundEvaluateData = transformerDateOnlineService.getSoundEvaluateData(busiTreeNodeVo.getId());
                    if (null == soundEvaluateData) {
                        log.error("--->>变压器评测-噪声在线装置未安装或未采集到数据");
                        transformerDateOnlineService.warringEvaluating(SiteConstants.FJ, BusiConstant.GzType.GZ_TYPE25,"附件评测-噪声在线装置未安装或未采集到数据", busiTreeNodeVo.getId(),busiTreeNodeVo.getName());
                        continue;
                    }
                }

                //TODO 容性设备 全电流（mA） 容性电流 阻性电流
                // 容性设备 全电流（mA） 容性电流
                BusiParamAppendixVo qParams =  threeLevelMap.get("quandianliu");
                BusiParamAppendixVo rParams =  threeLevelMap.get("drl");
                EpaCapacitanceDataVo epaCapacitanceDataVo = null ;
                if ((null != qParams && qParams.getIsAttend().equals("1"))
                        || (null != rParams && rParams.getIsAttend().equals("1"))) {
                    epaCapacitanceDataVo = transformerDateOnlineService.getCapacitanceEvaluateData(busiTreeNodeVo.getId());
                    if (null == epaCapacitanceDataVo) {
                        log.error("--->>附件评测-绝缘介质在线数据");
                        transformerDateOnlineService.warringEvaluating(SiteConstants.FJ, BusiConstant.GzType.GZ_TYPE25, "附件评测-绝缘介质装置未安装或未采集到数据", busiTreeNodeVo.getId(),busiTreeNodeVo.getName());
                        continue;
                    }
                }
                //电容量
                //红外温度在线数据
                BusiParamAppendixVo hwParams = threeLevelMap.get("hwwd");
                if (null != hwParams && hwParams.getIsAttend().equals("1")) {
                    EpaInfraredMonitorDataVo epaInfraredMonitorDataVo = transformerDateOnlineService.getInfraredMonitorEvaluateData(busiTreeNodeVo.getId());
                    if (null == epaInfraredMonitorDataVo) {
                        log.error("--->>变压器评测-红外温度在线数据在线数据");
                        transformerDateOnlineService.warringEvaluating(SiteConstants.FJ, BusiConstant.GzType.GZ_TYPE25,"附件评测-红外温度装置未安装或未采集到数据", busiTreeNodeVo.getId(),busiTreeNodeVo.getName());
                        continue;
                    }
                }

                // 104-运行工况 水温
                BusiParamAppendixVo swParams = threeLevelMap.get("sw");
                if (null != swParams && swParams.getIsAttend().equals("1")) {
                    EpaRunStatusDataVo runStatusEvaluateData = transformerDateOnlineService.getRunStatusEvaluateData(busiTreeNodeVo.getId());
                    if (null == runStatusEvaluateData) {
                        log.error("--->>变压器评测-104运行工况水温在线数据为空");
                        transformerDateOnlineService.warringEvaluating(SiteConstants.FJ, BusiConstant.GzType.GZ_TYPE25,"附件评测-104运行工况水温在线数据为空", busiTreeNodeVo.getId(),busiTreeNodeVo.getName());
                        continue;
                    }
                }
                // 104-运行工况 水压
                BusiParamAppendixVo syParams = threeLevelMap.get("sy");
                if (null != syParams && syParams.getIsAttend().equals("1")) {
                    EpaRunStatusDataVo runStatusEvaluateData = transformerDateOnlineService.getRunStatusEvaluateData(busiTreeNodeVo.getId());
                    if (null == runStatusEvaluateData) {
                        log.error("--->>变压器评测-104运行工况水压在线数据为空");
                        transformerDateOnlineService.warringEvaluating(SiteConstants.FJ, BusiConstant.GzType.GZ_TYPE25,"附件评测-104运行工况水压在线数据为空", busiTreeNodeVo.getId(),busiTreeNodeVo.getName());
                        continue;
                    }
                }
                //环境温度在线数据
                BusiParamAppendixVo hjParams = threeLevelMap.get("hjwd");
                if (null != hjParams && hjParams.getIsAttend().equals("1")) {
                    EpaEnvironmentDataVo epaEnvironmentDataVo  = transformerDateOnlineService.getEnvironmentEvaluateData(busiTreeNodeVo.getId());
                    if (null == epaEnvironmentDataVo) {
                        log.error("--->>变压器评测-红外温度在线数据在线数据");
                        transformerDateOnlineService.warringEvaluating(SiteConstants.FJ, BusiConstant.GzType.GZ_TYPE25,"附件评测-环境温度在线数据为空", busiTreeNodeVo.getId(),busiTreeNodeVo.getName());
                        continue;
                    }
                }

                BigDecimal w = AppendixCal.calW(busiOfflineTransformerBrandVo.getEquipmentDeliveryTime());
                BigDecimal β = AppendixCal.calHi1(busiOfflineTransformerBrandVo.getEquipmentDeliveryTime());
                AppendixCalDto appendixCalDto = new AppendixCalDto();
                appendixCalDto.setMainTreeId( busiTreeNodeVo.getId());
                appendixCalDto.setSiteId(busiTreeNodeVo.getSiteId());
                appendixCalDto.setΒ(β);
                appendixCalDto.setΩ(w);
                BigDecimal β1 = AppendixCal.calHi11(busiOfflineTransformerBrandVo.getEquipmentDeliveryTime(),busiOfflineTransformerBrandVo.getDesignLife());
                appendixCalDto.setΒ1(β1);
                appendixAssessService.assessmentForAppendix(appendixCalDto, "2",busiTreeNodeVo.getName(),transformerEvaluateDataVo);

            } catch (Exception e) {
                log.error("附件评测出错【站点：{};设备Code：{}】,错误信息如下:{}", busiTreeNodeVo.getSiteId(), busiTreeNodeVo.getId(), e.getMessage());
                log.error(e.getMessage(), e);
            }
        }
        log.info("{} end!", date);
    }

    public Map<String, BusiParamAppendixVo> convertParams(String level, List<BusiParamAppendixVo> list) {
        List<BusiParamAppendixVo> convertorlist = null;
        convertorlist = list.stream().filter(vo -> vo.getWeightLevel().equalsIgnoreCase(level)).collect(Collectors.toList());
        Map<String, BusiParamAppendixVo> map = convertorlist.stream().collect(Collectors.toMap(BusiParamAppendixVo::getName, Function.identity()));
        return map;
    }
}
