package com.njcn.harmonic.service.impl;

import com.njcn.device.pms.api.MonitorClient;
import com.njcn.device.pms.api.StatationStatClient;
import com.njcn.device.pms.pojo.dto.PmsMonitorDTO;
import com.njcn.device.pms.pojo.dto.PmsStatationStatInfoDTO;
import com.njcn.device.pms.pojo.param.PmsMonitorParam;
import com.njcn.device.pms.pojo.param.PmsStatationStatInfoParam;
import com.njcn.device.biz.pojo.po.Overlimit;
import com.njcn.harmonic.pojo.param.RMpHarmonicReportDParam;
import com.njcn.harmonic.pojo.po.*;
import com.njcn.harmonic.pojo.vo.RMpHarmonicReportDVO;
import com.njcn.harmonic.service.*;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.enums.DicDataTypeEnum;
import com.njcn.system.pojo.po.DictData;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Title RMpHarmonicReportDServiceImpl
 * @Package com.njcn.harmonic.service.impl
 * @Author jianghaifei
 * @Date 2022-10-20 19:19
 * @Version V1.0
 */
@Service
@RequiredArgsConstructor
public class RMpHarmonicReportDServiceImpl implements RMpHarmonicReportDService {

    private final MonitorClient monitorClient; //监测点服务

    private final DicDataFeignClient dicDataFeignClient; //字典服务

    private final StatationStatClient statationStatClient; //变电站服务

    private final RMpMeasureReportDService rMpMeasureReportDService; //【稳态监测点非谐波不带相位指标日报-日表(主配网表)】

    private final RMpMeasurePhaseReportDService  rMpMeasurePhaseReportDService; //【稳态监测点非谐波带相位指标日报-日表(主配网表)】

    //r_mp_harmonic_v_rate_report_d
    private final RMpHarmonicVRateReportDService rMpHarmonicVRateReportDService; //【稳态监测点指标日报-日表(主配网表)  /各次谐波电压含有率】

    //r_mp_harmonic_i_mag_report_d
    private final RMpHarmonicIMagReportDService rMpHarmonicIMagReportDService; //【各相各次谐波电流有效值】

    //r_mp_harmonic_i_rate_report_d
    private final RMpHarmonicIRateReportDService rMpHarmonicIRateReportDService; //【各相各次谐波电流含有率】

    //r_mp_inharmonic_v_rate_report_d
    private final RMpInharmonicVRateReportDService rMpInharmonicVRateReportDService; //【各相各次间谐波电压含有率】

    //r_mp_inharmonic_i_rate_report_d
    private final RMpInharmonicIRateReportDService rMpInharmonicIRateReportDService; //【各相各次间谐波电流含有率】

    @Override
    public List<RMpHarmonicReportDVO> getMonitorStatisticsD(RMpHarmonicReportDParam rMpHarmonicReportDParam) {
//
//        Overlimit data = lineFeignClient.getOverLimitData("064b948a81090b80860483994f2a8e75").getData();
//        System.out.println(data);
        //提取查询参数
//        String monitorName = rMpHarmonicReportDParam.getMonitorName(); //监测点名称
        String startTime = rMpHarmonicReportDParam.getStartTime();
        String endTime = rMpHarmonicReportDParam.getEndTime();
        String monitorId = rMpHarmonicReportDParam.getMonitorId(); //监测点id
        List<String> monitorIds = StringUtils.isNotBlank(monitorId) ? Arrays.asList(monitorId.split(",")) : null;
        //获取所有的条件筛选后的监测点信息
        PmsMonitorParam pmsMonitorParam = new PmsMonitorParam();
//        pmsMonitorParam.setMonitorName(monitorName); //监测点名称(模糊查询)
        pmsMonitorParam.setMonitorIds(monitorIds); //监测点id集合
        List<PmsMonitorDTO> monitors = monitorClient.getMonitorInfoListByCond(pmsMonitorParam).getData();

        //提取出监测点的id集合
        List<String> monitorIdList = monitors.stream().map(PmsMonitorDTO::getId).collect(Collectors.toList());
        //提取出变电站id集合
        List<String> stationIdList = monitors.stream().map(PmsMonitorDTO::getPowerrId).collect(Collectors.toList());
        PmsStatationStatInfoParam stationParam = new PmsStatationStatInfoParam();
        stationParam.setPowerIds(stationIdList);
        List<PmsStatationStatInfoDTO> stationList = statationStatClient.getStatationStatInfo(stationParam).getData();
        Map<String, PmsStatationStatInfoDTO> stationMap = stationList.stream().collect(Collectors.toMap(PmsStatationStatInfoDTO::getPowerId, dto -> dto));

        //获取电压等级的字典
        List<DictData> voltageLevelList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.DEV_VOLTAGE.getCode()).getData();
        //将电压信息转成map，key：id  value：name
        Map<String, String> voltageLevelMap = voltageLevelList.stream().collect(Collectors.toMap(DictData::getId, DictData::getName));

        //获取监测点的各相限值（不出意外的情况下前端只会传1个ID，这里防止有多个ID所以服务里都是用的id集合）
        List<Overlimit> overlimitList = new ArrayList<>();
        for (String id : monitorIdList) {
            Overlimit overlimit = monitorClient.getOverLimitData(id).getData();
            overlimitList.add(overlimit);
        }
        Map<String, Overlimit> overLimitMap = overlimitList.stream().collect(Collectors.toMap(Overlimit::getId, o -> o));

        /************查询每个检测点的日统计信息**************/
        //设置查询条件(通用于以下几张表的查询)
        HashMap<String, Object> condMap = new HashMap<>();
        condMap.put("startTime", startTime);
        condMap.put("endTime", endTime);
        condMap.put("monitorIdList", monitorIdList);
        //1.r_mp_measure_report_d【稳态监测点非谐波不带相位指标日报-日表(主配网表)】
//        LambdaQueryWrapper<RMpMeasureReportD> rMpMeasureReportDWrapper = new LambdaQueryWrapper<>();
//        rMpMeasureReportDWrapper.in(RMpMeasureReportD::getMeasurementPointId, monitorIdList)
//                .ge(RMpMeasureReportD::getDataDate, startTime).le(RMpMeasureReportD::getDataDate, endTime);
        List<RMpMeasureReportD> RMpMeasureReportDList = rMpMeasureReportDService.getListByCond(condMap);
        //1.1转成map，key：监测点id  value：实体
        Map<String, RMpMeasureReportD> RMpMeasureReportDMap = RMpMeasureReportDList.stream().collect(Collectors.toMap(RMpMeasureReportD::getMeasurementPointId, entity -> entity));

        //2.r_mp_measure_phase_report_d【稳态监测点非谐波带相位指标日报-日表(主配网表)】
//        LambdaQueryWrapper<RMpMeasurePhaseReportD> rMpMeasurePhaseReportDWrapper = new LambdaQueryWrapper<>();
//        rMpMeasurePhaseReportDWrapper.in(RMpMeasurePhaseReportD::getMeasurementPointId, monitorIdList)
//                .ge(RMpMeasurePhaseReportD::getDataDate, startTime).le(RMpMeasurePhaseReportD::getDataDate, endTime);
        List<RMpMeasurePhaseReportD> RMpMeasurePhaseReportDList = rMpMeasurePhaseReportDService.getListByCond(condMap);

        //3.r_mp_harmonic_v_rate_report_d【稳态监测点指标日报-日表(主配网表)  /各次谐波电压含有率】
//        LambdaQueryWrapper<RMpHarmonicVRateReportD> rMpHarmonicVRateReportWrapper = new LambdaQueryWrapper<>();
//        rMpHarmonicVRateReportWrapper.in(RMpHarmonicVRateReportD::getMeasurementPointId, monitorIdList)
//                .ge(RMpHarmonicVRateReportD::getDataDate, startTime).le(RMpHarmonicVRateReportD::getDataDate, endTime);

        List<RMpHarmonicVRateReportD> rMpHarmonicVRateReportDList = rMpHarmonicVRateReportDService.getListByCond(condMap);

        //4.r_mp_harmonic_i_mag_report_d【各相各次谐波电流有效值】
//        LambdaQueryWrapper<RMpHarmonicIMagReportD> rMpHarmonicIMagReportDWrapper = new LambdaQueryWrapper<>();
//        rMpHarmonicIMagReportDWrapper.in(RMpHarmonicIMagReportD::getMeasurementPointId, monitorIdList)
//                .ge(RMpHarmonicIMagReportD::getDataDate, startTime).le(RMpHarmonicIMagReportD::getDataDate, endTime);
        List<RMpHarmonicIMagReportD> rMpHarmonicIMagReportDList = rMpHarmonicIMagReportDService.getListByCond(condMap);

        //5.r_mp_harmonic_i_rate_report_d【各相各次谐波电流含有率】
//        LambdaQueryWrapper<RMpHarmonicIRateReportD> rMpHarmonicIRateReportDWrapper = new LambdaQueryWrapper<>();
//        rMpHarmonicIRateReportDWrapper.in(RMpHarmonicIRateReportD::getMeasurementPointId, monitorIdList)
//                .ge(RMpHarmonicIRateReportD::getDataDate, startTime).le(RMpHarmonicIRateReportD::getDataDate, endTime);
        List<RMpHarmonicIRateReportD> rMpHarmonicIRateReportDList = rMpHarmonicIRateReportDService.getListByCond(condMap);

        //6.r_mp_inharmonic_v_rate_report_d【各相各次间谐波电压含有率】
//        LambdaQueryWrapper<RMpInharmonicVRateReportD> rMpInharmonicVRateReportDWrapper = new LambdaQueryWrapper<>();
//        rMpInharmonicVRateReportDWrapper.in(RMpInharmonicVRateReportD::getMeasurementPointId, monitorIdList)
//                .ge(RMpInharmonicVRateReportD::getDataDate, startTime).le(RMpInharmonicVRateReportD::getDataDate, endTime);
        List<RMpInharmonicVRateReportD> rMpInharmonicVRateReportDList = rMpInharmonicVRateReportDService.getListByCond(condMap);

        //7.r_mp_inharmonic_i_rate_report_d【各相各次间谐波电流含有率】
//        LambdaQueryWrapper<RMpInharmonicIRateReportD> rMpInharmonicIRateReportDWrapper = new LambdaQueryWrapper<>();
//        rMpInharmonicIRateReportDWrapper.in(RMpInharmonicIRateReportD::getMeasurementPointId, monitorIdList)
//                .ge(RMpInharmonicIRateReportD::getDataDate, startTime).le(RMpInharmonicIRateReportD::getDataDate, endTime);
        List<RMpInharmonicIRateReportD> rMpInharmonicIRateReportDList = rMpInharmonicIRateReportDService.getListByCond(condMap);

        /*************整理返回数据**************/
        List<RMpHarmonicReportDVO> RMpHarmonicReportDVOList = monitors.stream().map(item -> {
            RMpHarmonicReportDVO rMpHarmonicReportDVO = new RMpHarmonicReportDVO();
            rMpHarmonicReportDVO.setOrgNo(item.getOrgId()); //单位id
            rMpHarmonicReportDVO.setOrgName(item.getOrgName()); //单位名称
            rMpHarmonicReportDVO.setPowerId(item.getPowerrId()); //变电站id
            rMpHarmonicReportDVO.setPowerName(item.getPowerrName()); //变电站名称
            rMpHarmonicReportDVO.setMeasurementPointId(item.getId()); //监测点ID
            rMpHarmonicReportDVO.setMeasurementPointName(item.getName()); //监测点名称
            rMpHarmonicReportDVO.setMinShortCircuitCapacity(item.getMinShortCircuitCapacity()); //最小短路容量
            rMpHarmonicReportDVO.setVoltageLevel(stationMap.get(item.getPowerrId()).getPowerVoltageLevel()); //变电站电压等级id
            rMpHarmonicReportDVO.setVoltageLevelName(voltageLevelMap.get(stationMap.get(item.getPowerrId()).getPowerVoltageLevel()));//变电站电压等级
            rMpHarmonicReportDVO.setDataDate(startTime); //监测日期
            /****r_mp_measure_report_d数据****/
            rMpHarmonicReportDVO.setRMpMeasureReportD(RMpMeasureReportDMap.get(item.getId()));
//            //总有功功率
//            rMpHarmonicReportDVO.setTotalActivePowerMax(RMpMeasureReportDMap.get(item.getId()).getTotalActivePowerMax());
//            rMpHarmonicReportDVO.setTotalActivePowerMin(RMpMeasureReportDMap.get(item.getId()).getTotalActivePowerMin());
//            rMpHarmonicReportDVO.setTotalActivePowerAvg(RMpMeasureReportDMap.get(item.getId()).getTotalActivePowerAvg());
//            rMpHarmonicReportDVO.setTotalActivePower95(RMpMeasureReportDMap.get(item.getId()).getTotalActivePower95());
            Double frequencyDeviationMax = RMpMeasureReportDMap.get(item.getId()).getFrequencyDeviationMax(); //频率偏差-最大值
            Double freqDev = Double.parseDouble(String.valueOf(overLimitMap.get(item.getId()).getFreqDev())); //频率偏差限值
            rMpHarmonicReportDVO.setFrequencyDeviationMaxResult((frequencyDeviationMax > freqDev) ? "越限" : "正常"); // 频率偏差-最大值限值结论
//            //总无功功率
//            rMpHarmonicReportDVO.setTotalReactivePowerMax(RMpMeasureReportDMap.get(item.getId()).getTotalReactivePowerMax());
//            rMpHarmonicReportDVO.setTotalReactivePowerMin(RMpMeasureReportDMap.get(item.getId()).getTotalReactivePowerMin());
//            rMpHarmonicReportDVO.setTotalReactivePowerAvg(RMpMeasureReportDMap.get(item.getId()).getTotalReactivePowerAvg());
//            rMpHarmonicReportDVO.setTotalReactivePower95(RMpMeasureReportDMap.get(item.getId()).getTotalReactivePower95());
//            //负序电压（三相电压）不平衡度
//            rMpHarmonicReportDVO.setNegativeSequenceVoltageUnbalanceMax(RMpMeasureReportDMap.get(item.getId()).getNegativeSequenceVoltageUnbalanceMax());
//            rMpHarmonicReportDVO.setNegativeSequenceVoltageUnbalanceMin(RMpMeasureReportDMap.get(item.getId()).getNegativeSequenceVoltageUnbalanceMin());
//            rMpHarmonicReportDVO.setNegativeSequenceVoltageUnbalanceAvg(RMpMeasureReportDMap.get(item.getId()).getNegativeSequenceVoltageUnbalanceAvg());
//            rMpHarmonicReportDVO.setNegativeSequenceVoltageUnbalance95(RMpMeasureReportDMap.get(item.getId()).getNegativeSequenceVoltageUnbalance95());
            Double unb = Double.parseDouble(String.valueOf(overLimitMap.get(item.getId()).getUbalance())); //限值
            Double unbalance95 = RMpMeasureReportDMap.get(item.getId()).getNegativeSequenceVoltageUnbalance95(); //负序电压不平衡度95值
            rMpHarmonicReportDVO.setNegativeSequenceVoltageUnbalance95Result((unbalance95 > unb) ? "越限" : "正常"); //负序电压（三相电压）不平衡度-95值限值结论
            Double unbalanceMax = RMpMeasureReportDMap.get(item.getId()).getNegativeSequenceVoltageUnbalanceMax();//负序电压不平衡度最大值
            rMpHarmonicReportDVO.setNegativeSequenceVoltageUnbalanceMaxResult((unbalanceMax > unb) ? "越限" : "正常"); //负序电压（三相电压）不平衡度-95值限值结论

//            //负序电流
//            rMpHarmonicReportDVO.setNegativeSequenceCurrentMax(RMpMeasureReportDMap.get(item.getId()).getNegativeSequenceCurrentMax());
//            rMpHarmonicReportDVO.setNegativeSequenceCurrentMin(RMpMeasureReportDMap.get(item.getId()).getNegativeSequenceCurrentMin());
//            rMpHarmonicReportDVO.setNegativeSequenceCurrentAvg(RMpMeasureReportDMap.get(item.getId()).getNegativeSequenceCurrentAvg());
//            rMpHarmonicReportDVO.setNegativeSequenceCurrent95(RMpMeasureReportDMap.get(item.getId()).getNegativeSequenceCurrent95());
            Double iNeg = Double.parseDouble(String.valueOf(overLimitMap.get(item.getId()).getINeg()));//负序电流限值
            Double current95 = RMpMeasureReportDMap.get(item.getId()).getNegativeSequenceCurrent95(); //负序电流95值
            rMpHarmonicReportDVO.setNegativeSequenceCurrent95Result((current95 > iNeg) ? "越限" : "正常"); //负序电流-95值限值结论
            Double currentMax = RMpMeasureReportDMap.get(item.getId()).getNegativeSequenceCurrentMax(); //负序电流值
            rMpHarmonicReportDVO.setNegativeSequenceCurrentMaxResult((currentMax > iNeg) ? "越限" : "正常"); //负序电流最大值限值结论


            /**********三相数据**********/
            //r_mp_measure_phase_report_d
            Map<String, RMpMeasurePhaseReportD> phaseReportDMap = RMpMeasurePhaseReportDList.stream().filter(phaseReportD -> phaseReportD.getMeasurementPointId().equals(item.getId()))
                    .collect(Collectors.toMap(RMpMeasurePhaseReportD::getPhase, phaseReportD -> phaseReportD));
            rMpHarmonicReportDVO.setPhaseReportD(phaseReportDMap);

            //r_mp_harmonic_v_rate_report_d
            Map<String, RMpHarmonicVRateReportD> vRateReportDMap = rMpHarmonicVRateReportDList.stream().filter(reportD -> reportD.getMeasurementPointId().equals(item.getId()))
                    .collect(Collectors.toMap(RMpHarmonicVRateReportD::getPhase, reportD -> reportD));
            rMpHarmonicReportDVO.setRMpHarmonicVRateReportDMap(vRateReportDMap);
            //电压总谐波畸变率-95限值结论
            Double uaberrance = Double.parseDouble(String.valueOf(overLimitMap.get(item.getId()).getUaberrance()));//电压总谐波畸变率限值
            Map<String, String> wave95ResultMap = rMpHarmonicVRateReportDList.stream().filter(reportD -> reportD.getMeasurementPointId().equals(item.getId()))
                    .collect(Collectors.toMap(RMpHarmonicVRateReportD::getPhase, reportD -> reportD.getVoltageHarmonicThd95() > uaberrance ? "越限" : "正常"));
            rMpHarmonicReportDVO.setVoltageHarmonicWave95ResultMap(wave95ResultMap);

            //r_mp_harmonic_i_mag_report_d
            Map<String, RMpHarmonicIMagReportD> iMagReportDMap = rMpHarmonicIMagReportDList.stream().filter(reportD -> reportD.getMeasurementPointId().equals(item.getId()))
                    .collect(Collectors.toMap(RMpHarmonicIMagReportD::getPhase, reportD -> reportD));
            rMpHarmonicReportDVO.setRMpHarmonicIMagReportDMap(iMagReportDMap);

            //r_mp_harmonic_i_rate_report_d
            Map<String, RMpHarmonicIRateReportD> iRateReportDMap = rMpHarmonicIRateReportDList.stream().filter(reportD -> reportD.getMeasurementPointId().equals(item.getId()))
                    .collect(Collectors.toMap(RMpHarmonicIRateReportD::getPhase, reportD -> reportD));
            rMpHarmonicReportDVO.setRMpHarmonicIRateReportDMap(iRateReportDMap);

            //r_mp_inharmonic_v_rate_report_d
            Map<String, RMpInharmonicVRateReportD> rMpInharmonicVRateReportD = rMpInharmonicVRateReportDList.stream().filter(reportD -> reportD.getMeasurementPointId().equals(item.getId()))
                    .collect(Collectors.toMap(RMpInharmonicVRateReportD::getPhase, reportD -> reportD));
            rMpHarmonicReportDVO.setRMpInharmonicVRateReportDMap(rMpInharmonicVRateReportD);

            //r_mp_inharmonic_i_rate_report_d
            Map<String, RMpInharmonicIRateReportD> rMpInharmonicIRateReportD = rMpInharmonicIRateReportDList.stream().filter(reportD -> reportD.getMeasurementPointId().equals(item.getId()))
                    .collect(Collectors.toMap(RMpInharmonicIRateReportD::getPhase, reportD -> reportD));
            rMpHarmonicReportDVO.setRMpInharmonicIRateReportDMap(rMpInharmonicIRateReportD);

            return rMpHarmonicReportDVO;
        }).collect(Collectors.toList());
        return RMpHarmonicReportDVOList;
    }
}
