package com.njcn.prepare.harmonic.service.mysql.send.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.device.pms.api.MonitorClient;
import com.njcn.device.pms.api.StatationStatClient;
import com.njcn.device.pms.pojo.param.PmsBaseParam;
import com.njcn.device.pms.pojo.po.Monitor;
import com.njcn.device.pms.pojo.po.StatationStat;
import com.njcn.harmonic.pojo.po.day.RStatDataVDPO;
import com.njcn.harmonic.pojo.po.send.ConverterDetailStatisticsPO;
import com.njcn.prepare.harmonic.mapper.mysql.send.ConverterDetailStatisticsPOMapper;
import com.njcn.prepare.harmonic.pojo.bo.CalculatedParam;
import com.njcn.prepare.harmonic.pojo.mysql.ROperatingMonitorDPO;
import com.njcn.prepare.harmonic.pojo.po.RStatSubstationMPO;
import com.njcn.prepare.harmonic.service.mysql.day.IRStatDataVDService;
import com.njcn.prepare.harmonic.service.mysql.line.ROperatingMonitorService;
import com.njcn.prepare.harmonic.service.mysql.newalgorithm.RStatSubstationMPOService;
import com.njcn.prepare.harmonic.service.mysql.send.ConverterDetailStatisticsPOService;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.system.enums.DicDataTypeEnum;
import com.njcn.system.pojo.po.DictData;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.user.pojo.vo.PvTerminalTreeVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 
 * Description:
 * Date: 2023/12/7  16:21【需求编号】
 *
 * @author clam
 * @version V1.0.0
 */
@Service
@RequiredArgsConstructor
public class ConverterDetailStatisticsPOServiceImpl extends ServiceImpl<ConverterDetailStatisticsPOMapper, ConverterDetailStatisticsPO> implements ConverterDetailStatisticsPOService {

    private final MonitorClient monitorClient;
    private final DeptFeignClient deptFeignClient;
    private final StatationStatClient statationStatClient;
//    private final PmsGeneratrixClient pmsGeneratrixClient;
    private final DicDataFeignClient dicDataFeignClient;
    private final ROperatingMonitorService rOperatingMonitorService;

    private final IRStatDataVDService IRStatDataVDService;
    private final RStatSubstationMPOService rStatSubstationMPOService;
    @Override
    public void handleDay(CalculatedParam<String> calculatedParam) {


        List<ConverterDetailStatisticsPO> converterDetailStatisticsPOList = new ArrayList<>();
        List<Monitor> monitorList = monitorClient.getMonitorList(new ArrayList<>()).getData();
//        List<GeneratrixAndPowerStationDTO> pmsGeneratrixDTOList = pmsGeneratrixClient.getGeneratrixAndPowerStationInfo(new PmsGeneratrixParam()).getData();
        List<StatationStat> stationList = statationStatClient.getstatationStatList(new PmsBaseParam()).getData();
        List<PvTerminalTreeVO> deptList = deptFeignClient.allDeptList().getData();
        Map<String, PvTerminalTreeVO> mapCode = deptList.stream().collect(Collectors.toMap(PvTerminalTreeVO::getCode, Function.identity()));
        Map<String, PvTerminalTreeVO> mapList = deptList.stream().collect(Collectors.toMap(PvTerminalTreeVO::getId, Function.identity()));


        DateTime begin = DateUtil.beginOfMonth(DateUtil.parse(calculatedParam.getDataDate(), DatePattern.NORM_DATE_PATTERN));
        DateTime end = DateUtil.endOfMonth(DateUtil.parse(calculatedParam.getDataDate(), DatePattern.NORM_DATE_PATTERN));
        //日date
//        LocalDate date = LocalDateTimeUtil.parseDate(calculatedParam.getDataDate(),DatePattern.NORM_DATE_PATTERN);
        //月date
        LocalDate localDate = LocalDateTimeUtil.parseDate( DateUtil.format(begin, DatePattern.NORM_DATE_PATTERN), DatePattern.NORM_DATE_PATTERN);

        List<DictData> supvVoltageDicList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.DEV_VOLTAGE.getCode()).getData();
        Map<String, DictData> mapVoltage = supvVoltageDicList.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));
        DictData run = dicDataFeignClient.getDicDataByCode(DicDataEnum.RUN.getCode()).getData();


        for (StatationStat temp : stationList) {
            ConverterDetailStatisticsPO converterDetailStatisticsPO = new ConverterDetailStatisticsPO();
//            List<GeneratrixAndPowerStationDTO> tempGeneratrixDTOList = pmsGeneratrixDTOList.stream().filter(pmsGeneratrixDTO -> Objects.equals(pmsGeneratrixDTO.getPowerId(), temp.getPowerId())).collect(Collectors.toList());
            List<Monitor> tempMonitorList = monitorList.stream().filter(monitor -> Objects.equals(monitor.getPowerrId(), temp.getPowerId())).collect(Collectors.toList());
            List<String> monitorIdList = tempMonitorList.stream().map(Monitor::getId).collect(Collectors.toList());
            converterDetailStatisticsPO.setStatisticalDate(calculatedParam.getDataDate());
            converterDetailStatisticsPO.setStatisticalType("03");

            if (mapCode.containsKey(temp.getOrgId())) {
                PvTerminalTreeVO pvTerminalTreeVO = mapCode.get(temp.getOrgId());
                String[] split = (pvTerminalTreeVO.getPids() + StrUtil.COMMA + pvTerminalTreeVO.getId())
                        .split(StrUtil.COMMA);
                for (int i = 2; i < split.length; i++) {
                    //省
                    if (i == 2) {
                        if (mapList.containsKey(split[i])) {
                            pvTerminalTreeVO = mapList.get(split[i]);
                            converterDetailStatisticsPO.setProvinceName(pvTerminalTreeVO.getName());
                            converterDetailStatisticsPO.setProvinceId(pvTerminalTreeVO.getCode());
                        }
                    }
                    //市
                    if (i == 3) {
                        if (mapList.containsKey(split[i])) {
                            pvTerminalTreeVO = mapList.get(split[i]);
                            converterDetailStatisticsPO.setCityName(pvTerminalTreeVO.getName());
                            converterDetailStatisticsPO.setCityId(pvTerminalTreeVO.getCode());
                        }
                    }
                    //县
                    if (i == 4) {
                        if (mapList.containsKey(split[i])) {
                            pvTerminalTreeVO = mapList.get(split[i]);
                            converterDetailStatisticsPO.setCountyName(pvTerminalTreeVO.getName());
                            converterDetailStatisticsPO.setCountyId(pvTerminalTreeVO.getCode());
                        }
                    }
                }
            }


            converterDetailStatisticsPO.setConverterId(temp.getPowerId());
            converterDetailStatisticsPO.setConverterName(temp.getPowerName());
            converterDetailStatisticsPO.setId(temp.getPowerId()+"-"+calculatedParam.getDataDate());

            //电站等级
            if (mapVoltage.containsKey(temp.getVoltageLevel())) {
                converterDetailStatisticsPO.setVoltageLevel(String.format("%02d", mapVoltage.get(temp.getVoltageLevel()).getAlgoDescribe()));
            }
            converterDetailStatisticsPO.setBusId("");
            converterDetailStatisticsPO.setBusName("");
            converterDetailStatisticsPO.setBusVoltageLevel("");
            converterDetailStatisticsPO.setMonitorId("");

            //站内有效监测点数量
            Integer effectiveMonitorNum = 0;
            if (!CollectionUtils.isEmpty(monitorIdList)) {
                List<ROperatingMonitorDPO> list = rOperatingMonitorService.lambdaQuery().
                        in(ROperatingMonitorDPO::getMeasurementPointId, monitorIdList).
                        eq(ROperatingMonitorDPO::getDataDate, calculatedParam.getDataDate()).
                        ge(ROperatingMonitorDPO::getDataIntegrityRate, 0.95).
                        eq(ROperatingMonitorDPO::getIsUnusual, 1).list();
                effectiveMonitorNum = list.size();
            }


            converterDetailStatisticsPO.setEffectiveMonitorNum(effectiveMonitorNum);
            //换流站电压等级》500kv，奇次谐波电压限值为1.6，压总谐波畸变率95%概率值限值为2.0
            converterDetailStatisticsPO.setOddVoltLimit(BigDecimal.valueOf(1.6).setScale(1,BigDecimal.ROUND_HALF_UP));
            converterDetailStatisticsPO.setVthdLimit(BigDecimal.valueOf(2.0).setScale(1,BigDecimal.ROUND_HALF_UP));
            RStatSubstationMPO one = rStatSubstationMPOService.lambdaQuery().eq(RStatSubstationMPO::getSubstationId, temp.getPowerId()).eq(RStatSubstationMPO::getDataDate, localDate).one();
            if (!Objects.isNull(one)){
                converterDetailStatisticsPO.setHarmvOvDay(one.getVOverDay().intValue());
                converterDetailStatisticsPO.setMonthsCount(localDate.getMonthValue());
                converterDetailStatisticsPO.setMonthOvDays(BigDecimal.valueOf(one.getVOverDay()));
                converterDetailStatisticsPO.setTotalOvDays(one.getHarmonicOverDay().intValue());
            }
            if (!CollectionUtils.isEmpty(monitorIdList)) {
                List<RStatDataVDPO> cp95 = IRStatDataVDService.lambdaQuery().
                        in(RStatDataVDPO::getLineId, monitorIdList).
                        eq(RStatDataVDPO::getTime, calculatedParam.getDataDate()).
                        eq(RStatDataVDPO::getValueType, "CP95").list();

                if (!CollectionUtils.isEmpty(cp95)) {
                    double vthd = cp95.stream().mapToDouble(RStatDataVDPO::getVThd).average().getAsDouble();
                    converterDetailStatisticsPO.setVthd(BigDecimal.valueOf(vthd).setScale(1,BigDecimal.ROUND_HALF_UP));

                    double v3 = cp95.stream().mapToDouble(RStatDataVDPO::getVThd).average().getAsDouble();
                    converterDetailStatisticsPO.setV3(BigDecimal.valueOf(v3).setScale(1,BigDecimal.ROUND_HALF_UP));

                    double v5 = cp95.stream().mapToDouble(RStatDataVDPO::getV5).average().getAsDouble();
                    converterDetailStatisticsPO.setV5(BigDecimal.valueOf(v5).setScale(1,BigDecimal.ROUND_HALF_UP));

                    double v7 = cp95.stream().mapToDouble(RStatDataVDPO::getV7).average().getAsDouble();
                    converterDetailStatisticsPO.setV7(BigDecimal.valueOf(v7).setScale(1,BigDecimal.ROUND_HALF_UP));

                    double v11 = cp95.stream().mapToDouble(RStatDataVDPO::getV11).average().getAsDouble();
                    converterDetailStatisticsPO.setV11(BigDecimal.valueOf(v11).setScale(1,BigDecimal.ROUND_HALF_UP));

                    double v13 = cp95.stream().mapToDouble(RStatDataVDPO::getV13).average().getAsDouble();
                    converterDetailStatisticsPO.setV13(BigDecimal.valueOf(v13).setScale(1,BigDecimal.ROUND_HALF_UP));

                    double v23 = cp95.stream().mapToDouble(RStatDataVDPO::getV23).average().getAsDouble();
                    converterDetailStatisticsPO.setV23(BigDecimal.valueOf(v23).setScale(1,BigDecimal.ROUND_HALF_UP));

                    double v25 = cp95.stream().mapToDouble(RStatDataVDPO::getV25).average().getAsDouble();
                    converterDetailStatisticsPO.setV25(BigDecimal.valueOf(v25).setScale(1,BigDecimal.ROUND_HALF_UP));

                }
            }
            converterDetailStatisticsPOList.add(converterDetailStatisticsPO);


        }

        if(!CollectionUtils.isEmpty(converterDetailStatisticsPOList)){
            this.saveOrUpdateBatch(converterDetailStatisticsPOList);
        }
    }
}
