package com.njcn.harmonic.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
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.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.config.GeneralInfo;
import com.njcn.common.pojo.constant.BizParamConstant;
import com.njcn.common.pojo.dto.SimpleDTO;
import com.njcn.common.pojo.enums.common.ServerEnum;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.utils.PubUtils;
import com.njcn.device.biz.commApi.CommLineClient;
import com.njcn.device.biz.commApi.CommTerminalGeneralClient;
import com.njcn.device.biz.pojo.dto.*;
import com.njcn.device.biz.pojo.param.DeptGetLineParam;
import com.njcn.device.pms.api.MonitorClient;
import com.njcn.device.pms.api.PmsGeneralDeviceInfoClient;
import com.njcn.device.pms.api.StatationStatClient;
import com.njcn.device.pms.pojo.dto.PmsGeneralDeviceDTO;
import com.njcn.device.pms.pojo.dto.PmsStatationStatInfoDTO;
import com.njcn.device.pms.pojo.param.PmsDeviceInfoParam;
import com.njcn.device.pms.pojo.param.PmsStatationStatInfoParam;
import com.njcn.device.pms.pojo.po.Monitor;
import com.njcn.device.pq.api.GeneralDeviceInfoClient;
import com.njcn.device.pq.api.LineFeignClient;
import com.njcn.device.pq.api.SubstationFeignClient;
import com.njcn.device.pq.api.UserLedgerFeignClient;
import com.njcn.device.pq.enums.LineBaseEnum;
import com.njcn.device.pq.enums.PowerFlagEnum;
import com.njcn.device.pq.pojo.dto.*;
import com.njcn.device.pq.pojo.param.DeviceInfoParam;
import com.njcn.device.pq.pojo.param.GridDiagramParam;
import com.njcn.device.pq.pojo.param.LineBaseQueryParam;
import com.njcn.device.pq.pojo.param.OnlineRateParam;
import com.njcn.device.pq.pojo.po.Line;
import com.njcn.device.pq.pojo.po.LineDetail;
import com.njcn.device.pq.pojo.vo.GridDiagramVO;
import com.njcn.device.pq.pojo.vo.RStatIntegrityVO;
import com.njcn.device.pq.pojo.vo.RStatOnlineRateVO;
import com.njcn.event.api.RmpEventDetailFeignClient;
import com.njcn.event.pojo.dto.EventCount;
import com.njcn.harmonic.mapper.*;
import com.njcn.harmonic.pojo.dto.PublicDTO;
import com.njcn.harmonic.pojo.excel.pollution.*;
import com.njcn.harmonic.pojo.param.HarmonicPublicParam;
import com.njcn.harmonic.pojo.param.PollutionSubstationQuryParam;
import com.njcn.harmonic.pojo.param.StatSubstationBizBaseParam;
import com.njcn.harmonic.pojo.po.*;
import com.njcn.harmonic.pojo.po.day.RStatLimitRateDPO;
import com.njcn.harmonic.pojo.vo.PollutionSubstationVO;
import com.njcn.harmonic.pojo.vo.PollutionVO;
import com.njcn.harmonic.pojo.vo.SubstationVo;
import com.njcn.harmonic.common.mapper.RStatLimitRateDMapper;
import com.njcn.harmonic.service.PollutionSubstationService;
import com.njcn.poi.excel.ExcelUtil;
import com.njcn.supervision.pojo.param.SensitiveUserParam;
import com.njcn.supervision.pojo.param.user.UserReportParam;
import com.njcn.supervision.pojo.po.user.UserReportPO;
import com.njcn.supervision.pojo.vo.user.NewUserReportVO;
import com.njcn.supervision.pojo.vo.user.UserLedgerVO;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.user.pojo.dto.DeptDTO;
import com.njcn.user.pojo.po.Dept;
import com.njcn.web.utils.RequestUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;


/**
 * Description:
 * 接口文档访问地址：http://serverIP:port/swagger-ui.html
 * Date: 2022/10/13  8:56【需求编号】
 *
 * @author clam
 * @version V1.0.0
 */
@Slf4j
@Service
@AllArgsConstructor
public class PollutionSubstationServiceImpl extends ServiceImpl<RStatPollutionSubstationMMapper, RStatPollutionSubstationM> implements PollutionSubstationService {


    private final SubstationFeignClient substationFeignClient;

    private final PmsGeneralDeviceInfoClient pmsGeneralDeviceInfoClient;
    private final StatationStatClient statationStatClient;
    private final MonitorClient monitorClient;
    private final DeptFeignClient deptFeignClient;

    private final RStatPollutionSubstationMMapper pollutionSubstationMMapper;
    private final RStatPollutionSubstationYPOMapper pollutionSubstationYPOMapper;
    private final RStatPollutionSubstationQPOMapper pollutionSubstationQPOMapper;
    private final RStatPollutionSubstationDPOMapper pollutionSubstationDPOMapper;


    private final GeneralDeviceInfoClient generalDeviceInfoClient;
    private final LineFeignClient lineFeignClient;
    private final GeneralInfo generalInfo;


    private final RStatPollutionOrgMPOMapper rStatPollutionOrgMPOMapper;
    private final RStatPollutionOrgYPOMapper rStatPollutionOrgYPOMapper;
    private final RStatPollutionOrgQPOMapper rStatPollutionOrgQPOMapper;
    private final RStatPollutionOrgDPOMapper rStatPollutionOrgDPOMapper;

    private final RMpPollutionDPOMapper rMpPollutionDPOMapper;
    private final CommTerminalGeneralClient commTerminalGeneralClient;
    private final DicDataFeignClient dicDataFeignClient;
    private final RStatLimitRateDMapper rStatLimitRateDMapper;
    private final UserLedgerFeignClient userLedgerFeignClient;
    private final RmpEventDetailFeignClient detailFeignClient;
    private final CommLineClient commLineClient;

    /**
     * @param pollutionSubstationQuryParam
     * @Description: getPollutionSubstationData
     * @Param: [pollutionSubstationQuryParam]
     * @return: java.util.List<com.njcn.harmonic.pojo.vo.PollutionSubstationVO>
     * @Author: clam
     * @Date: 2022/10/13
     */
    @Override
    public List<PollutionSubstationVO> getPollutionSubstationData(PollutionSubstationQuryParam pollutionSubstationQuryParam) {

        List<PollutionSubstationVO> pollutionSubstationVOList = new ArrayList<>();
        /*根据部门获取变电站详情*/
        HarmonicPublicParam harmonicPublicParam = new HarmonicPublicParam();
        BeanUtils.copyProperties(pollutionSubstationQuryParam, harmonicPublicParam);
        harmonicPublicParam.setServerName(generalInfo.getMicroServiceName());
        List<PollutionSubstationDTO> pollutionSubstationDTOList = new ArrayList<>();
        List<GeneralDeviceDTO> sub = generalDeviceInfoClient.getPracticalRunDeviceInfoAsSubstation(harmonicPublicParam).getData();

        sub.forEach(item -> {
            PollutionSubstationDTO pollutionSubstationDTO = lineFeignClient.getSubstationInfo(item.getIndex()).getData();

            pollutionSubstationDTOList.add(pollutionSubstationDTO);
        });
        List<String> collect = pollutionSubstationDTOList.stream().map(PollutionSubstationDTO::getId).collect(Collectors.toList());
        List<SubstationDTO> locationData = substationFeignClient.getSubstationById(collect).getData();
        /*todo 后期可以把locationData存入redis*/
        /*把所有的变电站的污染指数查出来*/
        QueryWrapper<RStatPollutionSubstationM> wrapper = new QueryWrapper<>();
        wrapper.in("substation_id", collect).
                eq("pollution_type", pollutionSubstationQuryParam.getPollutionStatis().getId()).
                eq("DATE_FORMAT( data_date ,'%Y-%m')", pollutionSubstationQuryParam.getLocalDate());
        List<RStatPollutionSubstationM> rStatPollutionSubstationMList = pollutionSubstationMMapper.selectList(wrapper);

        pollutionSubstationDTOList.forEach(substationInfo -> {

            Integer lineCount = lineFeignClient.getLineCountBySubstation(substationInfo.getId()).getData();
            Integer deviceCount = lineFeignClient.getDeviceCountBySubstation(substationInfo.getId()).getData();
            PollutionSubstationVO pollutionSubstationVO = new PollutionSubstationVO();
            pollutionSubstationVO.setSubstationId(substationInfo.getId());
            pollutionSubstationVO.setSubstationName(substationInfo.getName());
            pollutionSubstationVO.setDeviceCount(deviceCount);
            pollutionSubstationVO.setLineCount(lineCount);
            /*todo 添加经纬度接口返回数据暂时没有*/
            List<SubstationDTO> substationDTOList = locationData.stream()
                    .filter(temp -> Objects.equals(substationInfo.getId(), temp.getId()))
                    .collect(Collectors.toList());

            SubstationDTO substationDTO = new SubstationDTO();
            if (CollectionUtils.isEmpty(substationDTOList)) {
                throw new BusinessException(CommonResponseEnum.INTERNAL_ERROR);
            } else {
                substationDTO = substationDTOList.get(0);
            }

            pollutionSubstationVO.setLatitude(substationDTO.getLat());
            pollutionSubstationVO.setLongitude(substationDTO.getLng());

            List<RStatPollutionSubstationM> rStatPollutionSubstationMS = rStatPollutionSubstationMList.stream().
                    filter(temp -> Objects.equals(substationInfo.getId(), temp.getSubstationId()))
                    .collect(Collectors.toList());

            Double value = 3.14159;
            if (!CollectionUtils.isEmpty(rStatPollutionSubstationMS)) {
                value = rStatPollutionSubstationMS.get(0).getValue();
            }
            pollutionSubstationVO.setPollutionData(value);
            pollutionSubstationVO.setPollutionStatis(pollutionSubstationQuryParam.getStatisticalType().getName());
            pollutionSubstationVOList.add(pollutionSubstationVO);
        });
        List<PollutionSubstationVO> result = pollutionSubstationVOList.stream().sorted(Comparator.comparing(PollutionSubstationVO::getPollutionData).reversed()).collect(Collectors.toList());

        return result;
    }


    /**
     * @Description: getDeptSubstationRelations
     * @Param: [param]
     * @return: java.util.List<com.njcn.harmonic.pojo.vo.PollutionVO>
     * @Author: clam
     * @Date: 2022/11/3
     */
    @Override
    public List<PollutionVO> getDeptSubstationRelations(HarmonicPublicParam harmonicPublicParam) {
        List<PollutionVO> list = new ArrayList<>();
        String pollutionType = harmonicPublicParam.getStatisticalType().getId();
        String searchBeginTime = harmonicPublicParam.getSearchBeginTime().substring(0, 10);
        if (StringUtils.isBlank(RequestUtil.getDeptIndex())) {
            return list;
        }

        List<UserLedgerVO> userLedgerVOList = userLedgerFeignClient.selectUserList(new UserReportParam()).getData();
        Map<String, UserLedgerVO> userLedgerVOMap = userLedgerVOList.stream().collect(Collectors.toMap(UserLedgerVO::getId, Function.identity()));

        if (harmonicPublicParam.getType() != 0) {
     /*       PmsDeviceInfoParam pmsDeviceInfoParam = new PmsDeviceInfoParam();
            pmsDeviceInfoParam.setDeptIndex(harmonicPublicParam.getDeptIndex());
            //获取统计类型
            pmsDeviceInfoParam.setStatisticalType(harmonicPublicParam.getStatisticalType());
            //获取主网台账信息
            List<PmsGeneralDeviceDTO> orgList = pmsGeneralDeviceInfoClient.getPmsDeviceInfoWithInOrg(pmsDeviceInfoParam).getData();
            orgList.forEach(temp -> {
                PollutionVO pollutionVO = new PollutionVO();
                String detpid = temp.getIndex();
                String name = temp.getName();
                List<String> powers = temp.getPowerrIdList();
                pollutionVO.setId(detpid);
                pollutionVO.setName(name + "\n(" + temp.getMonitorIdList().size() + ")");
                pollutionVO.setData(3.14159);
                setData(harmonicPublicParam, pollutionType, searchBeginTime, harmonicPublicParam.getSearchEndTime(), pollutionVO, detpid);
                if (CollectionUtil.isNotEmpty(powers)) {
                    //子集变电站
                    List<PollutionVO> powersVO = new ArrayList<>();
                    PmsStatationStatInfoParam param = new PmsStatationStatInfoParam();
                    param.setPowerIds(powers);
                    List<PmsStatationStatInfoDTO> data = statationStatClient.getStatationStatInfo(param).getData();
                    //去重解决重复数据
                    ArrayList<PmsStatationStatInfoDTO> dsData = data.stream().collect(Collectors.collectingAndThen
                            (Collectors.toCollection(() ->
                                    new TreeSet<>(Comparator.comparing(o -> o.getPowerId()))), ArrayList::new));
                    Map<String, Double> stringDoubleMap = setPmsSubData(harmonicPublicParam, pollutionType, searchBeginTime, powers);
                    if (CollectionUtil.isNotEmpty(data)) {
                        dsData.forEach(power -> {
                            PollutionVO pollutionsubVO = new PollutionVO();
                            pollutionsubVO.setId(power.getPowerId());
                            pollutionsubVO.setName(power.getPowerName());
                            pollutionsubVO.setPid(temp.getIndex());
                            if (CollectionUtil.isNotEmpty(stringDoubleMap)) {
                                if (stringDoubleMap.containsKey(power.getPowerId())) {
                                    pollutionsubVO.setData(stringDoubleMap.get(power.getPowerId()));
                                }
                            }
                            powersVO.add(pollutionsubVO);
                        });
                    }
                    powersVO.sort((item1, item2) -> item2.getData().compareTo(item1.getData()));
                    pollutionVO.setChildren(powersVO);
                }
                list.add(pollutionVO);
            });*/

        } else {
            harmonicPublicParam.setServerName(generalInfo.getMicroServiceName());
            List<GeneralDeviceDTO> sub = generalDeviceInfoClient.getPracticalRunDeviceInfo(harmonicPublicParam).getData();
            for (GeneralDeviceDTO temp : sub) {
                List<String> subIndexes = temp.getSubIndexes();
                if (CollectionUtil.isEmpty(subIndexes)) {
                    continue;
                }
                PollutionVO pollutionVO = new PollutionVO();
                String detpid = temp.getIndex();
                String name = temp.getName();

                pollutionVO.setId(detpid);
                pollutionVO.setName(name + "\n(" + temp.getLineIndexes().size() + ")");
                pollutionVO.setData(3.14159);
                setData(harmonicPublicParam, pollutionType, searchBeginTime, harmonicPublicParam.getSearchEndTime(), pollutionVO, detpid);


                List<PollutionVO> subPollutionVO = new ArrayList<>();
                List<LineDetail> lineDetailList = lineFeignClient.getLineDetail(temp.getLineIndexes()).getData();
                if (CollUtil.isNotEmpty(lineDetailList)) {
                    List<LineDetail> userLedgerList = lineDetailList.stream().filter(it -> StrUtil.isNotBlank(it.getObjId())).collect(Collectors.toList());
                    List<LineDetail> powerLedgerList = lineDetailList.stream().filter(it -> StrUtil.isBlank(it.getObjId())).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(userLedgerList)) {
                        List<String> objIds = userLedgerList.stream().map(LineDetail::getObjId).distinct().collect(Collectors.toList());
                        objIds.forEach(obj -> {
                            PollutionVO pollutionsubVO = new PollutionVO();
                            if (userLedgerVOMap.containsKey(obj)) {
                                UserLedgerVO userLedgerVO = userLedgerVOMap.get(obj);
                                pollutionsubVO.setId(userLedgerVO.getId());
                                pollutionsubVO.setName(userLedgerVO.getProjectName());
                                pollutionsubVO.setPid(temp.getIndex());
                                pollutionsubVO.setData(3.14159);
                                pollutionsubVO.setPowerFlag(PowerFlagEnum.NO_GRID_SIDE.getCode());
                                setSubData(harmonicPublicParam, pollutionType, searchBeginTime, harmonicPublicParam.getSearchEndTime(), pollutionsubVO, userLedgerVO.getId());
                                subPollutionVO.add(pollutionsubVO);
                            }
                        });
                    }

                    if (CollUtil.isNotEmpty(powerLedgerList)) {
                        List<String> ids = powerLedgerList.stream().map(LineDetail::getId).collect(Collectors.toList());
                        List<Line> lineList = lineFeignClient.getBaseLineList(ids).getData();
                        List<String> subIds = lineList.stream().map(it -> it.getPids().split(StrUtil.COMMA)[LineBaseEnum.SUB_LEVEL.getCode()]).distinct().collect(Collectors.toList());
                        List<Line> subList = lineFeignClient.getBaseLineList(subIds).getData();
                        subList.forEach(station -> {
                            PollutionVO pollutionsubVO = new PollutionVO();
                            pollutionsubVO.setId(station.getId());
                            pollutionsubVO.setName(station.getName());
                            pollutionsubVO.setPid(temp.getIndex());
                            pollutionsubVO.setPowerFlag(PowerFlagEnum.GRID_SIDE.getCode());
                            pollutionsubVO.setData(3.14159);
                            setSubData(harmonicPublicParam, pollutionType, searchBeginTime, harmonicPublicParam.getSearchEndTime(), pollutionsubVO, station.getId());
                            subPollutionVO.add(pollutionsubVO);
                        });

                    }

                }
                double exe = subPollutionVO.stream().mapToDouble(PollutionVO::getData).filter(it -> it != 3.14159).max().orElse(3.14159);
                pollutionVO.setData(exe);
                pollutionVO.setChildren(subPollutionVO);
                list.add(pollutionVO);
            }
        }
      /*  if (!CollectionUtils.isEmpty(list)) {
            List<PollutionVO> listSort = list.stream().filter(x -> x.getData() != 3.14159).sorted(Comparator.comparing(PollutionVO::getData).reversed().thenComparing(PollutionVO::getName)).collect(Collectors.toList());
            listSort.addAll(list.stream().filter(x -> x.getData() == 3.14159).collect(Collectors.toList()));
            return listSort;
        }*/
        return list;
    }

    private Map<String, Double> setPmsSubData(HarmonicPublicParam harmonicPublicParam, String pollutionType, String searchBeginTime, List<String> id) {
        if (Objects.equals(harmonicPublicParam.getReportFlag(), BizParamConstant.STAT_BIZ_YEAR)) {
            QueryWrapper<RStatPollutionSubstationYPO> wrapper = new QueryWrapper<>();
            wrapper.in("substation_id", id).
                    eq("pollution_type", pollutionType).
                    eq("DATE_FORMAT( data_date ,'%Y-%m-%d')", searchBeginTime);
            List<RStatPollutionSubstationYPO> s = pollutionSubstationYPOMapper.selectList(wrapper);
            return s.stream().collect(Collectors.toMap(RStatPollutionSubstationYPO::getSubstationId, RStatPollutionSubstationYPO::getValue));
        } else if (Objects.equals(harmonicPublicParam.getReportFlag(), BizParamConstant.STAT_BIZ_QUARTER)) {
            QueryWrapper<RStatPollutionSubstationQPO> wrapper = new QueryWrapper<>();
            wrapper.in("substation_id", id).
                    eq("pollution_type", pollutionType).
                    eq("DATE_FORMAT( data_date ,'%Y-%m-%d')", searchBeginTime);
            List<RStatPollutionSubstationQPO> s = pollutionSubstationQPOMapper.selectList(wrapper);
            return s.stream().collect(Collectors.toMap(RStatPollutionSubstationQPO::getSubstationId, RStatPollutionSubstationQPO::getValue));

        } else if (Objects.equals(harmonicPublicParam.getReportFlag(), BizParamConstant.STAT_BIZ_MONTH)) {
            QueryWrapper<RStatPollutionSubstationM> wrapper = new QueryWrapper<>();
            wrapper.in("substation_id", id).
                    eq("pollution_type", pollutionType).
                    eq("DATE_FORMAT( data_date ,'%Y-%m-%d')", searchBeginTime);
            List<RStatPollutionSubstationM> s = pollutionSubstationMMapper.selectList(wrapper);
            return s.stream().collect(Collectors.toMap(RStatPollutionSubstationM::getSubstationId, RStatPollutionSubstationM::getValue));
        } else if (Objects.equals(harmonicPublicParam.getReportFlag(), BizParamConstant.STAT_BIZ_DAY)) {
            QueryWrapper<RStatPollutionSubstationDPO> wrapper = new QueryWrapper<>();
            wrapper.in("substation_id", id).
                    eq("pollution_type", pollutionType).
                    eq("DATE_FORMAT( data_date ,'%Y-%m-%d')", searchBeginTime);
            List<RStatPollutionSubstationDPO> s = pollutionSubstationDPOMapper.selectList(wrapper);
            return s.stream().collect(Collectors.toMap(RStatPollutionSubstationDPO::getSubstationId, RStatPollutionSubstationDPO::getValue));
        }
        return null;
    }

    private void setSubData(HarmonicPublicParam harmonicPublicParam, String pollutionType, String searchBeginTime, String searchEndTime, PollutionVO pollutionsubVO, String id) {
        if (Objects.equals(harmonicPublicParam.getReportFlag(), BizParamConstant.STAT_BIZ_YEAR)) {
            QueryWrapper<RStatPollutionSubstationYPO> wrapper = new QueryWrapper<>();
            wrapper.eq("substation_id", id).
                    eq("pollution_type", pollutionType).
                    eq("DATE_FORMAT( data_date ,'%Y-%m-%d')", searchBeginTime);
            RStatPollutionSubstationYPO rStatPollutionSubstationYPO = pollutionSubstationYPOMapper.selectOne(wrapper);

            Optional.ofNullable(rStatPollutionSubstationYPO).ifPresent(a -> pollutionsubVO.setData(BigDecimal.valueOf(a.getValue()).setScale(2, RoundingMode.UP).doubleValue()));
        } else if (Objects.equals(harmonicPublicParam.getReportFlag(), BizParamConstant.STAT_BIZ_QUARTER)) {
            QueryWrapper<RStatPollutionSubstationQPO> wrapper = new QueryWrapper<>();
            wrapper.eq("substation_id", id).
                    eq("pollution_type", pollutionType).
                    eq("DATE_FORMAT( data_date ,'%Y-%m-%d')", searchBeginTime);
            RStatPollutionSubstationQPO rStatPollutionSubstationQPO = pollutionSubstationQPOMapper.selectOne(wrapper);

            Optional.ofNullable(rStatPollutionSubstationQPO).ifPresent(a -> pollutionsubVO.setData(BigDecimal.valueOf(a.getValue()).setScale(2, RoundingMode.UP).doubleValue()));
        } else if (Objects.equals(harmonicPublicParam.getReportFlag(), BizParamConstant.STAT_BIZ_MONTH)) {
            QueryWrapper<RStatPollutionSubstationM> wrapper = new QueryWrapper<>();
            wrapper.eq("substation_id", id).
                    eq("pollution_type", pollutionType).
                    eq("DATE_FORMAT( data_date ,'%Y-%m-%d')", searchBeginTime);
            RStatPollutionSubstationM rStatPollutionSubstationM = pollutionSubstationMMapper.selectOne(wrapper);

            Optional.ofNullable(rStatPollutionSubstationM).ifPresent(a -> pollutionsubVO.setData(BigDecimal.valueOf(a.getValue()).setScale(2, RoundingMode.UP).doubleValue()));

        } else if (Objects.equals(harmonicPublicParam.getReportFlag(), BizParamConstant.STAT_BIZ_DAY)) {
            QueryWrapper<RStatPollutionSubstationDPO> wrapper = new QueryWrapper<>();
            wrapper.eq("substation_id", id).
                    eq("pollution_type", pollutionType).
                    eq("DATE_FORMAT( data_date ,'%Y-%m-%d')", searchBeginTime);
            RStatPollutionSubstationDPO rStatPollutionSubstationDPO = pollutionSubstationDPOMapper.selectOne(wrapper);

            Optional.ofNullable(rStatPollutionSubstationDPO).ifPresent(a -> pollutionsubVO.setData(BigDecimal.valueOf(a.getValue()).setScale(2, RoundingMode.UP).doubleValue()));
        } else if (Objects.equals(harmonicPublicParam.getReportFlag(), BizParamConstant.STAT_BIZ_WEEK)) {
            QueryWrapper<RStatPollutionSubstationDPO> wrapper = new QueryWrapper<>();
            wrapper.eq("substation_id", id).
                    eq("pollution_type", pollutionType).
                    between("DATE_FORMAT( data_date ,'%Y-%m-%d')", searchBeginTime, searchEndTime)
                    .orderByDesc("value").last(" limit 1");
            RStatPollutionSubstationDPO rStatPollutionSubstationDPO = pollutionSubstationDPOMapper.selectOne(wrapper);
            Optional.ofNullable(rStatPollutionSubstationDPO).ifPresent(a -> pollutionsubVO.setData(BigDecimal.valueOf(a.getValue()).setScale(2, RoundingMode.UP).doubleValue()));

        }
    }

    private void setData(HarmonicPublicParam harmonicPublicParam, String pollutionType, String searchBeginTime, String searchEndTime, PollutionVO pollutionVO, String detpid) {

        if (Objects.equals(harmonicPublicParam.getReportFlag(), BizParamConstant.STAT_BIZ_YEAR)) {
            QueryWrapper<RStatPollutionOrgYPO> rStatPollutionOrgYPOQueryWrapper = new QueryWrapper<>();
            rStatPollutionOrgYPOQueryWrapper.eq("org_id", detpid).
                    eq("pollution_type", pollutionType).
                    eq("DATE_FORMAT( data_date ,'%Y-%m-%d')", searchBeginTime);
            RStatPollutionOrgYPO rStatPollutionOrgYPO = rStatPollutionOrgYPOMapper.selectOne(rStatPollutionOrgYPOQueryWrapper);
            Optional.ofNullable(rStatPollutionOrgYPO).ifPresent(a -> pollutionVO.setData(BigDecimal.valueOf(a.getValue()).setScale(2, RoundingMode.UP).doubleValue()));
        } else if (Objects.equals(harmonicPublicParam.getReportFlag(), BizParamConstant.STAT_BIZ_QUARTER)) {
            QueryWrapper<RStatPollutionOrgQPO> rStatPollutionOrgQPOQueryWrapper = new QueryWrapper<>();
            rStatPollutionOrgQPOQueryWrapper.eq("org_id", detpid).
                    eq("pollution_type", pollutionType).
                    eq("DATE_FORMAT( data_date ,'%Y-%m-%d')", searchBeginTime);
            RStatPollutionOrgQPO rStatPollutionOrgQPO = rStatPollutionOrgQPOMapper.selectOne(rStatPollutionOrgQPOQueryWrapper);
            Optional.ofNullable(rStatPollutionOrgQPO).ifPresent(a -> pollutionVO.setData(BigDecimal.valueOf(a.getValue()).setScale(2, RoundingMode.UP).doubleValue()));
        } else if (Objects.equals(harmonicPublicParam.getReportFlag(), BizParamConstant.STAT_BIZ_MONTH)) {
            QueryWrapper<RStatPollutionOrgMPO> rStatPollutionOrgMPOQueryWrapper = new QueryWrapper<>();
            rStatPollutionOrgMPOQueryWrapper.eq("org_id", detpid).
                    eq("pollution_type", pollutionType).
                    eq("DATE_FORMAT( data_date ,'%Y-%m-%d')", searchBeginTime);
            RStatPollutionOrgMPO rStatPollutionOrgMPO = rStatPollutionOrgMPOMapper.selectOne(rStatPollutionOrgMPOQueryWrapper);
            Optional.ofNullable(rStatPollutionOrgMPO).ifPresent(a -> pollutionVO.setData(BigDecimal.valueOf(a.getValue()).setScale(2, RoundingMode.UP).doubleValue()));
        } else if (Objects.equals(harmonicPublicParam.getReportFlag(), BizParamConstant.STAT_BIZ_DAY)) {
            QueryWrapper<RStatPollutionOrgDPO> rStatPollutionOrgDPOQueryWrapper = new QueryWrapper<>();
            rStatPollutionOrgDPOQueryWrapper.eq("org_id", detpid).
                    eq("pollution_type", pollutionType).
                    between("DATE_FORMAT( data_date ,'%Y-%m-%d')", searchBeginTime, searchEndTime)
                    .orderByDesc("value").last(" limit 1");
            RStatPollutionOrgDPO rStatPollutionOrgDPO = rStatPollutionOrgDPOMapper.selectOne(rStatPollutionOrgDPOQueryWrapper);
            Optional.ofNullable(rStatPollutionOrgDPO).ifPresent(a -> pollutionVO.setData(BigDecimal.valueOf(a.getValue()).setScale(2, RoundingMode.UP).doubleValue()));
        } else if (Objects.equals(harmonicPublicParam.getReportFlag(), BizParamConstant.STAT_BIZ_WEEK)) {
            QueryWrapper<RStatPollutionOrgDPO> rStatPollutionOrgDPOQueryWrapper = new QueryWrapper<>();
            rStatPollutionOrgDPOQueryWrapper.eq("org_id", detpid).
                    eq("pollution_type", pollutionType).
                    between("DATE_FORMAT( data_date ,'%Y-%m-%d')", searchBeginTime, searchEndTime)
                    .orderByDesc("value").last(" limit 1");
            RStatPollutionOrgDPO rStatPollutionOrgDPO = rStatPollutionOrgDPOMapper.selectOne(rStatPollutionOrgDPOQueryWrapper);
            Optional.ofNullable(rStatPollutionOrgDPO).ifPresent(a -> pollutionVO.setData(BigDecimal.valueOf(a.getValue()).setScale(2, RoundingMode.UP).doubleValue()));

        }
    }


    /**
     * @Description: getSubstationInfoById
     * @Param: [param]
     * @return: java.util.List<com.njcn.device.pq.pojo.dto.PollutionSubstationDTO>
     * @Author: clam
     * @Date: 2022/11/3
     */
    @Override
    public List<PollutionSubstationDTO> getSubstationInfoById(HarmonicPublicParam deptParam) {
        String pollutionType = deptParam.getStatisticalType().getId();
        String searchBeginTime = deptParam.getSearchBeginTime().substring(0, 10);
        if (deptParam.getType() != 0) {
            List<PollutionSubstationDTO> list = new ArrayList<>();

            //根据部门code获取部门id
            Dept dept = deptFeignClient.getDeptByCode(deptParam.getDeptIndex()).getData();
            if (ObjectUtil.isNull(dept)) {
                return list;
            }
            //获取统计类型
            PmsDeviceInfoParam pmsDeviceInfoParam = new PmsDeviceInfoParam();
            pmsDeviceInfoParam.setDeptIndex(dept.getId());
            pmsDeviceInfoParam.setStatisticalType(deptParam.getStatisticalType());
            //获取主网台账信息
            List<PmsGeneralDeviceDTO> deviceList = pmsGeneralDeviceInfoClient.getPmsDeviceInfoWithInOrg(pmsDeviceInfoParam).getData();
            deviceList.forEach(temp -> {
                List<String> powers = temp.getPowerrIdList();
                //变电站不为空
                if (CollectionUtil.isNotEmpty(powers)) {
                    PmsStatationStatInfoParam param = new PmsStatationStatInfoParam();
                    param.setPowerIds(powers);
                    List<PmsStatationStatInfoDTO> data = statationStatClient.getStatationStatInfo(param).getData();
                    //去重解决重复数据
                    ArrayList<PmsStatationStatInfoDTO> dsData = data.stream().collect(Collectors.collectingAndThen
                            (Collectors.toCollection(() ->
                                    new TreeSet<>(Comparator.comparing(PmsStatationStatInfoDTO::getPowerId))), ArrayList::new));
                    Map<String, Double> stringDoubleMap = setPmsSubData(deptParam, pollutionType, searchBeginTime, powers);
                    if (CollectionUtil.isNotEmpty(data)) {
                        dsData.forEach(power -> {
                            PollutionSubstationDTO dto = new PollutionSubstationDTO();
                            dto.setId(power.getPowerId());
                            dto.setName(power.getPowerName());
                            dto.setVoltageLevel(power.getPowerVoltageLevel());
                            if (CollectionUtil.isNotEmpty(stringDoubleMap)) {
                                if (stringDoubleMap.containsKey(power.getPowerId())) {
                                    dto.setData(stringDoubleMap.get(power.getPowerId()));
                                }
                            }
                            list.add(dto);
                        });
                    }
                }

            });
            if (!CollectionUtils.isEmpty(list)) {
                return list.stream().sorted(Comparator.comparing(PollutionSubstationDTO::getData).reversed().thenComparing(PollutionSubstationDTO::getName)).collect(Collectors.toList());
            }
        } else {
            List<PollutionSubstationDTO> list = new ArrayList<>();
            deptParam.setServerName(generalInfo.getMicroServiceName());
            List<GeneralDeviceDTO> sub = generalDeviceInfoClient.getPracticalRunDeviceInfoAsSubstation(deptParam).getData();
            List<String> lineIds = sub.stream().flatMap(dto -> dto.getLineIndexes().stream()).collect(Collectors.toList());
            if (CollUtil.isEmpty(lineIds)) {
                return list;
            }
            list = lineFeignClient.getPowerStationByMonitorIds(lineIds).getData();
            List<String> powerIds = list.stream().map(PollutionSubstationDTO::getId).collect(Collectors.toList());


            if (Objects.equals(deptParam.getReportFlag(), BizParamConstant.STAT_BIZ_YEAR)) {
                QueryWrapper<RStatPollutionSubstationYPO> wrapper = new QueryWrapper<>();
                wrapper.in("substation_id", powerIds).
                        eq("pollution_type", pollutionType).
                        eq("DATE_FORMAT( data_date ,'%Y-%m-%d')", searchBeginTime);
                List<RStatPollutionSubstationYPO> rStatPollutionSubstationYPO = pollutionSubstationYPOMapper.selectList(wrapper);
                Map<String, RStatPollutionSubstationYPO> yMap = rStatPollutionSubstationYPO.stream().collect(Collectors.toMap(RStatPollutionSubstationYPO::getSubstationId, Function.identity()));
                list.forEach(pollutionSubstationDTO -> {
                    if (yMap.containsKey(pollutionSubstationDTO.getId())) {
                        pollutionSubstationDTO.setData(yMap.get(pollutionSubstationDTO.getId()).getValue());
                    } else {
                        pollutionSubstationDTO.setData(3.14159);
                    }
                });
            } else if (Objects.equals(deptParam.getReportFlag(), BizParamConstant.STAT_BIZ_QUARTER)) {
                QueryWrapper<RStatPollutionSubstationQPO> wrapper = new QueryWrapper<>();
                wrapper.in("substation_id", powerIds).
                        eq("pollution_type", pollutionType).
                        eq("DATE_FORMAT( data_date ,'%Y-%m-%d')", searchBeginTime);
                List<RStatPollutionSubstationQPO> rStatPollutionSubstationQPO = pollutionSubstationQPOMapper.selectList(wrapper);
                Map<String, RStatPollutionSubstationQPO> qMap = rStatPollutionSubstationQPO.stream().collect(Collectors.toMap(RStatPollutionSubstationQPO::getSubstationId, Function.identity()));
                list.forEach(pollutionSubstationDTO -> {
                    if (qMap.containsKey(pollutionSubstationDTO.getId())) {
                        pollutionSubstationDTO.setData(qMap.get(pollutionSubstationDTO.getId()).getValue());
                    } else {
                        pollutionSubstationDTO.setData(3.14159);
                    }
                });
            } else if (Objects.equals(deptParam.getReportFlag(), BizParamConstant.STAT_BIZ_MONTH)) {
                QueryWrapper<RStatPollutionSubstationM> wrapper = new QueryWrapper<>();
                wrapper.in("substation_id", powerIds).
                        eq("pollution_type", pollutionType).
                        eq("DATE_FORMAT( data_date ,'%Y-%m-%d')", searchBeginTime);
                List<RStatPollutionSubstationM> rStatPollutionSubstationM = pollutionSubstationMMapper.selectList(wrapper);

                Map<String, RStatPollutionSubstationM> mMap = rStatPollutionSubstationM.stream().collect(Collectors.toMap(RStatPollutionSubstationM::getSubstationId, Function.identity()));
                list.forEach(pollutionSubstationDTO -> {
                    if (mMap.containsKey(pollutionSubstationDTO.getId())) {
                        pollutionSubstationDTO.setData(mMap.get(pollutionSubstationDTO.getId()).getValue());
                    } else {
                        pollutionSubstationDTO.setData(3.14159);
                    }
                });
            } else if (Objects.equals(deptParam.getReportFlag(), BizParamConstant.STAT_BIZ_DAY)) {
                QueryWrapper<RStatPollutionSubstationDPO> wrapper = new QueryWrapper<>();
                wrapper.in("substation_id", powerIds).
                        eq("pollution_type", pollutionType).
                        eq("DATE_FORMAT( data_date ,'%Y-%m-%d')", searchBeginTime);
                List<RStatPollutionSubstationDPO> rStatPollutionSubstationDPO = pollutionSubstationDPOMapper.selectList(wrapper);
                Map<String, RStatPollutionSubstationDPO> dMap = rStatPollutionSubstationDPO.stream().collect(Collectors.toMap(RStatPollutionSubstationDPO::getSubstationId, Function.identity()));
                list.forEach(pollutionSubstationDTO -> {
                    if (dMap.containsKey(pollutionSubstationDTO.getId())) {
                        pollutionSubstationDTO.setData(dMap.get(pollutionSubstationDTO.getId()).getValue());
                    } else {
                        pollutionSubstationDTO.setData(3.14159);
                    }
                });
            }
            if (!CollectionUtils.isEmpty(list)) {
                return list.stream().sorted(Comparator.comparing(PollutionSubstationDTO::getData).reversed().thenComparing(PollutionSubstationDTO::getName)).collect(Collectors.toList());
            }
        }
        return Collections.emptyList();
    }

    /**
     * @Description: getLineInfoById
     * @Param: [param]
     * @return: java.util.List<com.njcn.device.biz.pojo.dto.PollutionLineDTO>
     * @Author: clam
     * @Date: 2022/11/3
     */
    @Override
    public List<PollutionLineDTO> getLineInfoById(HarmonicPublicParam harmonicPublicParam) {
        harmonicPublicParam.setServerName(generalInfo.getMicroServiceName());
        List<PollutionLineDTO> list = new ArrayList<>();

        String pollutionType = harmonicPublicParam.getStatisticalType().getId();
        PollutionParamDTO paramDTO = new PollutionParamDTO();
        if (StringUtils.isBlank(RequestUtil.getDeptIndex())) {
            return list;
        }
        if (harmonicPublicParam.getType() != 0) {
            PmsStatationStatInfoParam param = new PmsStatationStatInfoParam();
            param.setPowerIds(Arrays.asList(harmonicPublicParam.getId()));
            //获取变电站详情
            List<PmsStatationStatInfoDTO> data = statationStatClient.getStatationStatInfo(param).getData();
            if (CollectionUtil.isNotEmpty(data)) {
                List<String> monitorId = data.stream().map(PmsStatationStatInfoDTO::getMonitorId).collect(Collectors.toList());
                List<RMpPollutionDPO> lineData = rMpPollutionDPOMapper.selectMaxList(monitorId, pollutionType, harmonicPublicParam.getSearchBeginTime(), harmonicPublicParam.getSearchEndTime());
                Map<String, Double> lineMap = lineData.stream().collect(Collectors.toMap(RMpPollutionDPO::getLineId, RMpPollutionDPO::getValue));
                PollutionLineDTO dto;
                for (PmsStatationStatInfoDTO power : data) {
                    dto = new PollutionLineDTO();
                    dto.setId(power.getMonitorId());
                    dto.setName(power.getMonitorName());
                    dto.setPowerCompany(power.getOrgName());
                    dto.setSubstation(power.getPowerName());
                    dto.setBusBar(power.getBusBarName());
                    dto.setSubstationId(power.getPowerId());
                    if (CollectionUtil.isNotEmpty(lineMap)) {
                        if (lineMap.containsKey(power.getMonitorId())) {
                            dto.setData(lineMap.get(power.getMonitorId()));
                        }
                    }
                    list.add(dto);
                }
            }
        } else {
            if (PowerFlagEnum.GRID_SIDE.getCode().equals(harmonicPublicParam.getPowerFlag())) {
                List<String> line = new ArrayList<>();
                List<GeneralDeviceDTO> sub = generalDeviceInfoClient.getPracticalRunDeviceInfoAsSubstation(harmonicPublicParam).getData();
                sub.forEach(item -> {
                    if (Objects.equals(harmonicPublicParam.getId(), item.getIndex())) {
                        if (!CollectionUtils.isEmpty(item.getLineIndexes())) {
                            line.addAll(item.getLineIndexes());
                        }
                    }
                });
                return commDataDeal(line, paramDTO, harmonicPublicParam);
            } else {
                List<LineDetail> lineDetailList = lineFeignClient.getMonitorByObjId(harmonicPublicParam.getId()).getData();
                if (CollUtil.isNotEmpty(lineDetailList)) {
                    List<String> ids = lineDetailList.stream().map(LineDetail::getId).collect(Collectors.toList());
                    return commDataDeal(ids, paramDTO, harmonicPublicParam);
                }
            }

        }
        return list;
    }


    private List<PollutionLineDTO> commDataDeal(List<String> ids, PollutionParamDTO paramDTO, HarmonicPublicParam harmonicPublicParam) {
        //添加非空判断
        if(CollectionUtils.isEmpty(ids)){
            return  new ArrayList<>();
        }
        paramDTO.setLineList(ids);
        List<PollutionLineDTO> list = lineFeignClient.getLineInfo(paramDTO).getData();
        List<RMpPollutionDPO> lineData = rMpPollutionDPOMapper.selectMaxList(ids, harmonicPublicParam.getStatisticalType().getId(), harmonicPublicParam.getSearchBeginTime(), harmonicPublicParam.getSearchEndTime());
        Map<String, RMpPollutionDPO> map = lineData.stream().collect(Collectors.toMap(RMpPollutionDPO::getLineId, Function.identity()));
        if (!CollectionUtils.isEmpty(lineData)) {
            list.stream().sorted(Comparator.comparing(PollutionLineDTO::getData).reversed().thenComparing(PollutionLineDTO::getName)).forEach(item -> {
                if (map.containsKey(item.getId())) {
                    item.setData(map.get(item.getId()).getValue());
                } else {
                    item.setData(3.14159);
                }
            });
        }
        return list;
    }


    @Override
    public List<PollutionLineDTO> getLineRankTop10(HarmonicPublicParam param) {
        List<PollutionLineDTO> list = new ArrayList<>();
        if (param.getType() == 0) {
            param.setServerName(generalInfo.getMicroServiceName());
            PollutionParamDTO paramDTO = new PollutionParamDTO();
            List<GeneralDeviceDTO> generalDeviceDTOList = generalDeviceInfoClient.getPracticalRunDeviceInfo(param).getData();
            List<String> ids = generalDeviceDTOList.stream().filter(it -> CollUtil.isNotEmpty(it.getLineIndexes())).flatMap(it -> it.getLineIndexes().stream()).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(ids)) {
                List<PublicDTO> result = rMpPollutionDPOMapper.getTop10Line(ids, DateUtil.beginOfDay(DateUtil.parse(param.getSearchBeginTime())), DateUtil.endOfDay(DateUtil.parse(param.getSearchEndTime())), param.getStatisticalType().getId());
                if (!CollectionUtils.isEmpty(result)) {
                    List<String> monitorIds = result.stream().map(PublicDTO::getId).distinct().collect(Collectors.toList());
                    paramDTO.setLineList(monitorIds);
                    List<PollutionLineDTO> monitorList = lineFeignClient.getLineInfo(paramDTO).getData();
                    Map<String, PollutionLineDTO> monitorMap = monitorList.stream().collect(Collectors.toMap(PollutionLineDTO::getId, Function.identity()));
                    List<String> objIds = monitorList.stream().map(PollutionLineDTO::getObjId).distinct().collect(Collectors.toList());
                    Map<String, String> objMap = new HashMap<>();
                    if(CollUtil.isNotEmpty(objIds)){
                       List<NewUserReportVO> userReportVOList = userLedgerFeignClient.getUserReportByIds(objIds).getData();
                        objMap = userReportVOList.stream().collect(Collectors.toMap(NewUserReportVO::getId, NewUserReportVO::getProjectName));
                    }
                    Map<String, String> finalObjMap = objMap;
                    list = result.stream().map(it -> {
                        PollutionLineDTO pollutionLineDTO = new PollutionLineDTO();
                        pollutionLineDTO.setData(NumberUtil.round(it.getData(), 2).doubleValue());
                        PollutionLineDTO monitor = monitorMap.get(it.getId());
                        if(StrUtil.isNotBlank(monitor.getObjId())){
                          String objName = finalObjMap.get(monitor.getObjId());
                          pollutionLineDTO.setName(objName + "_" + monitor.getName());
                        }else {
                            pollutionLineDTO.setName(monitor.getSubstation() + "_" + monitor.getName());
                        }
                        return pollutionLineDTO;
                    }).sorted(Comparator.comparing(PollutionLineDTO::getData, Comparator.reverseOrder())).collect(Collectors.toList());
                }
            }
            return list;
        }
        //pms查询信息
        PmsDeviceInfoParam pmsDeviceInfoParam = new PmsDeviceInfoParam();
        pmsDeviceInfoParam.setDeptIndex(param.getDeptIndex());
        //获取统计类型
        pmsDeviceInfoParam.setStatisticalType(param.getStatisticalType());
        //获取主网台账信息
        List<PmsGeneralDeviceDTO> deviceList = pmsGeneralDeviceInfoClient.getPmsDeviceInfoWithInOrg(pmsDeviceInfoParam).getData();
        List<String> monitorIdList = new ArrayList<>();
        deviceList.forEach(dept -> {
            monitorIdList.addAll(dept.getMonitorIdList());
        });

        if (CollectionUtil.isNotEmpty(monitorIdList)) {
            //获取监测点数据
            List<PublicDTO> lineData = rMpPollutionDPOMapper.getTop10Line(monitorIdList, DateUtil.beginOfDay(DateUtil.parse(param.getSearchBeginTime())), DateUtil.endOfDay(DateUtil.parse(param.getSearchEndTime())), param.getStatisticalType().getId());
            if (CollectionUtil.isEmpty(lineData)) {
                return list;
            }
            //获取主网监测点信息
            List<Monitor> data = monitorClient.getMonitorList(monitorIdList).getData();
            Map<String, Monitor> monitorMap = data.stream().collect(Collectors.toMap(Monitor::getId, Function.identity(), (key1, kye2) -> key1));
            PollutionLineDTO dto;
            for (PublicDTO lineDatum : lineData) {
                if (monitorMap.containsKey(lineDatum.getId())) {
                    Monitor monitor = monitorMap.get(lineDatum.getId());
                    dto = new PollutionLineDTO();
                    dto.setId(monitor.getId());
                    dto.setName(monitor.getName());
                    dto.setPowerCompany(monitor.getOrgName());
                    dto.setSubstation(monitor.getPowerrId());
                    dto.setSubstationId(monitor.getPowerrName());
                    dto.setBusBar(monitor.getLineName());
                    dto.setData(lineDatum.getData());
                    list.add(dto);
                }
            }
        }
        return list;
    }

    @Override
    public GridDiagramVO getPollutionAlarmData(StatSubstationBizBaseParam param) {
        DeptGetLineParam deptGetLineParam = new DeptGetLineParam();
        deptGetLineParam.setDeptId(param.getId());
        deptGetLineParam.setIsUpToGrid(param.getIsUpToGrid());
        List<DeptGetSubStationDTO.Info> deptGetChildrenMoreDTOS = commTerminalGeneralClient.deptGetSubStationInfo(deptGetLineParam).getData();
        //获取全部变电站信息
        List<SubGetBase> collect = deptGetChildrenMoreDTOS.stream().flatMap(x -> x.getStationIds().stream()).collect(Collectors.toList());
        //全部变电站
        List<String> subAll = collect.stream().map(SubGetBase::getId).distinct().collect(Collectors.toList());
        //国网变电站
        List<String> subGw = collect.stream().filter(x -> 1 == x.getIsUpToGrid()).map(SubGetBase::getId).distinct().collect(Collectors.toList());

        GridDiagramVO vo = new GridDiagramVO();
        List<Double> info = new ArrayList<>();
        List<Double> gwInfo = new ArrayList<>();
        if (CollUtil.isNotEmpty(subAll)) {
            switch (param.getType()) {
                case 1:
                    List<RStatPollutionSubstationYPO> substationYlist = pollutionSubstationYPOMapper.selectList(new LambdaQueryWrapper<RStatPollutionSubstationYPO>()
                            .select(RStatPollutionSubstationYPO::getSubstationId, RStatPollutionSubstationYPO::getValue)
                            .in(CollUtil.isNotEmpty(subAll), RStatPollutionSubstationYPO::getSubstationId, subAll)
                            .in(CollUtil.isNotEmpty(param.getIds()), RStatPollutionSubstationYPO::getPollutionType, param.getIds())
                            .ge(StrUtil.isNotBlank(param.getStartTime()), RStatPollutionSubstationYPO::getDataDate, DateUtil.beginOfDay(DateUtil.parse(param.getStartTime())))
                            .le(StrUtil.isNotBlank(param.getEndTime()), RStatPollutionSubstationYPO::getDataDate, DateUtil.endOfDay(DateUtil.parse(param.getEndTime())))
                    );
                    info.addAll(substationYlist.stream().map(RStatPollutionSubstationYPO::getValue).collect(Collectors.toList()));
                    gwInfo.addAll(substationYlist.stream()
                            .filter(x -> subGw.contains(x.getSubstationId()))
                            .map(RStatPollutionSubstationYPO::getValue).collect(Collectors.toList()));
                    break;
                case 2:
                    List<RStatPollutionSubstationQPO> substationQlist = pollutionSubstationQPOMapper.selectList(new LambdaQueryWrapper<RStatPollutionSubstationQPO>()
                            .select(RStatPollutionSubstationQPO::getSubstationId, RStatPollutionSubstationQPO::getValue)
                            .in(CollUtil.isNotEmpty(subAll), RStatPollutionSubstationQPO::getSubstationId, subAll)
                            .in(CollUtil.isNotEmpty(param.getIds()), RStatPollutionSubstationQPO::getPollutionType, param.getIds())
                            .ge(StrUtil.isNotBlank(param.getStartTime()), RStatPollutionSubstationQPO::getDataDate, DateUtil.beginOfDay(DateUtil.parse(param.getStartTime())))
                            .le(StrUtil.isNotBlank(param.getEndTime()), RStatPollutionSubstationQPO::getDataDate, DateUtil.endOfDay(DateUtil.parse(param.getEndTime())))
                    );
                    info.addAll(substationQlist.stream().map(RStatPollutionSubstationQPO::getValue).collect(Collectors.toList()));
                    gwInfo.addAll(substationQlist.stream()
                            .filter(x -> subGw.contains(x.getSubstationId()))
                            .map(RStatPollutionSubstationQPO::getValue).collect(Collectors.toList()));
                    break;
                case 3:
                    List<RStatPollutionSubstationM> substationMlist = pollutionSubstationMMapper.selectList(new LambdaQueryWrapper<RStatPollutionSubstationM>()
                            .select(RStatPollutionSubstationM::getSubstationId, RStatPollutionSubstationM::getValue)
                            .in(CollUtil.isNotEmpty(subAll), RStatPollutionSubstationM::getSubstationId, subAll)
                            .in(CollUtil.isNotEmpty(param.getIds()), RStatPollutionSubstationM::getPollutionType, param.getIds())
                            .ge(StrUtil.isNotBlank(param.getStartTime()), RStatPollutionSubstationM::getDataDate, DateUtil.beginOfDay(DateUtil.parse(param.getStartTime())))
                            .le(StrUtil.isNotBlank(param.getEndTime()), RStatPollutionSubstationM::getDataDate, DateUtil.endOfDay(DateUtil.parse(param.getEndTime())))
                    );
                    info.addAll(substationMlist.stream().map(RStatPollutionSubstationM::getValue).collect(Collectors.toList()));
                    gwInfo.addAll(substationMlist.stream()
                            .filter(x -> subGw.contains(x.getSubstationId()))
                            .map(RStatPollutionSubstationM::getValue).collect(Collectors.toList()));
                    break;
                case 4:
                    List<RStatPollutionSubstationDPO> substationDlist = pollutionSubstationDPOMapper.selectList(new LambdaQueryWrapper<RStatPollutionSubstationDPO>()
                            .select(RStatPollutionSubstationDPO::getSubstationId, RStatPollutionSubstationDPO::getValue)
                            .in(CollUtil.isNotEmpty(subAll), RStatPollutionSubstationDPO::getSubstationId, subAll)
                            .in(CollUtil.isNotEmpty(param.getIds()), RStatPollutionSubstationDPO::getPollutionType, param.getIds())
                            .ge(StrUtil.isNotBlank(param.getStartTime()), RStatPollutionSubstationDPO::getDataDate, DateUtil.beginOfDay(DateUtil.parse(param.getStartTime())))
                            .le(StrUtil.isNotBlank(param.getEndTime()), RStatPollutionSubstationDPO::getDataDate, DateUtil.endOfDay(DateUtil.parse(param.getEndTime())))
                    );
                    info.addAll(substationDlist.stream().map(RStatPollutionSubstationDPO::getValue).collect(Collectors.toList()));
                    gwInfo.addAll(substationDlist.stream()
                            .filter(x -> subGw.contains(x.getSubstationId()))
                            .map(RStatPollutionSubstationDPO::getValue).collect(Collectors.toList()));
                    break;

            }
        }
        vo.setInfo(info);
        vo.setGwInfo(gwInfo);
        return vo;
    }

    @Override
    public GridDiagramVO getNewPollutionAlarmData(StatSubstationBizBaseParam param) {
        DeptGetLineParam deptGetLineParam = new DeptGetLineParam();
        deptGetLineParam.setDeptId(param.getId());
        deptGetLineParam.setIsUpToGrid(param.getIsUpToGrid());
        List<DeptGetSubStationDTO.Info> detSub = commTerminalGeneralClient.deptGetSubStationInfo(deptGetLineParam).getData();
        //获取全部变电站信息
        List<SubGetBase> collect = detSub.stream().flatMap(x -> x.getStationIds().stream()).collect(Collectors.toList());
        GridDiagramVO vo = new GridDiagramVO();
        List<Double> info = new ArrayList<>();
        List<Double> gwInfo = new ArrayList<>();


//        if (CollUtil.isNotEmpty(subAll)) {
//            List<RStatPollutionSubstationM> substationMlist = pollutionSubstationMMapper.selectList(new LambdaQueryWrapper<RStatPollutionSubstationM>()
//                    .select(RStatPollutionSubstationM::getSubstationId, RStatPollutionSubstationM::getValue)
//                    .in(CollUtil.isNotEmpty(subAll), RStatPollutionSubstationM::getSubstationId, subAll)
//                    .in(CollUtil.isNotEmpty(param.getIds()), RStatPollutionSubstationM::getPollutionType, param.getIds())
//                    .ge(StrUtil.isNotBlank(param.getStartTime()), RStatPollutionSubstationM::getDataDate, DateUtil.beginOfDay(DateUtil.parse(param.getStartTime())))
//                    .le(StrUtil.isNotBlank(param.getEndTime()), RStatPollutionSubstationM::getDataDate, DateUtil.endOfDay(DateUtil.parse(param.getEndTime())))
//            );
//            info.addAll(substationMlist.stream().map(RStatPollutionSubstationM::getValue).collect(Collectors.toList()));
//            gwInfo.addAll(substationMlist.stream()
//                    .filter(x -> subGw.contains(x.getSubstationId()))
//                    .map(RStatPollutionSubstationM::getValue).collect(Collectors.toList()));
//        }
        vo.setInfo(info);
        vo.setGwInfo(gwInfo);
        return vo;
    }

    @Override
    public Page<PollutionGridDiagramDTO> getPollutionAlarmPageData(StatSubstationBizBaseParam param) {
        Map<String, String> map = new HashMap<>();
        map.put("V", dicDataFeignClient.getDicDataByCode(DicDataEnum.V_HARMONIC.getCode()).getData().getId());
        map.put("I", dicDataFeignClient.getDicDataByCode(DicDataEnum.I_ALL.getCode()).getData().getId());
        DeptGetLineParam deptGetLineParam = new DeptGetLineParam();
        deptGetLineParam.setDeptId(param.getId());
        deptGetLineParam.setPowerFlag(0);
        deptGetLineParam.setLineRunFlag(0);
        List<DeptGetSubStationDTO.Info> deptGetChildrenMoreDTOS = commTerminalGeneralClient.deptGetSubStationInfo(deptGetLineParam).getData();
        //获取全部变电站信息
        List<SubGetBase> collect = deptGetChildrenMoreDTOS.stream().flatMap(x -> x.getStationIds().stream()).collect(Collectors.toList());
        ArrayList<SubGetBase> substationList = collect.stream().collect(Collectors.collectingAndThen
                (Collectors.toCollection(() ->
                        new TreeSet<>(Comparator.comparing(o -> o.getId()))), ArrayList::new));

        //根据部门统计有多少干扰源(设备数量)
        Map<String, SubGetBase> substationMap = substationList.stream().collect(Collectors.toMap(SubGetBase::getId, Function.identity()));

        List<String> subIDS = new ArrayList<>();
        if (0 == param.getType()) {
            //全部变电站
            subIDS.addAll(collect.stream().map(SubGetBase::getId).distinct().collect(Collectors.toList()));
        } else {
            //国网变电站
            subIDS.addAll(collect.stream().filter(x -> 1 == x.getIsUpToGrid()).map(SubGetBase::getId).distinct().collect(Collectors.toList()));
        }
        Page<PollutionGridDiagramDTO> pollutionPage = pollutionSubstationMMapper.selectBySubstationPage(new Page<>(param.getPageNum(), param.getPageSize())
                , subIDS, map, param.getStartTime(), param.getEndTime());

        List<PollutionGridDiagramDTO> records = pollutionPage.getRecords();
        if (CollUtil.isNotEmpty(records)) {
            records.forEach(x -> {
                if (substationMap.containsKey(x.getId())) {
                    SubGetBase subGetBase = substationMap.get(x.getId());
                    x.setName(subGetBase.getName());
                    x.setPowerCompany(subGetBase.getOrgName());
                    x.setVoltageLevel(subGetBase.getVoltageLevel());
                }
            });
        }
        return pollutionPage;
    }

    @Override
    public List<List<String>> getPollutionAlarmList(GridDiagramParam param) {
        List<List<String>> info = new ArrayList<>();
        DeptGetLineParam deptGetLineParam = new DeptGetLineParam();
        deptGetLineParam.setDeptId(param.getOrgId());
        deptGetLineParam.setIsUpToGrid(param.getDeviceInfoParam().getMonitorFlag());
        List<DeptGetSubStationDTO.Info> deptSub = commTerminalGeneralClient.deptGetSubStationInfo(deptGetLineParam).getData();
        List<String> lineIdList = deptSub.stream()
                .flatMap(x -> x.getStationIds().stream().flatMap(d -> d.getUnitChildrenList().stream()))
                .distinct()
                .collect(Collectors.toList());
        List<RMpPollutionDPO> rMpPollutionDPOS = rMpPollutionDPOMapper.selectSumList(lineIdList,
//                                                                                    Arrays.asList("b33a2946cb2d4f2641f485cf7720ecc7"),
                param.getIds(),
                                                                                    DateUtil.beginOfDay(DateUtil.parse(param.getSearchBeginTime())).toString(),
                                                                                    DateUtil.endOfDay(DateUtil.parse(param.getSearchEndTime())).toString());
        List<String> dept;
        for (DeptGetSubStationDTO.Info datum : deptSub) {
            if(!datum.getUnitId().equals(param.getOrgId())){
                dept = new ArrayList<>();
                dept.add(datum.getUnitName());
                dept.add(String.valueOf(datum.getStationIds().size()));
                dept.addAll(addList(rMpPollutionDPOS, datum.getStationIds()));
                info.add(dept);
            }
        }
        return info;
    }

    @Override
    public List<SubstationVo> getSubstationInfo(String deptIndex, String searchValue, String startTime, String endTime) {
        List<SubstationVo> result = new ArrayList<>();
        DeptGetLineParam deptGetLineParam = new DeptGetLineParam();
        deptGetLineParam.setDeptId(deptIndex);
        deptGetLineParam.setMonitorStateRunning(false);
        deptGetLineParam.setSearchValue(searchValue);
        List<DeptGetSubStationDTO.Info> deptGetChildrenMoreDTOS = commTerminalGeneralClient.deptGetSubStationInfo(deptGetLineParam).getData();
        List<String> lineIds = deptGetChildrenMoreDTOS.stream().flatMap(x -> x.getStationIds().stream()).flatMap(x -> x.getUnitChildrenList().stream()).distinct().collect(Collectors.toList());

        //获取监测点集合
        LineBaseQueryParam param = new LineBaseQueryParam();
        param.setLineIds(lineIds);
        List<LineDetail> data = lineFeignClient.getByName(param).getData();
        List<String> lineList = data.stream().map(LineDetail::getId).distinct().collect(Collectors.toList());

        if (CollUtil.isNotEmpty(lineList)) {
            //获取监测点的超标数据
            List<RStatLimitRateDPO> limitRateList = rStatLimitRateDMapper.getAllOverTimes(lineList, startTime, endTime);
            Map<String, RStatLimitRateDPO> monitorMap = limitRateList.stream().collect(Collectors.toMap(RStatLimitRateDPO::getLineId, Function.identity()));
            //todo 获取监测点污染数据
            //谐波电压
            String v = dicDataFeignClient.getDicDataByCode(DicDataEnum.V_HARMONIC_LIMIT.getCode()).getData().getId();
            //谐波电流
            String i = dicDataFeignClient.getDicDataByCode(DicDataEnum.I_ALL_LIMIT.getCode()).getData().getId();
            List<String> list = Arrays.asList(v, i);
            List<RMpPollutionDPO> lineData = rMpPollutionDPOMapper.selectList(new LambdaQueryWrapper<RMpPollutionDPO>()
                    .in(CollUtil.isNotEmpty(lineList), RMpPollutionDPO::getLineId, lineList)
                    .in(CollUtil.isNotEmpty(list), RMpPollutionDPO::getPollutionType, list)
                    .ge(StrUtil.isNotBlank(startTime), RMpPollutionDPO::getDataDate, DateUtil.beginOfDay(DateUtil.parse(startTime)))
                    .le(StrUtil.isNotBlank(endTime), RMpPollutionDPO::getDataDate, DateUtil.endOfDay(DateUtil.parse(endTime)))
            );
            List<RMpPollutionDPO> harmonicV = lineData.stream().filter(x -> v.equals(x.getPollutionType())).collect(Collectors.toList());
            List<RMpPollutionDPO> harmonicI = lineData.stream().filter(x -> i.equals(x.getPollutionType())).collect(Collectors.toList());

            List<SubGetBase> subNameMap = deptGetChildrenMoreDTOS.stream().flatMap(x -> x.getStationIds().stream()).distinct().collect(Collectors.toList());
            for (SubGetBase subGetBase : subNameMap) {
                AtomicInteger alarmTime = new AtomicInteger();
                SubstationVo vo = new SubstationVo();
                vo.setDeptName(subGetBase.getOrgName());
                vo.setSubstationName(subGetBase.getName());
                List<String> unitChildrenList = subGetBase.getUnitChildrenList();
                List<LineDetail> lineDetails = data.stream().filter((x -> unitChildrenList.contains(x.getId()))).collect(Collectors.toList());
                List<String> gridSide = lineDetails.stream().filter(t -> Objects.equals(t.getPowerFlag(), 0)).map(LineDetail::getId).collect(Collectors.toList());
                List<String> notGridSide = lineDetails.stream().filter(t -> Objects.equals(t.getPowerFlag(), 1)).map(LineDetail::getId).collect(Collectors.toList());
                vo.setDwLineList(lineDetails.stream().filter(x -> gridSide.contains(x.getId())).map(LineDetail::getMonitorName).sorted().collect(Collectors.toList()));
                vo.setYhLineList(lineDetails.stream().filter(x -> notGridSide.contains(x.getId())).map(LineDetail::getMonitorName).sorted().collect(Collectors.toList()));
                unitChildrenList.forEach(item -> {
                    if (monitorMap.containsKey(item)) {
                        alarmTime.set(alarmTime.get() + monitorMap.get(item).getAllTime());
                    }
                });
                vo.setAlarmFreq(NumberUtil.round(alarmTime.get() * 1.0 / unitChildrenList.size(), 2).doubleValue());
                double maxV = harmonicV.stream().filter(x -> unitChildrenList.contains(x.getLineId())).mapToDouble(RMpPollutionDPO::getValue).sum();
                vo.setVPollutionData(NumberUtil.round(maxV,2).doubleValue());
                double maxI = harmonicI.stream().filter(x -> unitChildrenList.contains(x.getLineId())).mapToDouble(RMpPollutionDPO::getValue).sum();
                vo.setIPollutionData(NumberUtil.round(maxI,2).doubleValue());
                result.add(vo);
            }
        }
        result.sort(Comparator.comparing(SubstationVo::getVPollutionData).reversed());
        return result;
    }

    @Override
    public List<LinePollution> downPollutionLineCalc(StatSubstationBizBaseParam param) {
        DeviceInfoParam deviceInfoParam=new DeviceInfoParam();
        deviceInfoParam.setDeptIndex(param.getId());
        deviceInfoParam.setStatisticalType(new SimpleDTO());
        List<GeneralDeviceDTO> data1 = generalDeviceInfoClient.getPracticalRunDeviceInfo(deviceInfoParam).getData();
        List<String> lineIdList = data1.stream().flatMap(x -> x.getLineIndexes().stream()).distinct().collect(Collectors.toList());
        List<LinePollution> finalLinePollutionList = pollutionCalcList(param,lineIdList);
        // 全部监测点计算完毕后根据污染值从大到小进行排序
        finalLinePollutionList = finalLinePollutionList.stream()
                .sorted(Comparator.comparing(LinePollution::getHarmonicValue).reversed())
                .collect(Collectors.toList());
        return finalLinePollutionList;
    }


    private List<LinePollution> pollutionCalcList(StatSubstationBizBaseParam param,List<String> lineIdList) {
        String startDate = param.getStartTime();
        String endDate = param.getEndTime();
        List<LinePollution> linePollutionList = new ArrayList<>();
        GridDiagramParam eventParam = new GridDiagramParam();

        eventParam.setIds(lineIdList);
        eventParam.setSearchBeginTime(param.getStartTime());
        eventParam.setSearchEndTime(param.getEndTime());

        List<EventCount> eventCounts = detailFeignClient.getEventCount(eventParam).getData();
        Map<String, EventCount> eventMap = new HashMap<>();
        if (CollUtil.isNotEmpty(eventCounts)) {
            eventMap.putAll(eventCounts.stream().collect(Collectors.toMap(EventCount::getLineId, Function.identity())));
        }
        // 获取所有监测点的元信息
        List<PollutionLineInfoDTO> lineInfoDTOList = commLineClient.getPollutionLineInfo(lineIdList).getData();
        Map<String, PollutionLineInfoDTO> lineMap = lineInfoDTOList.stream().collect(Collectors.toMap(PollutionLineInfoDTO::getLineId, Function.identity()));
        //获取监测点的数据完整性
        OnlineRateParam onlineRateParam = new OnlineRateParam();
        onlineRateParam.setStartTime(startDate);
        onlineRateParam.setEndTime(endDate);
        List<RStatIntegrityVO> integrityVOS = lineFeignClient.getOnIntegrityByIds(onlineRateParam).getData();
        Map<String, BigDecimal> integrityMap = integrityVOS.stream().collect(Collectors.toMap(RStatIntegrityVO::getLineIndex, RStatIntegrityVO::getIntegrityRate));

        //获取装置在线率
        List<RStatOnlineRateVO> onLineRateVOS = generalDeviceInfoClient.getOnlineRateByDevIds(onlineRateParam).getData();
        Map<String, BigDecimal> onlineRateMap = onLineRateVOS.stream().collect(Collectors.toMap(RStatOnlineRateVO::getDevIndex, RStatOnlineRateVO::getOnlineRate));

        List<RMpPollutionDPO> rMpPollutionDPOS = rMpPollutionDPOMapper.selectSumList(lineIdList, param.getIds(), startDate, endDate);
        Map<String, Double> calcMap = new HashMap<>();
        if (CollUtil.isNotEmpty(rMpPollutionDPOS)) {
            //谐波电压
            calcMap.putAll(rMpPollutionDPOS.stream().collect(Collectors.toMap(x -> x.getLineId(), RMpPollutionDPO::getValue)));
        }
        if (CollUtil.isNotEmpty(lineIdList)) {
            // 获取谐波电压数据&总畸变率&越限限值计算基础污染值
            for (String lineId : lineIdList) {
                if (lineMap.containsKey(lineId)) {
                    PollutionLineInfoDTO data = lineMap.get(lineId);
                    LinePollution linePollution = new LinePollution();
                    // 获取暂态数据
                    BeanUtil.copyProperties(eventMap.get(lineId), linePollution);
                    BeanUtil.copyProperties(data, linePollution, true);
                    //监测点在线率
                    BigDecimal vo2 = onlineRateMap.get(data.getDeviceId());
                    linePollution.setOnlineRate(Objects.isNull(vo2) ? 0.0f : vo2.floatValue());
                    //获取监测点数据完整性
                    linePollution.setIntegrity(Objects.isNull(integrityMap.get(lineId)) ? 0.0 : integrityMap.get(lineId).doubleValue() > 100 ? 100.0 : integrityMap.get(lineId).doubleValue());
                    // 计算谐波的污染值
                    linePollution.setHarmonicValue(calcMap.containsKey(lineId) ? calcMap.get(lineId).doubleValue() : 0.0);
                    linePollution.setInterval(data.getTimeInterval());
                    linePollutionList.add(linePollution);
                }
            }
        }
        return linePollutionList;
    }

    @Override
    public void downPollutionUserCalc(StatSubstationBizBaseParam param) {
        // 处理干扰源用户的报告
        List<LinePollution> loadTypeLineList = pollutionCalcList(param,null);
        /**
         * 1、首先过滤：重要变电站、一类变电站、跨省计量关点 todo...待优化
         * 2、过滤后，以监测对象分组统计数据有多个测点的需要出结果
         */
        List<String> loadTypeSubStation = Stream.of("重要变电站", "一类变电站", "跨省计量关点").collect(Collectors.toList());
        loadTypeLineList = loadTypeLineList.stream().filter(item -> !loadTypeSubStation.contains(item.getLoadType())).collect(Collectors.toList());
        // 监测对象分组
        Map<String, List<LinePollution>> loadTypeMap = loadTypeLineList.stream().collect(Collectors.groupingBy(LinePollution::getObjName));
        List<ObjPollution> objPollutions = new ArrayList<>();
        Set<String> objNameSet = loadTypeMap.keySet();
        for (String objName : objNameSet) {
            ObjPollution objPollution = new ObjPollution();
            List<LinePollution> linePollutions = loadTypeMap.get(objName);
            objPollution.setObjName(linePollutions.get(0).getObjName());
            objPollution.setLoadType(linePollutions.get(0).getLoadType());
//            objPollution.setBusinessType(linePollutions.get(0).getBusinessType());
            // 求出平均污染值
            double objVValue = linePollutions.stream()
                    .mapToDouble(o -> o.getHarmonicValue())
                    .sum();
            objPollution.setObjVValue(PubUtils.doubleRound(2, objVValue) + "");


            // 处理该监测对象下面监测点的信息
            List<LoadTypeLineItemPollution> loadTypeLineItemPollutions = new ArrayList<>();
            for (LinePollution linePollution : linePollutions) {
                LoadTypeLineItemPollution loadTypeLineItemPollution = new LoadTypeLineItemPollution();
                BeanUtil.copyProperties(linePollution, loadTypeLineItemPollution, true);
                loadTypeLineItemPollutions.add(loadTypeLineItemPollution);
            }
            objPollution.setLineItemPollutionList(loadTypeLineItemPollutions);
            objPollutions.add(objPollution);
        }
        // 排序
        objPollutions = objPollutions.stream()
                .sorted(Comparator.comparing(ObjPollution::getObjVValue).reversed())
                .collect(Collectors.toList());
        ExcelUtil.exportExcel("用户谐波电压污染值" + param.getEndTime() + ".xlsx", ObjPollution.class, objPollutions);
    }

    @Override
    public List<SubstationPollution> downPollutionSubCalc(StatSubstationBizBaseParam param) {
        DeviceInfoParam deviceInfoParam=new DeviceInfoParam();
        deviceInfoParam.setDeptIndex(param.getId());
        deviceInfoParam.setStatisticalType(new SimpleDTO());
        List<GeneralDeviceDTO> data1 = generalDeviceInfoClient.getPracticalAllDeviceInfoAsSubstation(deviceInfoParam).getData();
        List<String> lineIdList = data1.stream().flatMap(x -> x.getLineIndexes().stream()).distinct().collect(Collectors.toList());
        List<SubstationPollution> substationPollutions = new ArrayList<>();
        // 处理干扰源用户的报告
        List<LinePollution> linePollutionList = pollutionCalcList(param,lineIdList);

        // 以变电站分组
        Map<String, List<LinePollution>> subMap = linePollutionList.stream()
                .collect(Collectors.groupingBy(x -> x.getSubStationId()+"_"+ x.getGdName() + "_"  +x.getSubStationName() + "_" + x.getSubVoltage()));
        subMap.forEach((key, value) -> {
            String[] name = key.split("_");
            SubstationPollution substationPollution = new SubstationPollution();
            substationPollution.setGdName(name[1]);
            substationPollution.setSubStationName(name[2]);
            substationPollution.setSubVoltage(name[3]);
            double subVValue = value.stream()
                    .mapToDouble(o -> o.getHarmonicValue())
                    .sum();
            substationPollution.setSubVStationValue(PubUtils.doubleRound(2, subVValue) + "");
            List<PowerFlagPollution> lineItemPollutionList = new ArrayList<>();
            for (LinePollution linePollution : value) {
                PowerFlagPollution lineItemPollution = new PowerFlagPollution();
                BeanUtil.copyProperties(linePollution, lineItemPollution, true);
                lineItemPollution.setVHarmonicValue(linePollution.getHarmonicValue());
                lineItemPollution.setSubName(linePollution.getSubStationName());
                lineItemPollutionList.add(lineItemPollution);
            }
            substationPollution.setPowerFlagPollutionList(lineItemPollutionList);
            substationPollutions.add(substationPollution);
        });
        substationPollutions.sort(Comparator.comparingDouble(o -> Double.parseDouble(o.getSubVStationValue())));
        Collections.reverse(substationPollutions);
        return substationPollutions;
    }

    @Override
    public List<UserLinePollution> getSumList(OnlineRateParam.Info param) {
        List<UserLinePollution> info = new ArrayList<>();
        UserReportParam userReportParam = new UserReportParam();
        userReportParam.setUserType(6);
        List<UserLedgerVO> userLedgerVOList = userLedgerFeignClient.selectUserList(userReportParam).getData();
        Map<String, List<UserLedgerVO>> userMap = userLedgerVOList.stream().filter(x -> StrUtil.isNotBlank(x.getLineId())).collect(Collectors.groupingBy(UserLedgerVO::getLineId));
        List<RMpPollutionDPO> rMpPollutionDPOS = rMpPollutionDPOMapper.selectSumList(param.getIds(), param.getDicData(), param.getStartTime(), param.getEndTime());
        Map<String, Double> pollutionMap = rMpPollutionDPOS.stream().collect(Collectors.toMap(RMpPollutionDPO::getLineId, RMpPollutionDPO::getValue));
        UserLinePollution user;
        for (String id : param.getIds()) {
            user = new UserLinePollution();
            user.setLineId(id);
            if (pollutionMap.containsKey(id)) {
                user.setVHarmonicValue(pollutionMap.get(id));
            } else {
                user.setVHarmonicValue(0.0);
            }
            List<UserLinePollution.User> userList = new ArrayList<>();
            if (userMap.containsKey(id)) {
                List<UserLedgerVO> userLedgerVOS = userMap.get(id);
                userList.addAll(BeanUtil.copyToList(userLedgerVOS, UserLinePollution.User.class));
            }
            user.setUserList(userList);
            info.add(user);
        }
        return info;
    }

    @Override
    public List<AreaPollution> getAreaPollution(StatSubstationBizBaseParam param) {
        List<AreaPollution> info = new ArrayList<>();
        DeviceInfoParam deviceInfoParam = new DeviceInfoParam();
        deviceInfoParam.setLineRunFlag(0);
        deviceInfoParam.setDeptIndex(param.getId());
        deviceInfoParam.setStatisticalType(new SimpleDTO());
        List<GeneralDeviceDTO> deptData = generalDeviceInfoClient.getPracticalRunDeviceInfo(deviceInfoParam).getData();
        List<String> lineIdList = deptData.stream().flatMap(x -> x.getLineIndexes().stream()).distinct().collect(Collectors.toList());
        if (CollUtil.isNotEmpty(lineIdList)) {
            List<DeptDTO> deptList = deptFeignClient.getDepSonDetailByDeptId(param.getId()).getData();
            Map<String, String> deptId = deptList.stream().filter(x ->!x.getId().equals("46364ea96a55095ebc250be698d5262c") &&
                    !x.getId().equals("a3069759b0b6072c99cf9a7af6c162e9")).collect(Collectors.toMap(DeptDTO::getArea, DeptDTO::getId));

            List<RMpPollutionDPO> pollutionList = rMpPollutionDPOMapper.selectSumList(lineIdList, param.getIds(), param.getStartTime(), param.getEndTime());
            Map<String, Double> pollutionMap = pollutionList.stream().collect(Collectors.toMap(RMpPollutionDPO::getLineId, RMpPollutionDPO::getValue));

            List<PollutionLineInfoDTO> lineDetailList = commLineClient.getPollutionLineInfo(lineIdList).getData();
            List<String> ids = deptData.stream()
                    .filter(x -> x.getIndex().equals("46364ea96a55095ebc250be698d5262c") ||
                            x.getIndex().equals("a3069759b0b6072c99cf9a7af6c162e9"))
                    .flatMap(x -> x.getLineIndexes().stream()).collect(Collectors.toList());
            //获取到了部门风光储和超高压的其他部门信息
            Map<String, List<String>> fgIds = lineDetailList
                    .stream().filter(x -> ids.contains(x.getLineId()))
                    .collect(Collectors.groupingBy(x -> deptId.get(x.getActualArea()), Collectors.mapping(PollutionLineInfoDTO::getLineId, Collectors.toList())));
            for (GeneralDeviceDTO dto : deptData) {
                if (dto.getIndex().equals("46364ea96a55095ebc250be698d5262c") ||
                        dto.getIndex().equals("a3069759b0b6072c99cf9a7af6c162e9")) {
                    break;
                }
                if (fgIds.containsKey(dto.getIndex())) {
                    dto.getLineIndexes().addAll(fgIds.get(dto.getIndex()));
                }
                List<PowerFlagPollution> linePollutionList = new ArrayList<>();
                AreaPollution pollution = new AreaPollution();
                pollution.setDeptName(dto.getName());
                pollution.setDeptId(dto.getIndex());
                List<PollutionLineInfoDTO> lineDetails = lineDetailList.stream().filter(x -> dto.getLineIndexes().contains(x.getLineId())).collect(Collectors.toList());
                PowerFlagPollution pollution1;
                for (PollutionLineInfoDTO lineDetail : lineDetails) {
                    pollution1 = new PowerFlagPollution();
                    pollution1.setSubName(lineDetail.getSubStationName());
                    pollution1.setLineName(lineDetail.getLineName());
                    pollution1.setDevName(lineDetail.getDevName());
                    pollution1.setManufacturer(lineDetail.getManufacturer());
                    pollution1.setDevType(lineDetail.getDevType());
                    pollution1.setLoginTime(lineDetail.getLoginTime());
                    pollution1.setInterval(lineDetail.getTimeInterval());
                    pollution1.setPowerFlag(lineDetail.getPowerFlag());
                    pollution1.setLoadType(lineDetail.getLoadType());
                    pollution1.setObjName(lineDetail.getObjName());
                    pollution1.setVHarmonicValue(pollutionMap.containsKey(lineDetail.getLineId()) ? NumberUtil.round(pollutionMap.get(lineDetail.getLineId()), 2).doubleValue() : 0.0);
                    linePollutionList.add(pollution1);
                }
                pollution.setPowerFlagPollutionList(linePollutionList.stream().sorted(Comparator.comparing(PowerFlagPollution::getVHarmonicValue).reversed()).collect(Collectors.toList()));
                pollution.setScore(NumberUtil.round(linePollutionList.stream().mapToDouble(PowerFlagPollution::getVHarmonicValue).sum(), 2).doubleValue());
                info.add(pollution);
            }
        }
        return info;
    }

    @Override
    public List<SubstationPollution> downPollutionSensitiveUser(StatSubstationBizBaseParam param) {
        List<SubstationPollution> result = new ArrayList<>();
        DeptGetLineParam deptGetLineParam = new DeptGetLineParam();
        deptGetLineParam.setDeptId(param.getDeptId());
        deptGetLineParam.setLineRunFlag(0);
        deptGetLineParam.setServerName(ServerEnum.HARMONIC.getName());
        List<DeptGetChildrenMoreDTO> list = commTerminalGeneralClient.deptGetLine(deptGetLineParam).getData();
        List<String> lineList = list.stream()
                .flatMap(dto -> dto.getLineBaseList().stream().map(LineDevGetDTO::getPointId))
                .distinct()
                .collect(Collectors.toList());
        //全部监测点污染值
        List<LinePollution> finalLinePollutionList = pollutionCalcList(param,lineList);
        //根据变电站分组
        Map<String, List<LinePollution>> linePollutionMap = finalLinePollutionList.stream().collect(Collectors.groupingBy(LinePollution::getSubStationName));
        //获取部门id
        SensitiveUserParam sensitiveUserParam = new SensitiveUserParam();
        sensitiveUserParam.setDeptId(param.getDeptId());
        sensitiveUserParam.setProjectName(param.getSearchValue());
        List<UserReportPO> userReportPOList = userLedgerFeignClient.getSensitiveUserByDept(sensitiveUserParam).getData();

        if (CollectionUtil.isNotEmpty(userReportPOList)) {
            userReportPOList.forEach(item -> {
                if (ObjectUtil.isNotNull(item.getSubstation()) && !Objects.equals(item.getSubstation(), "")) {
                    List<BigDecimal> value = new ArrayList<>();
                    List<PowerFlagPollution> ll = new ArrayList<>();
                    String[] parts = item.getSubstation().split("、");
                    for (String part : parts) {
                        // 移除数字+kV和"变电站"
                        String name = part.replaceAll("\\d+kV", "").replace("变电站", "");
                        //根据变电站名称获取污染值
                        for (Map.Entry<String, List<LinePollution>> entry : linePollutionMap.entrySet()) {
                            if (entry.getKey().contains(name)) {
                                BigDecimal v = BigDecimal.valueOf(entry.getValue().stream().mapToDouble(LinePollution::getHarmonicValue).average().getAsDouble());
                                value.add(v);
                                for (LinePollution pojo : entry.getValue()) {
                                    PowerFlagPollution lineItemPollution = new PowerFlagPollution();
                                    BeanUtil.copyProperties(pojo, lineItemPollution, true);
                                    lineItemPollution.setVHarmonicValue(pojo.getHarmonicValue());
                                    lineItemPollution.setSubName(pojo.getSubStationName());
                                    ll.add(lineItemPollution);
                                }
                            }
                        }
                    }
                    SubstationPollution linePollution = new SubstationPollution();
                    linePollution.setGdName(item.getCity());
                    linePollution.setSubStationName(item.getSubstation());
                    linePollution.setProjectName(item.getProjectName());
                    if (CollectionUtil.isEmpty(ll)) {
                        linePollution.setSubValue(null);
                    } else {
                        linePollution.setSubValue(BigDecimal.valueOf(value.stream()
                                .mapToDouble(BigDecimal::doubleValue)
                                .average()
                                .orElse(0.0)).setScale(2, RoundingMode.HALF_UP).doubleValue());
                        linePollution.setPowerFlagPollutionList(ll);
                    }
                    result.add(linePollution);
                }
            });
        }
        if (CollectionUtil.isNotEmpty(result)) {
            result.sort(Comparator.comparing(SubstationPollution::getSubValue,Comparator.nullsLast(Comparator.reverseOrder())));
        }
        return result;
    }


    private List<String> addList(List<RMpPollutionDPO> pollLinelist, List<SubGetBase> notNum) {
        List<String> info = new ArrayList<>();
        Integer num1 = 0;
        Integer num2 = 0;
        Integer num3 = 0;
        Integer num4 = 0;
        Integer num5 = 0;
        Integer num6 = 0;
        for (SubGetBase subGetBase : notNum) {
            List<RMpPollutionDPO> linePoll = pollLinelist.stream().filter(x -> subGetBase.getUnitChildrenList().contains(x.getLineId())).collect(Collectors.toList());
            if(CollUtil.isNotEmpty(linePoll)){
                Double value = linePoll.stream().mapToDouble(RMpPollutionDPO::getValue).sum();
                //无污染 轻微污染0-100 轻度污染100-1000 中度污染1000-10000 重度污染10000
                if (0 == value) {
                    num1++;
                } else if (0 < value && value < 100) {
                    num2++;
                } else if (100 <= value && value < 1000) {
                    num3++;
                } else if (1000 <= value && value < 10000) {
                    num4++;
                } else if (10000 <= value) {
                    num5++;
                }
            }else{
                num6++;
            }
        }
        info.add(String.valueOf(num1));
        info.add(String.valueOf(num2));
        info.add(String.valueOf(num3));
        info.add(String.valueOf(num4));
        info.add(String.valueOf(num5));
        info.add(String.valueOf(num6));
        return info;
    }
}
