package com.njcn.harmonic.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
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.njcn.common.config.GeneralInfo;
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.GeneralDeviceDTO;
import com.njcn.device.biz.pojo.dto.PollutionLineDTO;
import com.njcn.device.pq.pojo.dto.PollutionParamDTO;
import com.njcn.device.pq.pojo.po.LineDetail;
import com.njcn.device.pq.pojo.vo.LineDeviceStateVO;
import com.njcn.harmonic.constant.Param;
import com.njcn.harmonic.mapper.RStatLimitTargetDMapper;
import com.njcn.harmonic.pojo.dto.AreaDTO;
import com.njcn.harmonic.pojo.param.HarmonicPublicParam;
import com.njcn.harmonic.pojo.po.LimitTarget;
import com.njcn.harmonic.pojo.po.day.RStatLimitTargetDPO;
import com.njcn.harmonic.pojo.vo.*;
import com.njcn.harmonic.service.IHarmonicService;
import com.njcn.supervision.pojo.param.user.UserReportParam;
import com.njcn.supervision.pojo.vo.user.UserLedgerVO;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.web.utils.RequestUtil;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.*;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 类的介绍：
 *
 * @author xuyang
 * @version 1.0.0
 * @createTime 2021/12/31 9:50
 */
@Service
@AllArgsConstructor
public class HarmonicServiceImpl implements IHarmonicService {

    private final GeneralDeviceInfoClient generalDeviceInfoClient;
    private final GeneralInfo generalInfo;
    private final LineFeignClient lineFeignClient;
    private final RStatLimitTargetDMapper targetDMapper;
    private final UserLedgerFeignClient userLedgerFeignClient;
    private final SubstationFeignClient substationFeignClient;

    @Override
    public List<PollutionVO> getDeptSubstationRelations(HarmonicPublicParam harmonicPublicParam) {
        harmonicPublicParam.setServerName(generalInfo.getMicroServiceName());
        List<PollutionVO> list = new ArrayList<>();
        if (StringUtils.isBlank(RequestUtil.getDeptIndex())) {
            return list;
        }
        Map<String, UserLedgerVO> userLedgerVOMap;
        if (harmonicPublicParam.isUserLedger()) {
            List<UserLedgerVO> userLedgerVOList = userLedgerFeignClient.selectUserList(new UserReportParam()).getData();
            userLedgerVOMap = userLedgerVOList.stream().collect(Collectors.toMap(UserLedgerVO::getId, Function.identity()));
        } else {
            userLedgerVOMap = new HashMap<>();
        }
        List<GeneralDeviceDTO> deptList = generalDeviceInfoClient.getPracticalRunDeviceInfo(harmonicPublicParam).getData();
        for (GeneralDeviceDTO dept : deptList) {
            if (CollUtil.isEmpty(dept.getLineIndexes())) {
                continue;
            }
            //获取所有的数据信息
            List<RStatLimitTargetDPO> limitTargetNew = getLimitTargetNew(dept.getLineIndexes(), harmonicPublicParam.getSearchBeginTime(), harmonicPublicParam.getSearchEndTime());
            //聚合查询
            List<RStatLimitTargetDPO> finalAllData;
            if (Objects.equals(harmonicPublicParam.getStatisticalType().getCode(), DicDataEnum.XBDY_ENUM.getCode())) {
                finalAllData = getAllDataV(dept.getLineIndexes(), harmonicPublicParam.getSearchBeginTime(), harmonicPublicParam.getSearchEndTime());
            } else if (Objects.equals(harmonicPublicParam.getStatisticalType().getCode(), DicDataEnum.XBDL_ENUM.getCode())) {
                finalAllData = getAllDataI(dept.getLineIndexes(), harmonicPublicParam.getSearchBeginTime(), harmonicPublicParam.getSearchEndTime());
            } else {
                finalAllData = new ArrayList<>();
            }

            PollutionParamDTO paramDTO = new PollutionParamDTO();
            paramDTO.setLineList(dept.getLineIndexes());
            List<PollutionLineDTO> pollutionLineDTOList = lineFeignClient.getLineInfo(paramDTO).getData();
            List<PollutionLineDTO> userLedgerList = pollutionLineDTOList.stream().filter(item -> StrUtil.isNotBlank(item.getObjId())).collect(Collectors.toList());
            List<PollutionLineDTO> powerLedgerList = pollutionLineDTOList.stream().filter(item -> StrUtil.isBlank(item.getObjId())).collect(Collectors.toList());

            List<PollutionVO> childrenList = new ArrayList<>();
            Map<String, List<PollutionLineDTO>> powerSubMap;
            if (CollUtil.isNotEmpty(powerLedgerList)) {
                powerSubMap = powerLedgerList.stream().collect(Collectors.groupingBy(it -> it.getPids().split(StrUtil.COMMA)[LineBaseEnum.SUB_LEVEL.getCode()]));
            } else {
                powerSubMap = new HashMap<>();
            }

            if (!CollectionUtils.isEmpty(dept.getSubIndexes())) {
                PollutionVO pollutionVO = new PollutionVO();
                pollutionVO.setId(dept.getIndex());
                pollutionVO.setName(dept.getName() + "\n(" + dept.getLineIndexes().size() + ")");
                powerSubMap.forEach((sub, monitList) -> {
                    PollutionVO children = new PollutionVO();
                    children.setId(sub);
                    children.setPid(dept.getIndex());
                    children.setPowerFlag(PowerFlagEnum.GRID_SIDE.getCode());
                    children.setName(monitList.get(0).getSubstation());
                    //监测点id
                    children.setData(handleDataNew(limitTargetNew, finalAllData, harmonicPublicParam.getStatisticalType().getCode()).getRatio());
                    childrenList.add(children);
                });

                if (CollUtil.isNotEmpty(userLedgerList)) {
                    Map<String, List<PollutionLineDTO>> objMap = userLedgerList.stream().collect(Collectors.groupingBy(PollutionLineDTO::getObjId));
                    objMap.forEach((obj, mList) -> {
                        UserLedgerVO userLedgerVO = userLedgerVOMap.getOrDefault(obj, new UserLedgerVO());
                        PollutionVO children = new PollutionVO();
                        children.setId(obj);
                        children.setPid(userLedgerVO.getStationId());
                        children.setName(StrUtil.isNotBlank(userLedgerVO.getProjectName()) ? userLedgerVO.getProjectName() : "异常数据");
                        children.setPowerFlag(PowerFlagEnum.NO_GRID_SIDE.getCode());
                        //监测点id
                        children.setData(handleDataNew(limitTargetNew, finalAllData, harmonicPublicParam.getStatisticalType().getCode()).getRatio());
                        childrenList.add(children);
                    });
                }

                if (!CollectionUtils.isEmpty(childrenList)) {
                    pollutionVO.setChildren(childrenList.stream().sorted(Comparator.comparing(PollutionVO::getData).reversed().thenComparing(PollutionVO::getName)).collect(Collectors.toList()));
                }
                if (!CollectionUtils.isEmpty(dept.getLineIndexes())) {
                    double tem = childrenList.stream().mapToDouble(PollutionVO::getData).average().orElse(3.14159);
                    pollutionVO.setData(tem == 3.14159 || tem < 0 ? 3.14159 : NumberUtil.round(tem, 2).doubleValue());
                }
                list.add(pollutionVO);
            }
        }
        if (!CollectionUtils.isEmpty(list)) {
            return list.stream().sorted(Comparator.comparing(PollutionVO::getData).reversed().thenComparing(PollutionVO::getName)).collect(Collectors.toList());
        }
        return list;
    }

    @Override
    public List<HarmonicDeptVO> getDeptInfo(HarmonicPublicParam param) {
        param.setServerName(generalInfo.getMicroServiceName());
        List<HarmonicDeptVO> list = new ArrayList<>();
        List<GeneralDeviceDTO> deptList = generalDeviceInfoClient.getPracticalRunDeviceInfo(param).getData();
        for(GeneralDeviceDTO dept : deptList){
            if (!CollectionUtils.isEmpty(dept.getLineIndexes())) {
                HarmonicDeptVO harmonicDeptVO = new HarmonicDeptVO();
                harmonicDeptVO.setId(dept.getIndex());
                harmonicDeptVO.setName(dept.getName());
                //获取所有的数据信息
                List<RStatLimitTargetDPO> limitTargetNew = getLimitTargetNew(dept.getLineIndexes(), param.getSearchBeginTime(), param.getSearchEndTime());
                //聚合查询
                List<RStatLimitTargetDPO> allData = new ArrayList<>();
                if (Objects.equals(param.getStatisticalType().getCode(), DicDataEnum.XBDY_ENUM.getCode())) {
                    allData = getAllDataV(dept.getLineIndexes(), param.getSearchBeginTime(), param.getSearchEndTime());
                } else if (Objects.equals(param.getStatisticalType().getCode(), DicDataEnum.XBDL_ENUM.getCode())) {
                    allData = getAllDataI(dept.getLineIndexes(), param.getSearchBeginTime(), param.getSearchEndTime());
                }
                AreaDTO areaDTO = handleDataNew(limitTargetNew, allData, param.getStatisticalType().getCode());
                BeanUtil.copyProperties(areaDTO, harmonicDeptVO);
                list.add(harmonicDeptVO);
            }
        }

        if (!CollectionUtils.isEmpty(list)) {
            List<HarmonicDeptVO> collect = list.stream().filter(x -> x.getRatio() != 3.14159 && x.getOnlineCount() != 0 && x.getOverLineCount() != 0)
                    .sorted(Comparator.comparing(HarmonicDeptVO::getRatio).reversed().thenComparing(HarmonicDeptVO::getOnlineCount).thenComparing(HarmonicDeptVO::getOverLineCount)).collect(Collectors.toList());
            List<String> ids = collect.stream().map(HarmonicDeptVO::getId).collect(Collectors.toList());
            collect.addAll(list.stream().filter(x -> !ids.contains(x.getId()))
                    .collect(Collectors.toList()));
            return collect;
        }
        return list;
    }

    @Override
    public List<HarmonicSubstationVO> getSubstationInfoById(HarmonicPublicParam param) {
        param.setServerName(generalInfo.getMicroServiceName());
        List<HarmonicSubstationVO> list = new ArrayList<>();
        List<GeneralDeviceDTO> subList = generalDeviceInfoClient.getPracticalRunDeviceInfoAsSubstation(param).getData();
        subList.forEach(item -> {
            HarmonicSubstationVO harmonicSubstationVO = new HarmonicSubstationVO();
            harmonicSubstationVO.setId(item.getIndex());
            harmonicSubstationVO.setName(item.getName());
            List<String> lineList = item.getLineIndexes();
            if (!CollectionUtils.isEmpty(lineList)) {
                AreaDTO areaDTO = handleData(getLimitTarget(lineList, param.getSearchBeginTime(), param.getSearchEndTime()), param.getStatisticalType().getCode(), lineList, param.getSearchBeginTime(), param.getSearchEndTime());
                BeanUtil.copyProperties(areaDTO, harmonicSubstationVO);
                int result = getWarningInfo(lineList, param.getSearchBeginTime(), param.getSearchEndTime(), param.getStatisticalType().getCode());
                if (result == -1) {
                    harmonicSubstationVO.setWarningFreq(-1.0);
                } else {
                    if (areaDTO.getOverLineCount() == 0) {
                        if (areaDTO.getOnlineCount() > 0) {
                            harmonicSubstationVO.setWarningFreq(0.0);
                        } else {
                            harmonicSubstationVO.setWarningFreq(-1.0);
                        }
                    } else {
                        harmonicSubstationVO.setWarningFreq(BigDecimal.valueOf(result * 1.0 / areaDTO.getOverLineCount()).setScale(2, RoundingMode.HALF_UP).doubleValue());
                    }
                }
            }
            list.add(harmonicSubstationVO);
        });
        if (!CollectionUtils.isEmpty(list)) {
            return list.stream().sorted(Comparator.comparing(HarmonicSubstationVO::getRatio).reversed().thenComparing(HarmonicSubstationVO::getOnlineCount).thenComparing(HarmonicSubstationVO::getOverLineCount)).collect(Collectors.toList());
        }
        return list;
    }

    @Override
    public List<HarmonicLineVO> getLineInfoById(HarmonicPublicParam param) {

        List<HarmonicLineVO> list = new ArrayList<>();
        List<LineDetail> lineDetailList = new ArrayList<>();
        if(PowerFlagEnum.GRID_SIDE.getCode().equals(param.getPowerFlag())){
            lineDetailList = substationFeignClient.getMonitorByStationId(param.getId(),PowerFlagEnum.GRID_SIDE.getCode()).getData();
        }else if(PowerFlagEnum.NO_GRID_SIDE.getCode().equals(param.getPowerFlag())){
            lineDetailList = lineFeignClient.getMonitorByObjId(param.getId()).getData();
        }
        List<String> lineIds = lineDetailList.stream().map(LineDetail::getId).collect(Collectors.toList());
        Map<String,LineDetail> map = lineDetailList.stream().collect(Collectors.toMap(LineDetail::getId,Function.identity()));
        if (!CollectionUtils.isEmpty(lineIds)) {
            List<LimitTarget> limitTargetList = getLineOverDays(lineIds, param.getSearchBeginTime(), param.getSearchEndTime(), param.getStatisticalType().getCode());
            if (!CollectionUtils.isEmpty(limitTargetList)) {
                buildData(list, limitTargetList, param.getStatisticalType().getCode());
            }
        }
        //获取监测点名称
        if (!CollectionUtils.isEmpty(list)) {
            list.stream().sorted(Comparator.comparing(HarmonicLineVO::getOverDays).reversed()).forEach(item -> item.setName(map.getOrDefault(item.getId(),new LineDetail()).getMonitorName()));
        }
        return list;
    }


    @Override
    public List<HarmonicLineVO> getLineRank(HarmonicPublicParam param) {
        param.setServerName(generalInfo.getMicroServiceName());
        List<HarmonicLineVO> list = new ArrayList<>();
        List<String> lineList = new ArrayList<>();
        if (StringUtils.isBlank(RequestUtil.getDeptIndex())) {
            return list;
        }
        List<GeneralDeviceDTO> deviceList = generalDeviceInfoClient.getPracticalRunDeviceInfo(param).getData();
        deviceList.forEach(item -> {
            if (!CollectionUtils.isEmpty(item.getLineIndexes())) {
                lineList.addAll(item.getLineIndexes());
            }
        });
        if (!CollectionUtils.isEmpty(lineList)) {
            List<LimitTarget> limitTargetList = getLineOverDays(lineList, param.getSearchBeginTime(), param.getSearchEndTime(), param.getStatisticalType().getCode());
            if (!CollectionUtils.isEmpty(limitTargetList)) {
                buildData(list, limitTargetList, param.getStatisticalType().getCode());
            }
        }
        list.sort((item1, item2) -> item2.getOverDays().compareTo(item1.getOverDays()));
        //获取监测点名称
        if (!CollectionUtils.isEmpty(list)) {
            List<String> l1 = list.stream().map(HarmonicLineVO::getId).collect(Collectors.toList());
            List<LineDeviceStateVO> lineDeviceStateVOList = lineFeignClient.getAllLine(l1).getData();
            list.stream().map(item1 -> lineDeviceStateVOList.stream().filter(item2 -> Objects.equals(item1.getId(), item2.getId())).findAny().map(item3 -> {
                item1.setName(item3.getName());
                return list;
            })).collect(Collectors.toList());
        }
        if (list.size() > Param.UP_LIMIT) {
            return list.subList(Param.DOWN_LIMIT, Param.UP_LIMIT);
        }
        return list;
    }

    public List<RStatLimitTargetDPO> getLimitTargetNew(List<String> lineList, String startTime, String endTime) {
        List<RStatLimitTargetDPO> limitRates = targetDMapper.selectList(new LambdaQueryWrapper<RStatLimitTargetDPO>()
                .in(RStatLimitTargetDPO::getLineId, lineList)
                .ge(StrUtil.isNotBlank(startTime), RStatLimitTargetDPO::getTime, DateUtil.beginOfDay(DateUtil.parse(startTime)))
                .le(StrUtil.isNotBlank(endTime), RStatLimitTargetDPO::getTime, DateUtil.endOfDay(DateUtil.parse(endTime)))
        );
        return limitRates;
    }

    /**
     * 功能描述: 获取limitTarget数据
     *
     * @param lineList  部门列表
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return java.util.List<com.njcn.harmonic.pojo.dto.PublicDTO>
     * @author xy
     * @date 2022/2/25 15:05
     */
    public List<RStatLimitTargetDPO> getLimitTarget(List<String> lineList, String startTime, String endTime) {
        return targetDMapper.selectList(new LambdaQueryWrapper<RStatLimitTargetDPO>()
                .in(RStatLimitTargetDPO::getLineId, lineList)
                .ge(StrUtil.isNotBlank(startTime), RStatLimitTargetDPO::getTime, DateUtil.beginOfDay(DateUtil.parse(startTime)))
                .le(StrUtil.isNotBlank(endTime), RStatLimitTargetDPO::getTime, DateUtil.endOfDay(DateUtil.parse(endTime)))
        );
    }

    public AreaDTO handleDataNew(List<RStatLimitTargetDPO> list, List<RStatLimitTargetDPO> sumList, String type) {
        int onlineCount = 0, overLineCount = 0, overCountByDay = 0;
        double avgOverDay = 0.0, ratio = 0.0;
        AreaDTO areaDTO = new AreaDTO();
        if (!CollectionUtils.isEmpty(list)) {
            List<RStatLimitTargetDPO> data = sumList;
            if (!CollectionUtils.isEmpty(sumList)) {
                onlineCount = data.size();
                //在线监测点个数
                areaDTO.setOnlineCount(onlineCount);
                for (RStatLimitTargetDPO pojo : data) {
                    if (pojo.getAllTime() > 0) {
                        overLineCount = overLineCount + 1;
                    }
                }
            }

            Map<LocalDate, List<RStatLimitTargetDPO>> map = list.stream().collect(Collectors.groupingBy(RStatLimitTargetDPO::getTime));
            for (LocalDate key : map.keySet()) {
                int overDay = 0;
                List<RStatLimitTargetDPO> l = map.get(key);
                for (RStatLimitTargetDPO pojo : l) {
                    if (Objects.equals(type, DicDataEnum.XBDY_ENUM.getCode())) {
                        if (pojo.getUaberranceOvertime() > 0 || pojo.getUharm20Overtime() > 0 || pojo.getUharm3Overtime() > 0 || pojo.getUharm4Overtime() > 0 || pojo.getUharm5Overtime() > 0 || pojo.getUharm6Overtime() > 0 || pojo.getUharm7Overtime() > 0 || pojo.getUharm8Overtime() > 0 || pojo.getUharm9Overtime() > 0 || pojo.getUharm10Overtime() > 0 || pojo.getUharm11Overtime() > 0 || pojo.getUharm12Overtime() > 0 || pojo.getUharm13Overtime() > 0 || pojo.getUharm14Overtime() > 0 || pojo.getUharm15Overtime() > 0 || pojo.getUharm16Overtime() > 0 || pojo.getUharm17Overtime() > 0 || pojo.getUharm18Overtime() > 0 || pojo.getUharm19Overtime() > 0 || pojo.getUharm20Overtime() > 0 || pojo.getUharm21Overtime() > 0 || pojo.getUharm22Overtime() > 0 || pojo.getUharm23Overtime() > 0 || pojo.getUharm24Overtime() > 0 || pojo.getUharm25Overtime() > 0) {
                            overCountByDay = overCountByDay + 1;
                            overDay = overDay + 1;
                        }
                    } else if (Objects.equals(type, DicDataEnum.XBDL_ENUM.getCode())) {
                        if (pojo.getIharm2Overtime() > 0 || pojo.getIharm3Overtime() > 0 || pojo.getIharm4Overtime() > 0 || pojo.getIharm5Overtime() > 0 || pojo.getIharm6Overtime() > 0 || pojo.getIharm7Overtime() > 0 || pojo.getIharm8Overtime() > 0 || pojo.getIharm9Overtime() > 0 || pojo.getIharm10Overtime() > 0 || pojo.getIharm11Overtime() > 0 || pojo.getIharm12Overtime() > 0 || pojo.getIharm13Overtime() > 0 || pojo.getIharm14Overtime() > 0 || pojo.getIharm15Overtime() > 0 || pojo.getIharm16Overtime() > 0 || pojo.getIharm17Overtime() > 0 || pojo.getIharm18Overtime() > 0 || pojo.getIharm19Overtime() > 0 || pojo.getIharm20Overtime() > 0 || pojo.getIharm21Overtime() > 0 || pojo.getIharm22Overtime() > 0 || pojo.getIharm23Overtime() > 0 || pojo.getIharm24Overtime() > 0 || pojo.getIharm25Overtime() > 0) {
                            overCountByDay = overCountByDay + 1;
                            overDay = overDay + 1;
                        }
                    }
                }
                ratio = ratio + overDay * 1.0 / l.size();
            }
            ratio = map.isEmpty() ? 0 : BigDecimal.valueOf(ratio * 100.0 / map.size()).setScale(2, RoundingMode.HALF_UP).doubleValue();
        }else {
            ratio = 3.14159;
        }

        //平均超标天数
        if (CollectionUtils.isEmpty(list)) {
            avgOverDay = 0;
        } else {
            avgOverDay = overLineCount == 0 ? 0.0 : BigDecimal.valueOf(overCountByDay * 1.0 / overLineCount).setScale(2, RoundingMode.HALF_UP).doubleValue();
        }
        //月监测点符合性超标占比
        areaDTO.setOnlineCount(onlineCount);
        areaDTO.setOverLineCount(overLineCount);
        //平均超标天数
        areaDTO.setAverageOverDay(avgOverDay);
        areaDTO.setRatio(Math.min(ratio, 100.0));
        //月监测点超标占比
        double lineRatio = onlineCount == 0 ? 0 : BigDecimal.valueOf(overLineCount * 100.0 / onlineCount).setScale(2, RoundingMode.HALF_UP).doubleValue();
        areaDTO.setLineRatio(Math.min(lineRatio, 100.0));
        return areaDTO;
    }


    /**
     * todo
     * 功能描述: 处理区域(变电站)在线监测点数、超标监测点数、平均超标天数、占比
     *
     * @param list 集合
     *             type 类型
     * @return
     * @author xy
     * @date 2022/2/25 15:05
     */
    public AreaDTO handleData(List<RStatLimitTargetDPO> list, String type, List<String> lineList, String startTime, String endTime) {
        int onlineCount = 0, overLineCount = 0, overCountByDay = 0;
        double avgOverDay = 0.0, ratio = 0.0;
        AreaDTO areaDTO = new AreaDTO();
        if (!CollectionUtils.isEmpty(list)) {
            List<RStatLimitTargetDPO> data = new ArrayList<>();
            if (Objects.equals(type, DicDataEnum.XBDY_ENUM.getCode())) {
                data = getAllDataV(lineList, startTime, endTime);
            } else if (Objects.equals(type, DicDataEnum.XBDL_ENUM.getCode())) {
                data = getAllDataI(lineList, startTime, endTime);
            }
            if (!CollectionUtils.isEmpty(data)) {
                onlineCount = data.size();
                //在线监测点个数
                areaDTO.setOnlineCount(onlineCount);
                //超标监测点数
                for (RStatLimitTargetDPO pojo : data) {
                    if (Objects.equals(type, DicDataEnum.XBDY_ENUM.getCode())) {
                        if (pojo.getAllTime() > 0) {
                            overLineCount = overLineCount + 1;
                        }
                    } else if (Objects.equals(type, DicDataEnum.XBDL_ENUM.getCode())) {
                        if (pojo.getAllTime() > 0) {
                            overLineCount = overLineCount + 1;
                        }
                    }
                }
            }
        }
        Map<LocalDate, List<RStatLimitTargetDPO>> map = list.stream().collect(Collectors.groupingBy(RStatLimitTargetDPO::getTime));
        for (LocalDate key : map.keySet()) {
            int overDay = 0;
            List<RStatLimitTargetDPO> l = map.get(key);
            for (RStatLimitTargetDPO pojo : l) {
                if (Objects.equals(type, DicDataEnum.XBDY_ENUM.getCode())) {
                    if (pojo.getUaberranceOvertime() > 0 || pojo.getUharm20Overtime() > 0 || pojo.getUharm3Overtime() > 0 || pojo.getUharm4Overtime() > 0 || pojo.getUharm5Overtime() > 0 || pojo.getUharm6Overtime() > 0 || pojo.getUharm7Overtime() > 0 || pojo.getUharm8Overtime() > 0 || pojo.getUharm9Overtime() > 0 || pojo.getUharm10Overtime() > 0 || pojo.getUharm11Overtime() > 0 || pojo.getUharm12Overtime() > 0 || pojo.getUharm13Overtime() > 0 || pojo.getUharm14Overtime() > 0 || pojo.getUharm15Overtime() > 0 || pojo.getUharm16Overtime() > 0 || pojo.getUharm17Overtime() > 0 || pojo.getUharm18Overtime() > 0 || pojo.getUharm19Overtime() > 0 || pojo.getUharm20Overtime() > 0 || pojo.getUharm21Overtime() > 0 || pojo.getUharm22Overtime() > 0 || pojo.getUharm23Overtime() > 0 || pojo.getUharm24Overtime() > 0 || pojo.getUharm25Overtime() > 0) {
                        overCountByDay = overCountByDay + 1;
                        overDay = overDay + 1;
                    }
                } else if (Objects.equals(type, DicDataEnum.XBDL_ENUM.getCode())) {
                    if (pojo.getIharm2Overtime() > 0 || pojo.getIharm3Overtime() > 0 || pojo.getIharm4Overtime() > 0 || pojo.getIharm5Overtime() > 0 || pojo.getIharm6Overtime() > 0 || pojo.getIharm7Overtime() > 0 || pojo.getIharm8Overtime() > 0 || pojo.getIharm9Overtime() > 0 || pojo.getIharm10Overtime() > 0 || pojo.getIharm11Overtime() > 0 || pojo.getIharm12Overtime() > 0 || pojo.getIharm13Overtime() > 0 || pojo.getIharm14Overtime() > 0 || pojo.getIharm15Overtime() > 0 || pojo.getIharm16Overtime() > 0 || pojo.getIharm17Overtime() > 0 || pojo.getIharm18Overtime() > 0 || pojo.getIharm19Overtime() > 0 || pojo.getIharm20Overtime() > 0 || pojo.getIharm21Overtime() > 0 || pojo.getIharm22Overtime() > 0 || pojo.getIharm23Overtime() > 0 || pojo.getIharm24Overtime() > 0 || pojo.getIharm25Overtime() > 0) {
                        overCountByDay = overCountByDay + 1;
                        overDay = overDay + 1;
                    }
                }
            }
            ratio = ratio + overDay * 1.0 / l.size();
        }
        //平均超标天数
        if (CollectionUtils.isEmpty(list)) {
            avgOverDay = -1.0;
        } else {
            avgOverDay = overLineCount == 0 ? 0.0 : BigDecimal.valueOf(overCountByDay * 1.0 / overLineCount).setScale(2, RoundingMode.HALF_UP).doubleValue();
        }
        //月监测点符合性超标占比
        ratio = map.size() == 0 ? -1.0 : BigDecimal.valueOf(ratio * 100 / map.size()).setScale(2, RoundingMode.HALF_UP).doubleValue();
        areaDTO.setOnlineCount(onlineCount);
        areaDTO.setOverLineCount(overLineCount);
        areaDTO.setAverageOverDay(avgOverDay);
        areaDTO.setRatio(Math.min(ratio, 100.0));
        //月监测点超标占比
        double lineRatio = onlineCount == 0 ? 0 : BigDecimal.valueOf(overLineCount * 100 / onlineCount).setScale(2, RoundingMode.HALF_UP).doubleValue();
        areaDTO.setLineRatio(Math.min(lineRatio, 100.0));
        return areaDTO;
    }

    /**
     * 功能描述: 处理区域在线监测点数、超标监测点数
     *
     * @param list 集合
     * @return
     * @author xy
     * @date 2022/2/25 15:05
     */
    private List<RStatLimitTargetDPO> getAllDataV(List<String> list, String startTime, String endTime) {
        return targetDMapper.getSumV(list, startTime, endTime);
    }

    private List<RStatLimitTargetDPO> getAllDataI(List<String> list, String startTime, String endTime) {
        return targetDMapper.getSumI(list, startTime, endTime);
    }


    /**
     * 功能描述: 获取告警频次
     *
     * @param lineList  监测点id
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param type      类型
     * @return
     * @author xy
     * @date 2022/4/24 16:47
     */
    private Integer getWarningInfo(List<String> lineList, String startTime, String endTime, String type) {
        Integer result = 0;
        if (Objects.equals(type, DicDataEnum.XBDY_ENUM.getCode())) {
            Integer sumAddV = targetDMapper.getSumAddV(lineList, startTime, endTime);
            if (ObjectUtil.isNotNull(sumAddV)) {
                result = sumAddV;
            } else {
                result = -1;
            }

        } else if (Objects.equals(type, DicDataEnum.XBDL_ENUM.getCode())) {
            Integer sumAddI = targetDMapper.getSumAddI(lineList, startTime, endTime);
            if (ObjectUtil.isNotNull(sumAddI)) {
                result = sumAddI;
            } else {
                result = -1;
            }

        }
        return result;
    }


    /**
     * 功能描述: 获取监测点超标天数
     *
     * @param lineList  监测点id
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param type      类型
     * @return
     * @author xy
     * @date 2022/4/24 16:47
     */
    private List<LimitTarget> getLineOverDays(List<String> lineList, String startTime, String endTime, String type) {
        List<LimitTarget> listInfo = new ArrayList<>();
        List<RStatLimitTargetDPO> sum = new ArrayList<>();
        if (Objects.equals(type, DicDataEnum.XBDY_ENUM.getCode())) {
            sum = targetDMapper.getSumV(lineList, startTime, endTime);

        } else if (Objects.equals(type, DicDataEnum.XBDL_ENUM.getCode())) {
            sum = targetDMapper.getSumI(lineList, startTime, endTime);

        }
        if (CollUtil.isNotEmpty(sum)) {
            sum.forEach(list -> {
                LimitTarget limitRatePO = BeanUtil.copyProperties(list, LimitTarget.class);
                limitRatePO.setLineId(list.getLineId());
                limitRatePO.setFlickerAllTime(list.getFlickerAllTime());
                limitRatePO.setFlickerOverTime(list.getFlickerOvertime());
                limitRatePO.setFreqDevOverTime(list.getFreqDevOvertime());
                limitRatePO.setIHarm2OverTime(list.getIharm2Overtime());
                limitRatePO.setIHarm3OverTime(list.getIharm3Overtime());
                limitRatePO.setIHarm4OverTime(list.getIharm4Overtime());
                limitRatePO.setIHarm5OverTime(list.getIharm5Overtime());
                limitRatePO.setIHarm6OverTime(list.getIharm6Overtime());
                limitRatePO.setIHarm7OverTime(list.getIharm7Overtime());
                limitRatePO.setIHarm8OverTime(list.getIharm8Overtime());
                limitRatePO.setIHarm9OverTime(list.getIharm9Overtime());
                limitRatePO.setIHarm10OverTime(list.getIharm10Overtime());
                limitRatePO.setIHarm11OverTime(list.getIharm11Overtime());
                limitRatePO.setIHarm12OverTime(list.getIharm12Overtime());
                limitRatePO.setIHarm13OverTime(list.getIharm13Overtime());
                limitRatePO.setIHarm14OverTime(list.getIharm14Overtime());
                limitRatePO.setIHarm15OverTime(list.getIharm15Overtime());
                limitRatePO.setIHarm16OverTime(list.getIharm16Overtime());
                limitRatePO.setIHarm17OverTime(list.getIharm17Overtime());
                limitRatePO.setIHarm18OverTime(list.getIharm18Overtime());
                limitRatePO.setIHarm19OverTime(list.getIharm19Overtime());
                limitRatePO.setIHarm20OverTime(list.getIharm20Overtime());
                limitRatePO.setIHarm21OverTime(list.getIharm21Overtime());
                limitRatePO.setIHarm22OverTime(list.getIharm22Overtime());
                limitRatePO.setIHarm23OverTime(list.getIharm23Overtime());
                limitRatePO.setIHarm24OverTime(list.getIharm24Overtime());
                limitRatePO.setIHarm25OverTime(list.getIharm25Overtime());
                limitRatePO.setINegOverTime(list.getINegOvertime());
                limitRatePO.setUAberranceOverTime(list.getUaberranceOvertime());
                limitRatePO.setUBalanceOverTime(list.getUbalanceOvertime());
                limitRatePO.setUHarm2OverTime(list.getUharm2Overtime());
                limitRatePO.setUHarm3OverTime(list.getUharm3Overtime());
                limitRatePO.setUHarm4OverTime(list.getUharm4Overtime());
                limitRatePO.setUHarm5OverTime(list.getUharm5Overtime());
                limitRatePO.setUHarm6OverTime(list.getUharm6Overtime());
                limitRatePO.setUHarm7OverTime(list.getUharm7Overtime());
                limitRatePO.setUHarm8OverTime(list.getUharm8Overtime());
                limitRatePO.setUHarm9OverTime(list.getUharm9Overtime());
                limitRatePO.setUHarm10OverTime(list.getUharm10Overtime());
                limitRatePO.setUHarm11OverTime(list.getUharm11Overtime());
                limitRatePO.setUHarm12OverTime(list.getUharm12Overtime());
                limitRatePO.setUHarm13OverTime(list.getUharm13Overtime());
                limitRatePO.setUHarm14OverTime(list.getUharm14Overtime());
                limitRatePO.setUHarm15OverTime(list.getUharm15Overtime());
                limitRatePO.setUHarm16OverTime(list.getUharm16Overtime());
                limitRatePO.setUHarm17OverTime(list.getUharm17Overtime());
                limitRatePO.setUHarm18OverTime(list.getUharm18Overtime());
                limitRatePO.setUHarm19OverTime(list.getUharm19Overtime());
                limitRatePO.setUHarm20OverTime(list.getUharm20Overtime());
                limitRatePO.setUHarm21OverTime(list.getUharm21Overtime());
                limitRatePO.setUHarm22OverTime(list.getUharm22Overtime());
                limitRatePO.setUHarm23OverTime(list.getUharm23Overtime());
                limitRatePO.setUHarm24OverTime(list.getUharm24Overtime());
                limitRatePO.setUHarm25OverTime(list.getUharm25Overtime());
                limitRatePO.setVoltageDevOverTime(list.getVoltageDevOvertime());

                limitRatePO.setInuHarm1OverTime(list.getInuharm1Overtime());
                limitRatePO.setInuHarm2OverTime(list.getInuharm2Overtime());
                limitRatePO.setInuHarm3OverTime(list.getInuharm3Overtime());
                limitRatePO.setInuHarm4OverTime(list.getInuharm4Overtime());
                limitRatePO.setInuHarm5OverTime(list.getInuharm5Overtime());
                limitRatePO.setInuHarm6OverTime(list.getInuharm6Overtime());
                limitRatePO.setInuHarm7OverTime(list.getInuharm7Overtime());
                limitRatePO.setInuHarm8OverTime(list.getInuharm8Overtime());
                limitRatePO.setInuHarm9OverTime(list.getInuharm9Overtime());
                limitRatePO.setInuHarm10OverTime(list.getInuharm10Overtime());
                limitRatePO.setInuHarm11OverTime(list.getInuharm11Overtime());
                limitRatePO.setInuHarm12OverTime(list.getInuharm12Overtime());
                limitRatePO.setInuHarm13OverTime(list.getInuharm13Overtime());
                limitRatePO.setInuHarm14OverTime(list.getInuharm14Overtime());
                limitRatePO.setInuHarm15OverTime(list.getInuharm15Overtime());
                limitRatePO.setInuHarm16OverTime(list.getInuharm16Overtime());

                limitRatePO.setFlickerOverTime(list.getFlickerOvertime());
                limitRatePO.setFlickerAllTime(list.getFlickerAllTime());
                limitRatePO.setFreqDevOverTime(list.getFreqDevOvertime());
                limitRatePO.setVoltageDevOverTime(list.getVoltageDevOvertime());
                limitRatePO.setUAberranceOverTime(list.getUaberranceOvertime());
                limitRatePO.setINegOverTime(list.getINegOvertime());

                listInfo.add(limitRatePO);
            });
        }
        return listInfo;
    }

    /**
     * 数据组装
     */
    private void buildData(List<HarmonicLineVO> result, List<LimitTarget> list, String type) {
        list.forEach(item -> {
            HarmonicLineVO harmonicLineVO = new HarmonicLineVO();
            harmonicLineVO.setId(item.getLineId());
            if (Objects.equals(type, DicDataEnum.XBDY_ENUM.getCode())) {
                harmonicLineVO.setOverThreeTimes(item.getUHarm3OverTime());
                harmonicLineVO.setOverFiveTimes(item.getUHarm5OverTime());
                harmonicLineVO.setOverSevenTimes(item.getUHarm7OverTime());
                harmonicLineVO.setOverElevenTimes(item.getUHarm11OverTime());
                harmonicLineVO.setOverThirteenTimes(item.getUHarm13OverTime());
                harmonicLineVO.setOverTwentyThreeTimes(item.getUHarm23OverTime());
                harmonicLineVO.setOverTwentyFiveTimes(item.getUHarm25OverTime());
                int otherTimes = item.getUAberranceOverTime() + item.getUHarm2OverTime() + item.getUHarm4OverTime() + item.getUHarm6OverTime() + item.getUHarm8OverTime() + item.getUHarm9OverTime() + item.getUHarm10OverTime() + item.getUHarm12OverTime() + item.getUHarm14OverTime() + item.getUHarm15OverTime() + item.getUHarm16OverTime() + item.getUHarm17OverTime() + item.getUHarm18OverTime() + item.getUHarm19OverTime() + item.getUHarm20OverTime() + item.getUHarm21OverTime() + item.getUHarm22OverTime() + item.getUHarm24OverTime();
                harmonicLineVO.setOtherTimes(otherTimes);
                List<Integer> over = Stream.of(item.getUAberranceOverTime(), item.getUHarm2OverTime(), item.getUHarm3OverTime(), item.getUHarm4OverTime(), item.getUHarm5OverTime(), item.getUHarm6OverTime(), item.getUHarm7OverTime(), item.getUHarm8OverTime(), item.getUHarm9OverTime(), item.getUHarm10OverTime(), item.getUHarm11OverTime(), item.getUHarm12OverTime(), item.getUHarm13OverTime(), item.getUHarm14OverTime(), item.getUHarm15OverTime(), item.getUHarm16OverTime(), item.getUHarm17OverTime(), item.getUHarm18OverTime(), item.getUHarm19OverTime(), item.getUHarm20OverTime(), item.getUHarm21OverTime(), item.getUHarm22OverTime(), item.getUHarm23OverTime(), item.getUHarm24OverTime(), item.getUHarm25OverTime()).collect(Collectors.toList());
                harmonicLineVO.setOverDays(Collections.max(over));
            } else if (Objects.equals(type, DicDataEnum.XBDL_ENUM.getCode())) {
                harmonicLineVO.setOverThreeTimes(item.getIHarm3OverTime());
                harmonicLineVO.setOverFiveTimes(item.getIHarm5OverTime());
                harmonicLineVO.setOverSevenTimes(item.getIHarm7OverTime());
                harmonicLineVO.setOverElevenTimes(item.getIHarm11OverTime());
                harmonicLineVO.setOverThirteenTimes(item.getIHarm13OverTime());
                harmonicLineVO.setOverTwentyThreeTimes(item.getIHarm23OverTime());
                harmonicLineVO.setOverTwentyFiveTimes(item.getIHarm25OverTime());
                int otherTimes = item.getIHarm2OverTime() + item.getIHarm4OverTime() + item.getIHarm6OverTime() + item.getIHarm8OverTime() + item.getIHarm9OverTime() + item.getIHarm10OverTime() + item.getIHarm12OverTime() + item.getIHarm14OverTime() + item.getIHarm15OverTime() + item.getIHarm16OverTime() + item.getIHarm17OverTime() + item.getIHarm18OverTime() + item.getIHarm19OverTime() + item.getIHarm20OverTime() + item.getIHarm21OverTime() + item.getIHarm22OverTime() + item.getIHarm24OverTime();
                harmonicLineVO.setOtherTimes(otherTimes);
                List<Integer> over = Stream.of(item.getIHarm2OverTime(), item.getIHarm3OverTime(), item.getIHarm4OverTime(), item.getIHarm5OverTime(), item.getIHarm6OverTime(), item.getIHarm7OverTime(), item.getIHarm8OverTime(), item.getIHarm9OverTime(), item.getIHarm10OverTime(), item.getIHarm11OverTime(), item.getIHarm12OverTime(), item.getIHarm13OverTime(), item.getIHarm14OverTime(), item.getIHarm15OverTime(), item.getIHarm16OverTime(), item.getIHarm17OverTime(), item.getIHarm18OverTime(), item.getIHarm19OverTime(), item.getIHarm20OverTime(), item.getIHarm21OverTime(), item.getIHarm22OverTime(), item.getIHarm23OverTime(), item.getIHarm24OverTime(), item.getIHarm25OverTime()).collect(Collectors.toList());
                harmonicLineVO.setOverDays(Collections.max(over));
            }
            result.add(harmonicLineVO);
        });
    }

}
