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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.device.biz.pojo.dto.DeptGetChildrenMoreDTO;
import com.njcn.device.biz.pojo.dto.LineDevGetDTO;
import com.njcn.device.pms.api.MonitorClient;
import com.njcn.device.pms.pojo.po.Monitor;
import com.njcn.harmonic.pojo.po.RMpPartHarmonicDetailD;
import com.njcn.harmonic.pojo.po.RMpSurplusHarmonicDetailD;
import com.njcn.harmonic.pojo.po.send.PqTypicalSourceCreatePO;
import com.njcn.harmonic.pojo.po.upload.PmsRunStatisticD;
import com.njcn.harmonic.pojo.po.upload.PmsRunStatisticM;
import com.njcn.harmonic.pojo.po.upload.PmsRunStatisticY;
import com.njcn.prepare.harmonic.mapper.mysql.line.RMpPartHarmonicDetailDMapper;
import com.njcn.prepare.harmonic.mapper.mysql.line.RMpSurplusHarmonicDetailDMapper;
import com.njcn.prepare.harmonic.mapper.mysql.send.PqTypicalSourceCreatePOMapper;
import com.njcn.prepare.harmonic.mapper.mysql.upload.PmsRunStatisticDMapper;
import com.njcn.prepare.harmonic.pojo.bo.CalculatedParam;
import com.njcn.prepare.harmonic.pojo.mysql.ROperatingMonitorDPO;
import com.njcn.prepare.harmonic.service.mysql.line.ROperatingMonitorService;
import com.njcn.prepare.harmonic.service.mysql.send.PqTypicalSourceCreatePOService;
import com.njcn.prepare.harmonic.service.mysql.upload.IPmsRunStatisticMService;
import com.njcn.prepare.harmonic.service.mysql.upload.IPmsRunStatisticYService;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.api.DictTreeFeignClient;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.system.enums.DicDataTypeEnum;
import com.njcn.system.enums.DicTreeEnum;
import com.njcn.system.pojo.po.DictData;
import com.njcn.system.pojo.po.SysDicTreePO;
import com.njcn.system.pojo.vo.DictTreeVO;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.user.pojo.vo.PvTerminalTreeVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
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;
import java.util.stream.Stream;

/**
 *
 * Description:
 * Date: 2023/12/12  15:16【需求编号】
 *
 * @author clam
 * @version V1.0.0
 */
@Service
@RequiredArgsConstructor
public class PqTypicalSourceCreatePOServiceImpl extends ServiceImpl<PqTypicalSourceCreatePOMapper, PqTypicalSourceCreatePO> implements PqTypicalSourceCreatePOService{

    private final DeptFeignClient deptFeignClient;
    private final DicDataFeignClient dicDataFeignClient;
    private final MonitorClient monitorClient;
    private final DictTreeFeignClient dictTreeFeignClient;

    private final RMpPartHarmonicDetailDMapper rMpPartHarmonicDetailDMapper;
    private final RMpSurplusHarmonicDetailDMapper rMpSurplusHarmonicDetailDMapper;
    private final ROperatingMonitorService rOperatingMonitorService;
    private final PmsRunStatisticDMapper runStatisticDMapper;
    private final IPmsRunStatisticMService runStatisticMService;
    private final IPmsRunStatisticYService runStatisticYService;


    /*
    *01	电压
    *02	长时间闪变
    *03	三相电压不平衡
    *04	电压总谐波畸变率
    *05	各次谐波电压
    *06	负序电流
    *
    * */
    @Override
    public void handlerDay(CalculatedParam<DeptGetChildrenMoreDTO> calculatedParam) {
        List<PmsRunStatisticD> pmsRunStatisticsListD = runStatisticDMapper.selectList(new LambdaQueryWrapper<PmsRunStatisticD>().eq(PmsRunStatisticD::getStatisticDate,calculatedParam.getDataDate()));
        Map<String, PmsRunStatisticD> pmsRunStatisticMap = pmsRunStatisticsListD.stream().collect(Collectors.toMap(PmsRunStatisticD::getDeptId,Function.identity()));



        List<PqTypicalSourceCreatePO> pqTypicalSourceCreatePOList = new ArrayList<>();
        LocalDate localDate = LocalDateTimeUtil.parseDate(calculatedParam.getDataDate(), DatePattern.NORM_DATE_PATTERN);

        QueryWrapper<RMpPartHarmonicDetailD> queryWrapper = new QueryWrapper<>();
        QueryWrapper<RMpSurplusHarmonicDetailD> rMpSurplusHarmonicDetailDQueryWrapper = new QueryWrapper<>();
        List<SysDicTreePO> sysdictreepo = dictTreeFeignClient.queryAll().getData();
       /* List<String> other_interferencesource_users = Stream.of(DicDataEnum.SEMICONDUCTOR_MANUFACTURING.getCode(),
                DicDataEnum.PRECISION_MACHINING.getCode(),
                DicDataEnum.PARTY_GOVERNMENT.getCode(),
                DicDataEnum.NOSOCOMIUM.getCode(),
                DicDataEnum.TRANSPORTATION_HUB.getCode(),
                DicDataEnum.AERODROME.getCode(),
                DicDataEnum.FINANCE.getCode(),
                DicDataEnum.DATA_CENTER.getCode(),
                DicDataEnum.HAZARDOUS_CHEMICALS.getCode(),
                DicDataEnum.EXPLOSIVE_PRODUCTS.getCode(),
                DicDataEnum.LARGEVENUE.getCode()
                ).collect(Collectors.toList());*/


        List<String> windfarm_user = Stream.of(
                DicDataEnum.WINDPOWER_STATION.getCode()).collect(Collectors.toList());
        List<String> photovoltaicsit_eusers = Stream.of(
                DicDataEnum.PHOTOVOLTAIC_POWER_STATION.getCode()).collect(Collectors.toList());
        List<String> tractionstation = Stream.of(
                DicDataEnum.ELECTRIFIED_RAILWAY.getCode()).collect(Collectors.toList());

        DictTreeVO dictTreeVO = dictTreeFeignClient.queryByCode(DicTreeEnum.Imp_Users.getCode()).getData();
        List<DictTreeVO> dictTreeVOList = dictTreeFeignClient.query(dictTreeVO.getId()).getData();
        List<String> importUser = dictTreeVOList.stream().map(DictTreeVO::getCode).distinct().collect(Collectors.toList());
        importUser.add(dictTreeVO.getCode());


        /*3.45	典型源荷用户类型*/
        List<String> collect = Stream.of(DicDataEnum.TRACTIONSTATION.getCode(),
                DicDataEnum.WINDFARM_USER.getCode(),
                DicDataEnum.PHOTOVOLTAICSIT_EUSERS.getCode(),
                DicDataEnum.OTHER_INTERFERENCESOURCE_USERS.getCode()).collect(Collectors.toList());

//        List<SysDicTreePO> other_interferencesource_users_dict = sysdictreepo.stream().filter(temp -> other_interferencesource_users.contains(temp.getCode())).collect(Collectors.toList());
        List<SysDicTreePO> windfarm_user_dict = sysdictreepo.stream().filter(temp -> windfarm_user.contains(temp.getCode())).collect(Collectors.toList());
        List<SysDicTreePO> photovoltaicsit_eusers_dict = sysdictreepo.stream().filter(temp -> photovoltaicsit_eusers.contains(temp.getCode())).collect(Collectors.toList());
        List<SysDicTreePO> tractionstation_dict = sysdictreepo.stream().filter(temp -> tractionstation.contains(temp.getCode())).collect(Collectors.toList());
        List<SysDicTreePO> import_dict = sysdictreepo.stream().filter(temp -> importUser.contains(temp.getCode())).collect(Collectors.toList());

        List<SysDicTreePO> un_other_interferencesource_users_dict =  new ArrayList<>();
        un_other_interferencesource_users_dict.addAll(photovoltaicsit_eusers_dict);
        un_other_interferencesource_users_dict.addAll(tractionstation_dict);
        un_other_interferencesource_users_dict.addAll(windfarm_user_dict);
        un_other_interferencesource_users_dict.addAll(import_dict);


        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()));
//        List<DictData> indicatorTypeDate = dicDataFeignClient.getDicDataByTypeCode(
//                DicDataTypeEnum.STEADY_STATIS.getCode()).getData();

        List<DictData> supvVoltageDicList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.DEV_VOLTAGE.getCode()).getData();
        Map<String, DictData> mapVoltage = supvVoltageDicList.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));
        for (DeptGetChildrenMoreDTO deptGetChildrenMoreDTO : calculatedParam.getIdList()) {
            List<String> collect1;
            if(pmsRunStatisticMap.containsKey(deptGetChildrenMoreDTO.getUnitId())){
                String typicalOnlineIds = pmsRunStatisticMap.get(deptGetChildrenMoreDTO.getUnitId()).getTypicalOnlineIds();
                if(StrUtil.isNotBlank(typicalOnlineIds)){
                     collect1 = CollectionUtil.toList(typicalOnlineIds.split(StrUtil.COMMA));
                }else {
                    collect1 =  deptGetChildrenMoreDTO.getLineBaseList().stream().filter(temp->Objects.equals(temp.getIsUpToGrid(),1)).map(LineDevGetDTO::getPointId).collect(Collectors.toList());
                }
            } else {
                 collect1 = deptGetChildrenMoreDTO.getLineBaseList().stream().filter(temp->Objects.equals(temp.getIsUpToGrid(),1)).map(LineDevGetDTO::getPointId).collect(Collectors.toList());
            }
            List<Monitor> monitorList;
            if (!CollectionUtils.isEmpty(collect1)) {
                 monitorList = monitorClient.getMonitorList(collect1).getData();
            } else {
                monitorList = new ArrayList<>();
            }

            collect.stream().forEach(temp->{
                PqTypicalSourceCreatePO pqTypicalSourceCreatePO = new PqTypicalSourceCreatePO();

                List<Monitor> tempList = new ArrayList<>();
                if (temp.equals(DicDataEnum.TRACTIONSTATION.getCode())){
                    List<String> idList = tractionstation_dict.stream().map(SysDicTreePO::getId).collect(Collectors.toList());
                    tempList = monitorList.stream().filter(tempmonitor -> idList.contains(tempmonitor.getObjType())).collect(Collectors.toList());
                    pqTypicalSourceCreatePO.setIndustryType("99");

                } else if (temp.equals(DicDataEnum.WINDFARM_USER.getCode())) {
                    List<String> idList = windfarm_user_dict.stream().map(SysDicTreePO::getId).collect(Collectors.toList());
                    tempList = monitorList.stream().filter(tempmonitor -> idList.contains(tempmonitor.getObjType())).collect(Collectors.toList());
                    pqTypicalSourceCreatePO.setIndustryType("99");

                }else  if(temp.equals(DicDataEnum.PHOTOVOLTAICSIT_EUSERS.getCode())) {
                    List<String> idList = photovoltaicsit_eusers_dict.stream().map(SysDicTreePO::getId).collect(Collectors.toList());
                    tempList = monitorList.stream().filter(tempmonitor -> idList.contains(tempmonitor.getObjType())).collect(Collectors.toList());
                    pqTypicalSourceCreatePO.setIndustryType("99");
                }else if(temp.equals(DicDataEnum.OTHER_INTERFERENCESOURCE_USERS.getCode())) {
                    List<String> idList = un_other_interferencesource_users_dict.stream().map(SysDicTreePO::getId).collect(Collectors.toList());
                    tempList = monitorList.stream().filter(tempmonitor -> !idList.contains(tempmonitor.getObjType())).collect(Collectors.toList());
                    pqTypicalSourceCreatePO.setIndustryType("00");

                }

                if(CollectionUtils.isEmpty(tempList)){
                    return;
                }
//                else {
//                    //不需要赋值电站等级
//                    if (mapVoltage.containsKey(tempList.get(0).getVoltageLevel())) {
//                        pqTypicalSourceCreatePO.setVoltageLevel(String.format("%02d", mapVoltage.get(tempList.get(0).getVoltageLevel()).getAlgoDescribe()));
//                        //默认给05
//                        pqTypicalSourceCreatePO.setIndustryType("05");
//                    }
//
//                }
                List<String> monitorIds = tempList.stream().map(Monitor::getId).collect(Collectors.toList());
                //站内有效监测点数量
                Integer effectiveMonitorNum;

                List<RMpPartHarmonicDetailD> rMpPartHarmonicDetailDS;
                List<RMpSurplusHarmonicDetailD> rMpSurplusHarmonicDetailDS;
                if (!CollectionUtils.isEmpty(monitorIds)) {
                    List<ROperatingMonitorDPO> list = rOperatingMonitorService.lambdaQuery().
                            in(ROperatingMonitorDPO::getMeasurementPointId, monitorIds).
                            eq(ROperatingMonitorDPO::getDataDate, calculatedParam.getDataDate()).
                            ge(ROperatingMonitorDPO::getDataIntegrityRate, 0.95).
                            eq(ROperatingMonitorDPO::getIsUnusual, 1).list();
                    effectiveMonitorNum = list.size();

                    queryWrapper.clear();
                    queryWrapper.
                            in("measurement_point_id",monitorIds).
                            eq("data_date",localDate);
                    rMpPartHarmonicDetailDS = rMpPartHarmonicDetailDMapper.selectList(queryWrapper);

                    rMpSurplusHarmonicDetailDQueryWrapper.clear();
                    rMpSurplusHarmonicDetailDQueryWrapper.
                            in("measurement_point_id",monitorIds).
                            eq("data_date",localDate);
                    rMpSurplusHarmonicDetailDS = rMpSurplusHarmonicDetailDMapper.selectList(rMpSurplusHarmonicDetailDQueryWrapper);

                } else {
                    rMpSurplusHarmonicDetailDS = new ArrayList<>();
                    rMpPartHarmonicDetailDS = new ArrayList<>();
                    effectiveMonitorNum = 0;
                }
                if(deptGetChildrenMoreDTO.getUnitId().equals("13B9B47F1E483324E05338297A0A0595")){
                    System.out.println("");
                }

                pqTypicalSourceCreatePO = initPqTypicalSourceCreatePO(pqTypicalSourceCreatePO,rMpPartHarmonicDetailDS,rMpSurplusHarmonicDetailDS,monitorIds.size());
                pqTypicalSourceCreatePO.setIndexType(temp);
                pqTypicalSourceCreatePO.setStatisticalDate(calculatedParam.getDataDate());
                pqTypicalSourceCreatePO.setComputeDate(calculatedParam.getDataDate());
                pqTypicalSourceCreatePO.setStatisticalType("03");
                pqTypicalSourceCreatePO.setMonitorNum(monitorIds.size());
                pqTypicalSourceCreatePO.setMonitorCount(monitorIds.size());
                pqTypicalSourceCreatePO.setMonitoringRate(divideAndRound(monitorIds.size(),monitorIds.size()));
                if (mapCode.containsKey(deptGetChildrenMoreDTO.getUnitId())) {
                    PvTerminalTreeVO pvTerminalTreeVO = mapCode.get(deptGetChildrenMoreDTO.getUnitId());
                    String[] split = (pvTerminalTreeVO.getPids() + StrUtil.COMMA + pvTerminalTreeVO.getId())
                            .split(StrUtil.COMMA);
                    if (split.length <3) {
                        return;
                    }

                    for (int i = 2; i < split.length; i++) {
                        //省
                        if (i == 2) {
                            if (mapList.containsKey(split[i])) {
                                pvTerminalTreeVO = mapList.get(split[i]);
                                pqTypicalSourceCreatePO.setProvinceName(pvTerminalTreeVO.getName());
                                pqTypicalSourceCreatePO.setProvinceId(pvTerminalTreeVO.getCode());
                                pqTypicalSourceCreatePO.setStatisticalLevel("3");
                            }
                        }
                        //市
                        if (i == 3) {
                            if (mapList.containsKey(split[i])) {
                                pvTerminalTreeVO = mapList.get(split[i]);
                                pqTypicalSourceCreatePO.setCityName(pvTerminalTreeVO.getName());
                                pqTypicalSourceCreatePO.setCityId(pvTerminalTreeVO.getCode());
                                pqTypicalSourceCreatePO.setStatisticalLevel("4");

                            }
                        }
                        //县
                        if (i == 4) {
                            if (mapList.containsKey(split[i])) {
                                pvTerminalTreeVO = mapList.get(split[i]);
                                pqTypicalSourceCreatePO.setCountyName(pvTerminalTreeVO.getName());
                                pqTypicalSourceCreatePO.setCountyId(pvTerminalTreeVO.getCode());
                                pqTypicalSourceCreatePO.setStatisticalLevel("5");

                            }
                        }
                    }
                }
                pqTypicalSourceCreatePO.setId(deptGetChildrenMoreDTO.getUnitId()+"-"+pqTypicalSourceCreatePO.getIndexType()+"-"+calculatedParam.getDataDate());
                pqTypicalSourceCreatePOList.add(pqTypicalSourceCreatePO);

            });


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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handlerMonth(CalculatedParam<DeptGetChildrenMoreDTO> calculatedParam) {
        List<PqTypicalSourceCreatePO> pqTypicalSourceCreatePOList = new ArrayList<>();
        //查询时间范围
        String begin = DateUtil.beginOfMonth(DateUtil.parse(calculatedParam.getDataDate(), DatePattern.NORM_DATE_PATTERN)).toString();
        String end = DateUtil.endOfMonth(DateUtil.parse(calculatedParam.getDataDate(), DatePattern.NORM_DATE_PATTERN)).toString();
        String date = begin.substring(0, 7);

        List<PmsRunStatisticM> pmsRunStatistic = runStatisticMService.selectListByDate(begin, end,calculatedParam.getDataDate());
        Map<String, PmsRunStatisticM> pmsRunStatisticMap = pmsRunStatistic.stream().collect(Collectors.toMap(PmsRunStatisticM::getDeptId,Function.identity()));



        List<SysDicTreePO> sysdictreepo = dictTreeFeignClient.queryAll().getData();

        List<String> windfarm_user = Stream.of(
                DicDataEnum.WINDPOWER_STATION.getCode()).collect(Collectors.toList());
        List<String> photovoltaicsit_eusers = Stream.of(
                DicDataEnum.PHOTOVOLTAIC_POWER_STATION.getCode()).collect(Collectors.toList());
        List<String> tractionstation = Stream.of(
                DicDataEnum.ELECTRIFIED_RAILWAY.getCode()).collect(Collectors.toList());

        DictTreeVO dictTreeVO = dictTreeFeignClient.queryByCode(DicTreeEnum.Imp_Users.getCode()).getData();
        List<DictTreeVO> dictTreeVOList = dictTreeFeignClient.query(dictTreeVO.getId()).getData();
        List<String> importUser = dictTreeVOList.stream().map(DictTreeVO::getCode).distinct().collect(Collectors.toList());
        importUser.add(dictTreeVO.getCode());


        /*3.45	典型源荷用户类型*/
        List<String> collect = Stream.of(DicDataEnum.TRACTIONSTATION.getCode(),
                DicDataEnum.WINDFARM_USER.getCode(),
                DicDataEnum.PHOTOVOLTAICSIT_EUSERS.getCode(),
                DicDataEnum.OTHER_INTERFERENCESOURCE_USERS.getCode()).collect(Collectors.toList());

        List<SysDicTreePO> windfarm_user_dict = sysdictreepo.stream().filter(temp -> windfarm_user.contains(temp.getCode())).collect(Collectors.toList());
        List<SysDicTreePO> photovoltaicsit_eusers_dict = sysdictreepo.stream().filter(temp -> photovoltaicsit_eusers.contains(temp.getCode())).collect(Collectors.toList());
        List<SysDicTreePO> tractionstation_dict = sysdictreepo.stream().filter(temp -> tractionstation.contains(temp.getCode())).collect(Collectors.toList());
        List<SysDicTreePO> import_dict = sysdictreepo.stream().filter(temp -> importUser.contains(temp.getCode())).collect(Collectors.toList());

        List<SysDicTreePO> un_other_interferencesource_users_dict =  new ArrayList<>();
        un_other_interferencesource_users_dict.addAll(photovoltaicsit_eusers_dict);
        un_other_interferencesource_users_dict.addAll(tractionstation_dict);
        un_other_interferencesource_users_dict.addAll(windfarm_user_dict);
        un_other_interferencesource_users_dict.addAll(import_dict);


        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()));

        for (DeptGetChildrenMoreDTO deptGetChildrenMoreDTO : calculatedParam.getIdList()) {
            List<String> collect1;
            if(pmsRunStatisticMap.containsKey(deptGetChildrenMoreDTO.getUnitId())){
                String typicalOnlineIds = pmsRunStatisticMap.get(deptGetChildrenMoreDTO.getUnitId()).getTypicalOnlineIds();
                if(StrUtil.isNotBlank(typicalOnlineIds)){
                    collect1 = CollectionUtil.toList(typicalOnlineIds.split(StrUtil.COMMA));
                }else {
                    collect1 =  deptGetChildrenMoreDTO.getLineBaseList().stream().filter(temp->Objects.equals(temp.getIsUpToGrid(),1)).map(LineDevGetDTO::getPointId).collect(Collectors.toList());
                }
            } else {
                collect1 = deptGetChildrenMoreDTO.getLineBaseList().stream().filter(temp->Objects.equals(temp.getIsUpToGrid(),1)).map(LineDevGetDTO::getPointId).collect(Collectors.toList());
            }
            List<Monitor> monitorList;
            if (!CollectionUtils.isEmpty(collect1)) {
                monitorList = monitorClient.getMonitorList(collect1).getData();
            } else {
                monitorList = new ArrayList<>();
            }

            collect.stream().forEach(temp->{
                PqTypicalSourceCreatePO pqTypicalSourceCreatePO = new PqTypicalSourceCreatePO();

                List<Monitor> tempList = new ArrayList<>();
                if (temp.equals(DicDataEnum.TRACTIONSTATION.getCode())){
                    List<String> idList = tractionstation_dict.stream().map(SysDicTreePO::getId).collect(Collectors.toList());
                    tempList = monitorList.stream().filter(tempmonitor -> idList.contains(tempmonitor.getObjType())).collect(Collectors.toList());
                    pqTypicalSourceCreatePO.setIndustryType("99");

                } else if (temp.equals(DicDataEnum.WINDFARM_USER.getCode())) {
                    List<String> idList = windfarm_user_dict.stream().map(SysDicTreePO::getId).collect(Collectors.toList());
                    tempList = monitorList.stream().filter(tempmonitor -> idList.contains(tempmonitor.getObjType())).collect(Collectors.toList());
                    pqTypicalSourceCreatePO.setIndustryType("99");

                }else  if(temp.equals(DicDataEnum.PHOTOVOLTAICSIT_EUSERS.getCode())) {
                    List<String> idList = photovoltaicsit_eusers_dict.stream().map(SysDicTreePO::getId).collect(Collectors.toList());
                    tempList = monitorList.stream().filter(tempmonitor -> idList.contains(tempmonitor.getObjType())).collect(Collectors.toList());
                    pqTypicalSourceCreatePO.setIndustryType("99");
                }else if(temp.equals(DicDataEnum.OTHER_INTERFERENCESOURCE_USERS.getCode())) {
                    List<String> idList = un_other_interferencesource_users_dict.stream().map(SysDicTreePO::getId).collect(Collectors.toList());
                    tempList = monitorList.stream().filter(tempmonitor -> !idList.contains(tempmonitor.getObjType())).collect(Collectors.toList());
                    pqTypicalSourceCreatePO.setIndustryType("00");

                }

                if(CollectionUtils.isEmpty(tempList)){
                    return;
                }
                List<String> monitorIds = tempList.stream().map(Monitor::getId).collect(Collectors.toList());
                if (mapCode.containsKey(deptGetChildrenMoreDTO.getUnitId())) {
                    PvTerminalTreeVO pvTerminalTreeVO = mapCode.get(deptGetChildrenMoreDTO.getUnitId());
                    String[] split = (pvTerminalTreeVO.getPids() + StrUtil.COMMA + pvTerminalTreeVO.getId())
                            .split(StrUtil.COMMA);
                    if (split.length <3) {
                        return;
                    }

                    for (int i = 2; i < split.length; i++) {
                        //省
                        if (i == 2) {
                            if (mapList.containsKey(split[i])) {
                                pvTerminalTreeVO = mapList.get(split[i]);
                                pqTypicalSourceCreatePO.setProvinceName(pvTerminalTreeVO.getName());
                                pqTypicalSourceCreatePO.setProvinceId(pvTerminalTreeVO.getCode());
                                pqTypicalSourceCreatePO.setStatisticalLevel("3");
                            }
                        }
                        //市
                        if (i == 3) {
                            if (mapList.containsKey(split[i])) {
                                pvTerminalTreeVO = mapList.get(split[i]);
                                pqTypicalSourceCreatePO.setCityName(pvTerminalTreeVO.getName());
                                pqTypicalSourceCreatePO.setCityId(pvTerminalTreeVO.getCode());
                                pqTypicalSourceCreatePO.setStatisticalLevel("4");

                            }
                        }
                        //县
                        if (i == 4) {
                            if (mapList.containsKey(split[i])) {
                                pvTerminalTreeVO = mapList.get(split[i]);
                                pqTypicalSourceCreatePO.setCountyName(pvTerminalTreeVO.getName());
                                pqTypicalSourceCreatePO.setCountyId(pvTerminalTreeVO.getCode());
                                pqTypicalSourceCreatePO.setStatisticalLevel("5");

                            }
                        }
                    }
                }
                pqTypicalSourceCreatePO.setIndexType(temp);
                pqTypicalSourceCreatePO.setStatisticalType("03");
                PqTypicalSourceCreatePO  po= this.baseMapper.selectAvgMonth(pqTypicalSourceCreatePO, begin, end);
                if(ObjectUtil.isNotNull(po)){
                    int ovNum = po.getInseqOvNum() + po.getFlickerOvNum() + po.getUnbanOvNum() + po.getVOvNum() + po.getIOvNum();
                    if(po.getOvNum()>ovNum||po.getOvCount()>ovNum){
                        pqTypicalSourceCreatePO.setOvNum(ovNum);
                        pqTypicalSourceCreatePO.setOvCount(ovNum);
                    }
                    po.setStatisticalType("02");
                    po.setIndexType(temp);
                    po.setStatisticalDate(date);
                    po.setComputeDate(calculatedParam.getDataDate());
                    po.setInterferenceSourceNum(monitorIds.size());
                    po.setInterferenceSourceCount(monitorIds.size());
                    po.setMonitorNum(monitorIds.size());
                    po.setMonitorCount(monitorIds.size());
                    po.setProvinceName(pqTypicalSourceCreatePO.getProvinceName());
                    po.setProvinceId(pqTypicalSourceCreatePO.getProvinceId());
                    po.setCityName(pqTypicalSourceCreatePO.getCityName());
                    po.setCityId(pqTypicalSourceCreatePO.getCityId());
                    po.setCountyName(pqTypicalSourceCreatePO.getCountyName());
                    po.setCountyId(pqTypicalSourceCreatePO.getCountyId());
                    po.setStatisticalLevel(pqTypicalSourceCreatePO.getStatisticalLevel());
                    po.setIndustryType(pqTypicalSourceCreatePO.getIndustryType());
                    po.setId(deptGetChildrenMoreDTO.getUnitId()+"-"+po.getIndexType()+"-"+po.getStatisticalType()+"-"+date);
                    pqTypicalSourceCreatePOList.add(po);
                }

            });


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

    @Override
    public void handleYear(CalculatedParam<DeptGetChildrenMoreDTO> calculatedParam) {
        List<PqTypicalSourceCreatePO> pqTypicalSourceCreatePOList = new ArrayList<>();
        //查询时间范围
        String begin = DateUtil.beginOfYear(DateUtil.parse(calculatedParam.getDataDate(), DatePattern.NORM_DATE_PATTERN)).toString();
        String end = DateUtil.endOfYear(DateUtil.parse(calculatedParam.getDataDate(), DatePattern.NORM_DATE_PATTERN)).toString();
        String date = begin.substring(0, 4);
        List<PmsRunStatisticY> pmsRunStatistic = runStatisticYService.selectListByDate(begin, end,calculatedParam.getDataDate());
        Map<String, PmsRunStatisticY> pmsRunStatisticMap = pmsRunStatistic.stream().collect(Collectors.toMap(PmsRunStatisticY::getDeptId,Function.identity()));

        List<SysDicTreePO> sysdictreepo = dictTreeFeignClient.queryAll().getData();

        List<String> windfarm_user = Stream.of(
                DicDataEnum.WINDPOWER_STATION.getCode()).collect(Collectors.toList());
        List<String> photovoltaicsit_eusers = Stream.of(
                DicDataEnum.PHOTOVOLTAIC_POWER_STATION.getCode()).collect(Collectors.toList());
        List<String> tractionstation = Stream.of(
                DicDataEnum.ELECTRIFIED_RAILWAY.getCode()).collect(Collectors.toList());

        DictTreeVO dictTreeVO = dictTreeFeignClient.queryByCode(DicTreeEnum.Imp_Users.getCode()).getData();
        List<DictTreeVO> dictTreeVOList = dictTreeFeignClient.query(dictTreeVO.getId()).getData();
        List<String> importUser = dictTreeVOList.stream().map(DictTreeVO::getCode).distinct().collect(Collectors.toList());
        importUser.add(dictTreeVO.getCode());


        /*3.45	典型源荷用户类型*/
        List<String> collect = Stream.of(DicDataEnum.TRACTIONSTATION.getCode(),
                DicDataEnum.WINDFARM_USER.getCode(),
                DicDataEnum.PHOTOVOLTAICSIT_EUSERS.getCode(),
                DicDataEnum.OTHER_INTERFERENCESOURCE_USERS.getCode()).collect(Collectors.toList());

        List<SysDicTreePO> windfarm_user_dict = sysdictreepo.stream().filter(temp -> windfarm_user.contains(temp.getCode())).collect(Collectors.toList());
        List<SysDicTreePO> photovoltaicsit_eusers_dict = sysdictreepo.stream().filter(temp -> photovoltaicsit_eusers.contains(temp.getCode())).collect(Collectors.toList());
        List<SysDicTreePO> tractionstation_dict = sysdictreepo.stream().filter(temp -> tractionstation.contains(temp.getCode())).collect(Collectors.toList());
        List<SysDicTreePO> import_dict = sysdictreepo.stream().filter(temp -> importUser.contains(temp.getCode())).collect(Collectors.toList());

        List<SysDicTreePO> un_other_interferencesource_users_dict =  new ArrayList<>();
        un_other_interferencesource_users_dict.addAll(photovoltaicsit_eusers_dict);
        un_other_interferencesource_users_dict.addAll(tractionstation_dict);
        un_other_interferencesource_users_dict.addAll(windfarm_user_dict);
        un_other_interferencesource_users_dict.addAll(import_dict);


        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()));

        for (DeptGetChildrenMoreDTO deptGetChildrenMoreDTO : calculatedParam.getIdList()) {
            List<String> collect1;
            if(pmsRunStatisticMap.containsKey(deptGetChildrenMoreDTO.getUnitId())){
                String typicalOnlineIds = pmsRunStatisticMap.get(deptGetChildrenMoreDTO.getUnitId()).getTypicalOnlineIds();
                if(StrUtil.isNotBlank(typicalOnlineIds)){
                    collect1 = CollectionUtil.toList(typicalOnlineIds.split(StrUtil.COMMA));
                }else {
                    collect1 =  deptGetChildrenMoreDTO.getLineBaseList().stream().filter(temp->Objects.equals(temp.getIsUpToGrid(),1)).map(LineDevGetDTO::getPointId).collect(Collectors.toList());
                }
            } else {
                collect1 = deptGetChildrenMoreDTO.getLineBaseList().stream().filter(temp->Objects.equals(temp.getIsUpToGrid(),1)).map(LineDevGetDTO::getPointId).collect(Collectors.toList());
            }
            List<Monitor> monitorList;
            if (!CollectionUtils.isEmpty(collect1)) {
                monitorList = monitorClient.getMonitorList(collect1).getData();
            } else {
                monitorList = new ArrayList<>();
            }

            collect.stream().forEach(temp->{
                PqTypicalSourceCreatePO pqTypicalSourceCreatePO = new PqTypicalSourceCreatePO();

                List<Monitor> tempList = new ArrayList<>();
                if (temp.equals(DicDataEnum.TRACTIONSTATION.getCode())){
                    List<String> idList = tractionstation_dict.stream().map(SysDicTreePO::getId).collect(Collectors.toList());
                    tempList = monitorList.stream().filter(tempmonitor -> idList.contains(tempmonitor.getObjType())).collect(Collectors.toList());
                    pqTypicalSourceCreatePO.setIndustryType("99");

                } else if (temp.equals(DicDataEnum.WINDFARM_USER.getCode())) {
                    List<String> idList = windfarm_user_dict.stream().map(SysDicTreePO::getId).collect(Collectors.toList());
                    tempList = monitorList.stream().filter(tempmonitor -> idList.contains(tempmonitor.getObjType())).collect(Collectors.toList());
                    pqTypicalSourceCreatePO.setIndustryType("99");

                }else  if(temp.equals(DicDataEnum.PHOTOVOLTAICSIT_EUSERS.getCode())) {
                    List<String> idList = photovoltaicsit_eusers_dict.stream().map(SysDicTreePO::getId).collect(Collectors.toList());
                    tempList = monitorList.stream().filter(tempmonitor -> idList.contains(tempmonitor.getObjType())).collect(Collectors.toList());
                    pqTypicalSourceCreatePO.setIndustryType("99");
                }else if(temp.equals(DicDataEnum.OTHER_INTERFERENCESOURCE_USERS.getCode())) {
                    List<String> idList = un_other_interferencesource_users_dict.stream().map(SysDicTreePO::getId).collect(Collectors.toList());
                    tempList = monitorList.stream().filter(tempmonitor -> !idList.contains(tempmonitor.getObjType())).collect(Collectors.toList());
                    pqTypicalSourceCreatePO.setIndustryType("00");

                }

                if(CollectionUtils.isEmpty(tempList)){
                    return;
                }
                List<String> monitorIds = tempList.stream().map(Monitor::getId).collect(Collectors.toList());
                if (mapCode.containsKey(deptGetChildrenMoreDTO.getUnitId())) {
                    PvTerminalTreeVO pvTerminalTreeVO = mapCode.get(deptGetChildrenMoreDTO.getUnitId());
                    String[] split = (pvTerminalTreeVO.getPids() + StrUtil.COMMA + pvTerminalTreeVO.getId())
                            .split(StrUtil.COMMA);
                    if (split.length <3) {
                        return;
                    }

                    for (int i = 2; i < split.length; i++) {
                        //省
                        if (i == 2) {
                            if (mapList.containsKey(split[i])) {
                                pvTerminalTreeVO = mapList.get(split[i]);
                                pqTypicalSourceCreatePO.setProvinceName(pvTerminalTreeVO.getName());
                                pqTypicalSourceCreatePO.setProvinceId(pvTerminalTreeVO.getCode());
                                pqTypicalSourceCreatePO.setStatisticalLevel("3");
                            }
                        }
                        //市
                        if (i == 3) {
                            if (mapList.containsKey(split[i])) {
                                pvTerminalTreeVO = mapList.get(split[i]);
                                pqTypicalSourceCreatePO.setCityName(pvTerminalTreeVO.getName());
                                pqTypicalSourceCreatePO.setCityId(pvTerminalTreeVO.getCode());
                                pqTypicalSourceCreatePO.setStatisticalLevel("4");

                            }
                        }
                        //县
                        if (i == 4) {
                            if (mapList.containsKey(split[i])) {
                                pvTerminalTreeVO = mapList.get(split[i]);
                                pqTypicalSourceCreatePO.setCountyName(pvTerminalTreeVO.getName());
                                pqTypicalSourceCreatePO.setCountyId(pvTerminalTreeVO.getCode());
                                pqTypicalSourceCreatePO.setStatisticalLevel("5");

                            }
                        }
                    }
                }
                pqTypicalSourceCreatePO.setIndexType(temp);
                pqTypicalSourceCreatePO.setStatisticalType("02");
                PqTypicalSourceCreatePO  po= this.baseMapper.selectAvgYear(pqTypicalSourceCreatePO, begin, end);
                if(ObjectUtil.isNotNull(po)){
                    int ovNum = po.getInseqOvNum() + po.getFlickerOvNum() + po.getUnbanOvNum() + po.getVOvNum() + po.getIOvNum();
                    if(po.getOvNum()>ovNum||po.getOvCount()>ovNum){
                        pqTypicalSourceCreatePO.setOvNum(ovNum);
                        pqTypicalSourceCreatePO.setOvCount(ovNum);
                    }
                    po.setStatisticalType("01");
                    po.setIndexType(temp);
                    po.setStatisticalDate(date);
                    po.setComputeDate(calculatedParam.getDataDate());
                    po.setInterferenceSourceNum(monitorIds.size());
                    po.setInterferenceSourceCount(monitorIds.size());
                    po.setMonitorNum(monitorIds.size());
                    po.setMonitorCount(monitorIds.size());
                    po.setProvinceName(pqTypicalSourceCreatePO.getProvinceName());
                    po.setProvinceId(pqTypicalSourceCreatePO.getProvinceId());
                    po.setCityName(pqTypicalSourceCreatePO.getCityName());
                    po.setCityId(pqTypicalSourceCreatePO.getCityId());
                    po.setCountyName(pqTypicalSourceCreatePO.getCountyName());
                    po.setCountyId(pqTypicalSourceCreatePO.getCountyId());
                    po.setStatisticalLevel(pqTypicalSourceCreatePO.getStatisticalLevel());
                    po.setIndustryType(pqTypicalSourceCreatePO.getIndustryType());
                    po.setId(deptGetChildrenMoreDTO.getUnitId()+"-"+po.getIndexType()+"-"+po.getStatisticalType()+"-"+date);
                    pqTypicalSourceCreatePOList.add(po);
                }
            });


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


    private PqTypicalSourceCreatePO initPqTypicalSourceCreatePO(PqTypicalSourceCreatePO pqTypicalSourceCreatePO,
//                                                                String code,
                                                                List<RMpPartHarmonicDetailD> rMpPartHarmonicDetailDS,
                                                                List<RMpSurplusHarmonicDetailD> rMpSurplusHarmonicDetailDS,
                                                                int count) {
        BigDecimal initialvalue = new BigDecimal(0.00);
        pqTypicalSourceCreatePO.setInterferenceSourceNum(count);

        //负序电流
        int inseqOvNum = Integer.valueOf(rMpPartHarmonicDetailDS.stream().filter(temp ->temp.getIsINeg()==1).count()+"");
        pqTypicalSourceCreatePO.setInseqOvNum(inseqOvNum);
        pqTypicalSourceCreatePO.setInseqOvRate(divideAndRound(inseqOvNum,count));
        pqTypicalSourceCreatePO.setInseqAvgOvRate(divideAndRound(inseqOvNum,count));


        //闪变
        int flickervalue = Integer.valueOf(rMpSurplusHarmonicDetailDS.stream().filter(temp ->temp.getIsFlicker()==1).count()+"");
        pqTypicalSourceCreatePO.setFlickerOvNum(flickervalue);
        pqTypicalSourceCreatePO.setFlickerOvRate(divideAndRound(flickervalue,count));
        pqTypicalSourceCreatePO.setFlickerAvgOvRate(divideAndRound(flickervalue,count));

        //三相电压不平衡度
        int phase_voltagevalue = Integer.valueOf(rMpPartHarmonicDetailDS.stream().filter(temp ->temp.getIsUnbalance()==1).count()+"");
        pqTypicalSourceCreatePO.setUnbanOvNum(phase_voltagevalue);
        pqTypicalSourceCreatePO.setUnbanOvRate(divideAndRound(phase_voltagevalue,count));
        pqTypicalSourceCreatePO.setUnbanAvgOvRate(divideAndRound(phase_voltagevalue,count));

        //谐波电压
        int harmonic_voltagevalue = Integer.valueOf(rMpPartHarmonicDetailDS.stream().filter(temp ->temp.getIsV()==1).count()+"");
        pqTypicalSourceCreatePO.setVOvNum(harmonic_voltagevalue);
        pqTypicalSourceCreatePO.setVOvRate(divideAndRound(harmonic_voltagevalue,count));
        pqTypicalSourceCreatePO.setVAvgOvRate(divideAndRound(harmonic_voltagevalue,count));

        //谐波电流
        int harmonic_Ivalue = Integer.valueOf(rMpPartHarmonicDetailDS.stream().filter(temp ->temp.getIsI()==1).count()+"");
        pqTypicalSourceCreatePO.setIOvNum(harmonic_Ivalue);
        pqTypicalSourceCreatePO.setIOvRate(divideAndRound(harmonic_Ivalue,count));
        pqTypicalSourceCreatePO.setIAvgOvRate(divideAndRound(harmonic_Ivalue,count));


        pqTypicalSourceCreatePO.setFlickerOvCount(flickervalue);
        pqTypicalSourceCreatePO.setHarmiOvCount(harmonic_Ivalue);
        pqTypicalSourceCreatePO.setInseqOvCount(inseqOvNum);
        pqTypicalSourceCreatePO.setUnbanOvCount(phase_voltagevalue);
        pqTypicalSourceCreatePO.setHarmvOvCount(harmonic_voltagevalue);
        //稳态指标是否超标(0:否 1:是)
        Map<String, Integer> collect = rMpSurplusHarmonicDetailDS.stream().collect(Collectors.toMap(RMpSurplusHarmonicDetailD::getMeasurementPointId, RMpSurplusHarmonicDetailD::getIsFlicker));
        int ovNum=0;
        for (RMpPartHarmonicDetailD detailD : rMpPartHarmonicDetailDS) {
            Integer isFlicker=0;
            int num = detailD.getIsINeg() + detailD.getIsUnbalance() + detailD.getIsV() + detailD.getIsI();
            if(collect.containsKey(detailD.getMeasurementPointId())){
                isFlicker = collect.get(detailD.getMeasurementPointId());
            }
            if((num+isFlicker)>0){
                ovNum++;
            }
        }
        int i = inseqOvNum + flickervalue + phase_voltagevalue + harmonic_voltagevalue + harmonic_Ivalue;
        if(ovNum>i){
            ovNum=i;
        }

        pqTypicalSourceCreatePO.setOvRate(divideAndRound(ovNum,count));
        if(ovNum>0){
            pqTypicalSourceCreatePO.setOvDayCount(1);
            pqTypicalSourceCreatePO.setAverageOvDays(new BigDecimal(1.00));
        }else {
            pqTypicalSourceCreatePO.setOvDayCount(0);
            pqTypicalSourceCreatePO.setAverageOvDays(initialvalue);
        }
        pqTypicalSourceCreatePO.setOvNum(ovNum);
        pqTypicalSourceCreatePO.setOvCount(ovNum);
        pqTypicalSourceCreatePO.setInterferenceSourceCount(count);


        return pqTypicalSourceCreatePO;
    }

    /**
     * @Description: divideAndRound
     * @Param:  两个int做除法返回BigDecimal保留2位小数 考虑到被除数为0的情况
     * @return: java.math.BigDecimal
     * @Author: clam
     * @Date: 2023/12/12
     */
    public  BigDecimal divideAndRound(Integer a, Integer b) {
        if (b == 0) {
            return BigDecimal.valueOf(0.00);
        }
        return NumberUtil.round(a*100.0/b,2);
    }


}
