package com.njcn.device.pq.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.config.GeneralInfo;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.device.common.service.GeneralDeviceService;
import com.njcn.device.pq.api.AlarmClient;
import com.njcn.device.pq.api.GeneralDeviceInfoClient;
import com.njcn.device.biz.enums.DeviceResponseEnum;
import com.njcn.device.pq.enums.LineBaseEnum;
import com.njcn.device.pq.enums.PowerFlagEnum;
import com.njcn.device.pq.enums.RunFlagEnum;
import com.njcn.device.pq.mapper.LineIntegrityDataMapper;
import com.njcn.device.pq.pojo.dto.GeneralDeviceDTO;
import com.njcn.device.pq.pojo.dto.PublicDTO;
import com.njcn.device.pq.pojo.param.DeviceInfoParam;
import com.njcn.device.pq.pojo.param.LineIntegrityDataParam;
import com.njcn.device.pq.pojo.param.OnlineRateParam;
import com.njcn.device.pq.pojo.po.LineDataIntegrity;
import com.njcn.device.pq.pojo.vo.AlarmStrategyVO;
import com.njcn.device.pq.pojo.vo.LineIntegrityDataVO;
import com.njcn.device.pq.pojo.vo.RStatIntegrityVO;
import com.njcn.device.pq.service.LineIntegrityDataService;
import com.njcn.device.pq.utils.DataStatisticsUtil;
import com.njcn.device.rstatintegrity.mapper.RStatIntegrityDMapper;
import com.njcn.device.userledger.service.UserLedgerService;
import com.njcn.harmonic.pojo.vo.IntegrityIconVO;
import com.njcn.supervision.pojo.param.user.UserReportParam;
import com.njcn.supervision.pojo.vo.user.UserLedgerVO;
import com.njcn.system.pojo.enums.StatisticsEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.Collator;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 监测点数据完整性
 *
 * @author yzh
 * @date 2022/9/14
 */

@Slf4j
@Service
@RequiredArgsConstructor
public class LineIntegrityDataServiceImpl extends ServiceImpl<LineIntegrityDataMapper, LineIntegrityDataVO> implements LineIntegrityDataService {

    private final LineIntegrityDataMapper lineIntegrityDataMapper;
    private final AlarmClient alarmClient;
    private final GeneralDeviceService generalDeviceService;
    private final RStatIntegrityDMapper rStatIntegrityDMapper;
    private final GeneralInfo generalInfo;
    private final GeneralDeviceInfoClient generalDeviceInfoClient;
    private final UserLedgerService userLedgerService;

    /**
     * 监测点数据完整性
     *
     * @param lineIntegrityDataParam 实体参数
     */
    @Override
    public List<LineIntegrityDataVO> getIntegrityDataOfLine(LineIntegrityDataParam lineIntegrityDataParam) {
        // 创建集合返回数据
        List<LineIntegrityDataVO> pro = new ArrayList<>();
        // 获取所有数据
        List<GeneralDeviceDTO> generalDeviceDTOList = generalDeviceService.getDeviceInfo(lineIntegrityDataParam, Stream.of(RunFlagEnum.RUNNING.getStatus()).collect(Collectors.toList()), Stream.of(1).collect(Collectors.toList()));

        // 判断所有数据集合状态
        if (CollectionUtil.isNotEmpty(generalDeviceDTOList)) {
            Map<String, UserLedgerVO> userLedgerVOMap;
            if (lineIntegrityDataParam.isUserLedger()) {
                List<UserLedgerVO> userLedgerVOList = userLedgerService.selectUserList(new UserReportParam());
                userLedgerVOMap = userLedgerVOList.stream().collect(Collectors.toMap(UserLedgerVO::getId, Function.identity()));
            } else {
                userLedgerVOMap = new HashMap<>();
            }


            // 获取告警策略列表
            List<AlarmStrategyVO> alarmStrategyVos = alarmClient.getAlarmStrategyData().getData();
            // 判断告警策略数据状态
            if (CollectionUtil.isEmpty(alarmStrategyVos)) {
                throw new BusinessException(DeviceResponseEnum.QUERY_ALARMSTRATEGY_DATA_EMPTY);
            }
            Map<String, Integer> mapA = alarmStrategyVos.stream().collect(Collectors.toMap(AlarmStrategyVO::getId, AlarmStrategyVO::getIntegrityValue));
            // 遍历集合
            for (GeneralDeviceDTO generalDeviceDTO : generalDeviceDTOList) {

                // 判断监测点索引集合状态
                if (CollectionUtils.isEmpty(generalDeviceDTO.getLineIndexes())) {
                    continue;
                }



                // 创建实体类
                LineIntegrityDataVO lineIntegrityDataVO = new LineIntegrityDataVO();

                // 通过监测点索引查询监测点信息
                List<LineIntegrityDataVO> lineList = lineIntegrityDataMapper.getDetailedParametersForLine(generalDeviceDTO.getLineIndexes(), lineIntegrityDataParam.getLineGrade());
                List<LineDataIntegrity> percentageOfCompleteDatas = rStatIntegrityDMapper.getLineIntegrityRate(generalDeviceDTO.getLineIndexes(), lineIntegrityDataParam.getSearchBeginTime(), lineIntegrityDataParam.getSearchEndTime());
                dealMonitorData(lineList,percentageOfCompleteDatas,mapA);

                List<LineIntegrityDataVO> userLedgerList = lineList.stream().filter(item -> StrUtil.isNotBlank(item.getObjId())).collect(Collectors.toList());
                List<LineIntegrityDataVO> powerLedgerList = lineList.stream().filter(item -> StrUtil.isBlank(item.getObjId())).collect(Collectors.toList());

                List<LineIntegrityDataVO> childrenList = new ArrayList<>();
                if (CollUtil.isNotEmpty(userLedgerList)) {
                    Map<String, List<LineIntegrityDataVO>> objMap = userLedgerList.stream().collect(Collectors.groupingBy(LineIntegrityDataVO::getObjId));
                    objMap.forEach((obj, mList) -> {
                        UserLedgerVO userLedgerVO = userLedgerVOMap.getOrDefault(obj, new UserLedgerVO());
                        LineIntegrityDataVO children = new LineIntegrityDataVO();
                        children.setId(obj);
                        children.setPid(userLedgerVO.getStationId());
                        children.setName(userLedgerVO.getProjectName());
                        children.setPowerFlag(PowerFlagEnum.NO_GRID_SIDE.getCode());
                        children.setChildren(mList);
                        dealDataJinDu(mList,children);
                        childrenList.add(children);
                    });
                }
                Map<String,List<LineIntegrityDataVO>> userStationMap = childrenList.stream().collect(Collectors.groupingBy(LineIntegrityDataVO::getPid));



                List<String> lineIds = lineList.stream().map(LineIntegrityDataVO::getId).distinct().collect(Collectors.toList());

                // 通过供电站索引查询供电站信息
                List<LineIntegrityDataVO> subList = lineIntegrityDataMapper.getSubList(lineIds);
                List<String> gdIds = subList.stream().map(LineIntegrityDataVO::getPid).distinct().collect(Collectors.toList());

                // 通过供电公司索引查询供电公司信息
                List<LineIntegrityDataVO> gdList = lineIntegrityDataMapper.getGdList(gdIds);

                // 通过供电公司索引查询省会
                List<LineIntegrityDataVO> proList = lineIntegrityDataMapper.getProvinceList(gdIds);

                //处理变电站
                dealChildrenData(subList, powerLedgerList,userStationMap, true);
                //处理供电公司
                dealChildrenData(gdList, subList, null,false);

                if (lineIntegrityDataParam.getStatisticalType().getCode().equalsIgnoreCase(StatisticsEnum.POWER_NETWORK.getCode())) {
                    lineIntegrityDataVO.setChildren(gdList);
                } else {
                    //还需要额外处理省会
                    dealChildrenData(proList, gdList, null,false);
                    lineIntegrityDataVO.setChildren(proList);
                }

                // 数据封装
                // 汇总所有监测点的实际时间和期望时间，重新计算完整性
                int totalRealTime = (int) lineList.stream().filter(item -> item.getIntegrityData() != 3.14159).mapToLong(LineIntegrityDataVO::getRealTime).sum();
                int totalDueTime = (int) lineList.stream().filter(item -> item.getIntegrityData() != 3.14159).mapToLong(LineIntegrityDataVO::getDueTime).sum();
                lineIntegrityDataVO.setRealTime(totalRealTime);
                lineIntegrityDataVO.setDueTime(totalDueTime);
                lineIntegrityDataVO.setIntegrityData(DataStatisticsUtil.calculateIntegrityRate(totalRealTime, totalDueTime));
                LineIntegrityDataVO temp = lineList.stream().filter(t -> t.getAlgoDescribe() != null).min(Comparator.comparing(LineIntegrityDataVO::getAlgoDescribe)).orElse(new LineIntegrityDataVO());
                lineIntegrityDataVO.setAlgoDescribe(temp.getAlgoDescribe());
                lineIntegrityDataVO.setId(generalDeviceDTO.getIndex());
                lineIntegrityDataVO.setName(generalDeviceDTO.getName());
                lineIntegrityDataVO.setLevel(0);
                pro.add(lineIntegrityDataVO);

            }

           // getAreaIntegrityData(mapAlarm, pro);
            return pro;
        } else {
            return new ArrayList<>();
        }
    }


    private void dealDataJinDu(List<LineIntegrityDataVO> mList,LineIntegrityDataVO children){
        // 汇总子节点的实际时间和期望时间，重新计算完整性
        int totalRealTime = (int) mList.stream().filter(it->it.getIntegrityData()!=3.14159).mapToLong(LineIntegrityDataVO::getRealTime).sum();
        int totalDueTime = (int) mList.stream().filter(it->it.getIntegrityData()!=3.14159).mapToLong(LineIntegrityDataVO::getDueTime).sum();
        children.setRealTime(totalRealTime);
        children.setDueTime(totalDueTime);
        children.setIntegrityData(DataStatisticsUtil.calculateIntegrityRate(totalRealTime, totalDueTime));
    }

    private void dealMonitorData(List<LineIntegrityDataVO> lineList,List<LineDataIntegrity> percentageOfCompleteDatas,Map<String, Integer> mapA){
        // 查询监测点数据完整性
        Map<String,LineDataIntegrity> dataIntegrityMap = percentageOfCompleteDatas.stream().collect(Collectors.toMap(LineDataIntegrity::getLineId,Function.identity()));
        for (LineIntegrityDataVO monitor : lineList) {
            boolean flag = false;
            if(dataIntegrityMap.containsKey(monitor.getId())){
                flag = true;
                LineDataIntegrity integrity = dataIntegrityMap.get(monitor.getId());
                monitor.setRealTime(integrity.getReal() == null ? 0 : integrity.getReal().intValue());
                monitor.setDueTime(integrity.getDue() == null ? 0 : integrity.getDue().intValue());
                Double integrityData = DataStatisticsUtil.calculateIntegrityRate(monitor.getRealTime(), monitor.getDueTime());
                monitor.setIntegrityData(integrityData);
                if (StrUtil.isNotBlank(monitor.getLineGrade())) {
                    if (mapA.containsKey(monitor.getLineGrade())) {
                        if (integrityData != 3.14159 && integrityData > mapA.get(monitor.getLineGrade())) {
                            monitor.setValueOver(1);
                        } else {
                            monitor.setValueOver(0);
                        }
                    } else {
                        throw new BusinessException(DeviceResponseEnum.LINE_GRADE_LESS);
                    }
                } else {
                    //默认没有设置等级的监测点标志为1  0.不合格 1.合格
                    monitor.setValueOver(1);
                }
            }
            if (!flag) {
                //表示未匹配到数据完整性
                monitor.setIntegrityData(3.14159);
                monitor.setRealTime(0);
                monitor.setDueTime(0);
                monitor.setValueOver(0);
            }
        }
    }

    @Override
    public List<IntegrityIconVO> getIntegrityIcon(DeviceInfoParam.CompareBusinessParam integrityIconParam) {
        integrityIconParam.setServerName(generalInfo.getMicroServiceName());
        List<GeneralDeviceDTO> generalDeviceDTOList = generalDeviceInfoClient.getPracticalRunDeviceInfo(integrityIconParam).getData();
        List<IntegrityIconVO> out = new ArrayList<>();
        if (!CollectionUtils.isEmpty(generalDeviceDTOList)) {
            for (GeneralDeviceDTO generalDeviceDTO : generalDeviceDTOList) {
                IntegrityIconVO outParam = new IntegrityIconVO();
                List<String> lineIndexes = generalDeviceDTO.getLineIndexes();
                if (CollectionUtils.isEmpty(lineIndexes)) {
                    continue;
                }
                outParam.setType(generalDeviceDTO.getName() + "\n(" + generalDeviceDTO.getLineIndexes().size() + ")");
                //根据监测点查询数据完整性
                List<PublicDTO> integrityData = getCondition(lineIndexes, integrityIconParam.getSearchBeginTime(), integrityIconParam.getSearchEndTime());
                // 汇总所有监测点的实际时间和期望时间，再计算总完整性
                int totalRealTime = (int) integrityData.stream().mapToLong(PublicDTO::getOnlineMin).sum();
                int totalDueTime = (int) integrityData.stream().mapToLong(PublicDTO::getOfflineMin).sum();
                double v = DataStatisticsUtil.calculateIntegrityRate(totalRealTime, totalDueTime);
                outParam.setSingle(v);
                //如果存在需要比较的时间，再获取对应数据
                if (StrUtil.isNotBlank(integrityIconParam.getPeriodBeginTime()) && StrUtil.isNotBlank(integrityIconParam.getPeriodEndTime())) {
                    List<PublicDTO> compareData = getCondition(lineIndexes, integrityIconParam.getPeriodBeginTime(), integrityIconParam.getPeriodEndTime());
                    // 汇总所有监测点的实际时间和期望时间，再计算总完整性
                    int compareRealTime = (int) compareData.stream().mapToLong(PublicDTO::getOnlineMin).sum();
                    int compareDueTime = (int) compareData.stream().mapToLong(PublicDTO::getOfflineMin).sum();
                    double v1 = DataStatisticsUtil.calculateIntegrityRate(compareRealTime, compareDueTime);
                    outParam.setRatio(v1);
                }
                out.add(outParam);
            }
        }
        out.sort(new Comparator<IntegrityIconVO>() {
            @Override
            public int compare(IntegrityIconVO o1, IntegrityIconVO o2) {
                Comparator<Object> com = Collator.getInstance(Locale.CHINA);
                return com.compare(o1.getType(), o2.getType());
            }
        });
        return out;
    }

    @Override
    public List<LineIntegrityDataVO> getEnterpriseIntegrityData(LineIntegrityDataParam lineIntegrityDataParam) {

        // 获取所有数据
        List<GeneralDeviceDTO> generalDeviceDTOList = generalDeviceService.getDeviceInfo(lineIntegrityDataParam, Stream.of(0).collect(Collectors.toList()), Stream.of(1).collect(Collectors.toList()));

        // 判断所有数据集合状态
        if (CollectionUtil.isNotEmpty(generalDeviceDTOList)) {

            // 创建集合返回数据
            List<LineIntegrityDataVO> pro = new ArrayList<>();

            // 获取告警策略列表
            List<AlarmStrategyVO> alarmStrategyVos = alarmClient.getAlarmStrategyData().getData();
            // 判断告警策略数据状态
            if (CollectionUtil.isEmpty(alarmStrategyVos)) {
                throw new BusinessException(DeviceResponseEnum.QUERY_ALARMSTRATEGY_DATA_EMPTY);
            }
            List<AlarmStrategyVO> alarmAlgoDescribe = lineIntegrityDataMapper.getAlarmAlgoDescribe(alarmStrategyVos);
            Map<Integer, Integer> mapAlarm = alarmAlgoDescribe.stream().collect(Collectors.toMap(AlarmStrategyVO::getAlgoDescribe, AlarmStrategyVO::getIntegrityValue));

            Map<String, Integer> mapA = alarmStrategyVos.stream().collect(Collectors.toMap(AlarmStrategyVO::getId, AlarmStrategyVO::getIntegrityValue));


            // 遍历集合
            for (GeneralDeviceDTO generalDeviceDTO : generalDeviceDTOList) {

                // 判断监测点索引集合状态
                if (CollectionUtils.isEmpty(generalDeviceDTO.getLineIndexes())) {
                    continue;
                }

                // 创建实体类
                LineIntegrityDataVO lineIntegrityDataVO = new LineIntegrityDataVO();

                // 通过监测点索引查询监测点信息
                List<LineIntegrityDataVO> lineList = lineIntegrityDataMapper.getDetailedParametersForLine(generalDeviceDTO.getLineIndexes(), lineIntegrityDataParam.getLineGrade());
                List<String> lineIds = lineList.stream().map(LineIntegrityDataVO::getId).distinct().collect(Collectors.toList());

                // 通过供电站索引查询供电站信息
                List<LineIntegrityDataVO> subList = lineIntegrityDataMapper.getSubList(lineIds);


                // 查询监测点数据完整性
                List<LineDataIntegrity> percentageOfCompleteDatas = rStatIntegrityDMapper.getLineIntegrityRate(generalDeviceDTO.getLineIndexes(), lineIntegrityDataParam.getSearchBeginTime(), lineIntegrityDataParam.getSearchEndTime());

                for (LineIntegrityDataVO lineDataIntegrity : lineList) {
                    boolean flag = false;
                    for (LineDataIntegrity lineData : percentageOfCompleteDatas) {
                        if (lineDataIntegrity.getId().equals(lineData.getLineId())) {
                            flag = true;
                            lineDataIntegrity.setRealTime(lineData.getReal() == null ? 0 : lineData.getReal().intValue());
                            lineDataIntegrity.setDueTime(lineData.getDue() == null ? 0 : lineData.getDue().intValue());
                            Double temValue = DataStatisticsUtil.calculateIntegrityRate(lineDataIntegrity.getRealTime(), lineDataIntegrity.getDueTime());
                            lineDataIntegrity.setIntegrityData(temValue);
                            //根据等级判断是否越限
                            if (StrUtil.isNotBlank(lineDataIntegrity.getLineGrade())) {
                                if (mapA.containsKey(lineDataIntegrity.getLineGrade())) {
                                    if (temValue != 3.14159 && temValue > mapA.get(lineDataIntegrity.getLineGrade())) {
                                        lineDataIntegrity.setValueOver(1);
                                    } else {
                                        lineDataIntegrity.setValueOver(0);
                                    }
                                } else {
                                    throw new BusinessException(DeviceResponseEnum.LINE_GRADE_LESS);
                                }
                            } else {
                                //默认没有设置等级的监测点标志为1  0.不合格 1.合格
                                lineDataIntegrity.setValueOver(1);
                            }
                            break;
                        }
                    }
                    if (!flag) {
                        //表示未匹配到数据完整性
                        lineDataIntegrity.setIntegrityData(3.14159);
                        lineDataIntegrity.setRealTime(0);
                        lineDataIntegrity.setDueTime(0);
                        lineDataIntegrity.setValueOver(0);
                    }
                }

                //处理变电站
                dealEnterpriseChildrenData(subList, lineList, true);
                lineIntegrityDataVO.setChildren(subList);

                // 数据封装
                // 汇总所有监测点的实际时间和期望时间，重新计算完整性
                int totalRealTime = (int) lineList.stream().filter(item -> item.getIntegrityData() != 3.14159).mapToLong(LineIntegrityDataVO::getRealTime).sum();
                int totalDueTime = (int) lineList.stream().filter(item -> item.getIntegrityData() != 3.14159).mapToLong(LineIntegrityDataVO::getDueTime).sum();
                lineIntegrityDataVO.setRealTime(totalRealTime);
                lineIntegrityDataVO.setDueTime(totalDueTime);
                lineIntegrityDataVO.setIntegrityData(DataStatisticsUtil.calculateIntegrityRate(totalRealTime, totalDueTime));
                LineIntegrityDataVO temp = lineList.stream().filter(t -> t.getAlgoDescribe() != null).min(Comparator.comparing(LineIntegrityDataVO::getAlgoDescribe)).orElse(new LineIntegrityDataVO());
                lineIntegrityDataVO.setAlgoDescribe(temp.getAlgoDescribe());
                lineIntegrityDataVO.setId(generalDeviceDTO.getIndex());
                lineIntegrityDataVO.setName(generalDeviceDTO.getName());
                lineIntegrityDataVO.setLevel(0);
                pro.add(lineIntegrityDataVO);

            }

            getAreaIntegrityData(mapAlarm, pro);
            return pro;
        } else {
            return new ArrayList<>();
        }
    }


    /**
     * 处理变电站
     *
     * @param targetData   父集合
     * @param childrenData 子集合
     * @param isLine       处理策略
     */
    private void dealEnterpriseChildrenData(List<LineIntegrityDataVO> targetData, List<LineIntegrityDataVO> childrenData, boolean isLine) {
        // 创建一个map集合，用于封装对象
        Map<String, List<LineIntegrityDataVO>> groupLine;
        if (isLine) {
            // 通过stream流分组
            groupLine = childrenData.stream().collect(Collectors.groupingBy(lineAdministrationTree -> {
                // 获取父id字符串，通过 逗号 分割 成一个数组
                String[] pid = lineAdministrationTree.getPids().split(",");
                // 判断集合索引为3的元素
                return pid[LineBaseEnum.SUB_LEVEL.getCode()];
            }));
        } else {
            groupLine = childrenData.stream().collect(Collectors.groupingBy(LineIntegrityDataVO::getPid));
        }
        targetData = targetData.stream().peek(lineAdministrationTree -> {
            Set<String> pids = groupLine.keySet();
            for (String pid : pids) {
                if (lineAdministrationTree.getId().equals(pid)) {
                    List<LineIntegrityDataVO> lineIntegrityDataVOList = groupLine.get(pid);
                    //父级完整性匹配 - 汇总子节点的实际时间和期望时间，重新计算完整性
                    int totalRealTime = (int) lineIntegrityDataVOList.stream().filter(item -> item.getIntegrityData() != 3.14159).mapToLong(LineIntegrityDataVO::getRealTime).sum();
                    int totalDueTime = (int) lineIntegrityDataVOList.stream().filter(item -> item.getIntegrityData() != 3.14159).mapToLong(LineIntegrityDataVO::getDueTime).sum();
                    lineAdministrationTree.setRealTime(totalRealTime);
                    lineAdministrationTree.setDueTime(totalDueTime);
                    lineAdministrationTree.setIntegrityData(DataStatisticsUtil.calculateIntegrityRate(totalRealTime, totalDueTime));
                    LineIntegrityDataVO temp = lineIntegrityDataVOList.stream().filter(t -> t.getAlgoDescribe() != null).min(Comparator.comparing(LineIntegrityDataVO::getAlgoDescribe)).orElse(new LineIntegrityDataVO());
                    lineAdministrationTree.setAlgoDescribe(temp.getAlgoDescribe());
                }
            }
        }).collect(Collectors.toList());
    }


    private List<PublicDTO> getCondition(List<String> lineList, String startTime, String endTime) {
        List<PublicDTO> integrityList = new ArrayList<>();
        OnlineRateParam param = new OnlineRateParam();
        param.setIds(lineList);
        param.setStartTime(DateUtil.beginOfDay(DateUtil.parse(startTime)).toString());
        param.setEndTime(DateUtil.endOfDay(DateUtil.parse(endTime)).toString());
        List<RStatIntegrityVO> data = rStatIntegrityDMapper.getOnIntegrityByIds(param);
        if (!CollectionUtils.isEmpty(data)) {
            data.forEach(po -> {
                PublicDTO publicDTO = new PublicDTO();
                publicDTO.setId(po.getLineIndex());
                publicDTO.setOnlineMin(po.getRealTime() == null ? 0 : po.getRealTime().intValue());
                publicDTO.setOfflineMin(po.getDueTime() == null ? 0 : po.getDueTime().intValue());
                // 计算数据完整性
                Double integrity = DataStatisticsUtil.calculateIntegrityRate(publicDTO.getOnlineMin(), publicDTO.getOfflineMin());
                publicDTO.setData(integrity);
                integrityList.add(publicDTO);
            });
        }
        return integrityList;
    }

    public void getAreaIntegrityData(Map<Integer, Integer> mapAlarm, List<LineIntegrityDataVO> proList) {
        for (LineIntegrityDataVO proItem : proList) {
            List<LineIntegrityDataVO> gds = proItem.getChildren();
            if (CollectionUtil.isNotEmpty(gds)) {
                for (LineIntegrityDataVO gdItem : gds) {
                    List<LineIntegrityDataVO> subs = gdItem.getChildren();
                    if (CollectionUtil.isNotEmpty(subs)) {
                        for (LineIntegrityDataVO subItem : subs) {
                            if (Objects.nonNull(subItem.getAlgoDescribe())) {
                                if (mapAlarm.containsKey(subItem.getAlgoDescribe())) {
                                    if (subItem.getIntegrityData() != 3.14159 && subItem.getIntegrityData() < mapAlarm.get(subItem.getAlgoDescribe())) {
                                        subItem.setValueOver(1);
                                    } else {
                                        subItem.setValueOver(0);
                                    }
                                }
                            }
                        }
                    }
                    if (Objects.nonNull(gdItem.getAlgoDescribe())) {
                        if (mapAlarm.containsKey(gdItem.getAlgoDescribe())) {
                            if (gdItem.getIntegrityData() != 3.14159 && gdItem.getIntegrityData() < mapAlarm.get(gdItem.getAlgoDescribe())) {
                                gdItem.setValueOver(1);
                            } else {
                                gdItem.setValueOver(0);
                            }
                        }
                    }
                }
            }
            if (Objects.nonNull(proItem.getAlgoDescribe())) {
                if (mapAlarm.containsKey(proItem.getAlgoDescribe())) {
                    if (proItem.getIntegrityData() != 3.14159 && proItem.getIntegrityData() < mapAlarm.get(proItem.getAlgoDescribe())) {
                        proItem.setValueOver(1);
                    } else {
                        proItem.setValueOver(0);
                    }
                }
            }
        }
    }

    /**
     * 处理变电站
     *
     * @param targetData   父集合
     * @param childrenData 子集合
     * @param isLine       处理策略
     */
    /**
     * 处理变电站
     *
     * @param targetData   父集合
     * @param childrenData 子集合
     * @param isLine       处理策略
     */
/*
    private void dealChildrenData(List<LineIntegrityDataVO> targetData, List<LineIntegrityDataVO> childrenData, boolean isLine) {
        // 创建一个map集合，用于封装对象
        Map<String, List<LineIntegrityDataVO>> groupLine;
        if (isLine) {
            // 通过stream流分组
            groupLine = childrenData.stream().collect(Collectors.groupingBy(lineAdministrationTree -> {
                // 获取父id字符串，通过 逗号 分割 成一个数组
                String[] pid = lineAdministrationTree.getPids().split(",");
                // 判断集合索引为3的元素
                return pid[LineBaseEnum.SUB_LEVEL.getCode()];
            }));
        } else {
            groupLine = childrenData.stream().collect(Collectors.groupingBy(LineIntegrityDataVO::getPid));
        }
        targetData = targetData.stream().peek(lineAdministrationTree -> {
            Set<String> pids = groupLine.keySet();
            for (String pid : pids) {
                if (lineAdministrationTree.getId().equals(pid)) {
                    List<LineIntegrityDataVO> lineIntegrityDataVOList = groupLine.get(pid);
                    lineAdministrationTree.setChildren(lineIntegrityDataVOList);
                    //父级完整性匹配
                    Double temValue = lineIntegrityDataVOList.stream().filter(item -> item.getIntegrityData() != 3.14159).mapToDouble(LineIntegrityDataVO::getIntegrityData).average().orElse(3.14159);
                    lineAdministrationTree.setIntegrityData(DataStatisticsUtil.dataLimits(temValue));
                    LineIntegrityDataVO temp = lineIntegrityDataVOList.stream().filter(t -> t.getAlgoDescribe() != null).min(Comparator.comparing(LineIntegrityDataVO::getAlgoDescribe)).orElse(new LineIntegrityDataVO());
                    lineAdministrationTree.setAlgoDescribe(temp.getAlgoDescribe());
                }
            }
        }).collect(Collectors.toList());
    }
*/


    /**
     * 处理子集
     *
     * @param targetData   父集合
     * @param powerChildren 子集合
     * @param isLine       处理策略
     */
    private void dealChildrenData(List<LineIntegrityDataVO> targetData, List<LineIntegrityDataVO> powerChildren,Map<String,List<LineIntegrityDataVO>> userStationMap, boolean isLine) {
        // 创建一个map集合，用于封装对象
        Map<String, List<LineIntegrityDataVO>> groupLine;
        if (isLine) {
            // 通过stream流分组
            groupLine = powerChildren.stream().collect(Collectors.groupingBy(lineAdministrationTree -> {
                // 获取父id字符串，通过 逗号 分割 成一个数组
                String[] pid = lineAdministrationTree.getPids().split(StrUtil.COMMA);
                // 判断集合索引为3的元素
                return pid[LineBaseEnum.SUB_LEVEL.getCode()];
            }));
        } else {
            groupLine = powerChildren.stream().collect(Collectors.groupingBy(LineIntegrityDataVO::getPid));
        }
        targetData.forEach(lineAdministrationTree -> {
            List<LineIntegrityDataVO> temList = new ArrayList<>();
            if(groupLine.containsKey(lineAdministrationTree.getId())){
                temList.addAll(groupLine.get(lineAdministrationTree.getId()));
            }
            if(isLine){
                if(userStationMap.containsKey(lineAdministrationTree.getId())){
                    temList.addAll(userStationMap.get(lineAdministrationTree.getId()));
                }
            }
            lineAdministrationTree.setChildren(temList);
            dealDataJinDu(temList,lineAdministrationTree);

        });
    }

}
