package com.njcn.harmonic.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.njcn.device.pq.api.GeneralDeviceInfoClient;
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.pq.pojo.param.DeviceInfoParam;
import com.njcn.device.pq.utils.PublicDateUtil;
import com.njcn.harmonic.mapper.SteadyExceedRateMapper;
import com.njcn.harmonic.pojo.po.LimitRatePO;
import com.njcn.harmonic.pojo.po.day.RStatLimitRateDPO;
import com.njcn.harmonic.pojo.vo.MonitorOverLimitVO;
import com.njcn.harmonic.pojo.vo.SteadyExceedRateCensusVO;
import com.njcn.harmonic.pojo.vo.SteadyExceedRateVO;
import com.njcn.harmonic.mapper.RStatLimitRateDMapper;
import com.njcn.harmonic.service.SteadyExceedRateService;
import com.njcn.harmonic.utils.PubUtils;
import com.njcn.influx.pojo.constant.InfluxDBTableConstant;
import com.njcn.supervision.pojo.param.user.UserReportParam;
import com.njcn.supervision.pojo.vo.user.UserLedgerVO;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @version 1.0.0
 * @author: chenchao
 * @date: 2022/04/12 14:03
 */
@Service
@AllArgsConstructor
public class SteadyExceedRateServiceImpl implements SteadyExceedRateService {

    private final GeneralDeviceInfoClient generalDeviceInfoClient;
    private final SteadyExceedRateMapper steadyExceedRateMapper;
    private final RStatLimitRateDMapper rateDMapper;
    private final UserLedgerFeignClient userLedgerFeignClient;


    @Override
    public List<SteadyExceedRateVO> getSteadyExceedRateData(DeviceInfoParam.BusinessParam steadyExceedParam) {
        List<SteadyExceedRateVO> steadyExceedRateVOS = new ArrayList<>();
        //按照条件获取实际运行终端综合信息
        List<GeneralDeviceDTO> deviceDataList = generalDeviceInfoClient.getPracticalRunDeviceInfo(steadyExceedParam).getData();
        Map<String, UserLedgerVO> userLedgerVOMap = new HashMap<>();
        if(steadyExceedParam.isUserLedger()){
            List<UserLedgerVO> userLedgerVOList = userLedgerFeignClient.selectUserList(new UserReportParam()).getData();
            userLedgerVOMap = userLedgerVOList.stream().collect(Collectors.toMap(UserLedgerVO::getId, Function.identity()));
        }

        for (GeneralDeviceDTO generalDeviceDTO: deviceDataList){
            List<String> lineIndexes = generalDeviceDTO.getLineIndexes();
            if (CollectionUtils.isEmpty(lineIndexes)) {
                continue;
            }
            SteadyExceedRateVO steadyExceedRateVO = new SteadyExceedRateVO();
            steadyExceedRateVO.setId(generalDeviceDTO.getIndex());
            steadyExceedRateVO.setName(generalDeviceDTO.getName());
            //组装子集数据树
            List<SteadyExceedRateVO> treeList = getTreeData(lineIndexes, steadyExceedParam,userLedgerVOMap,steadyExceedParam.getPowerFlag());
            //父级数据
            double parentRate = treeList.stream().mapToDouble(SteadyExceedRateVO::getSteadyExceedRate).average().orElse(0);
            if(parentRate == 3.14159){
                steadyExceedRateVO.setSteadyExceedRate(parentRate);
            }else {
                steadyExceedRateVO.setSteadyExceedRate(PubUtils.dataLimits(NumberUtil.round(parentRate, 2).doubleValue()));
            }
            steadyExceedRateVO.setChildren(treeList);
            steadyExceedRateVOS.add(steadyExceedRateVO);
        }
        return steadyExceedRateVOS;
    }

    @SneakyThrows
    @Override
    public SteadyExceedRateCensusVO getSteadyExceedRateCensus(DeviceInfoParam.BusinessParam steadyExceedCensusParam) {
        SteadyExceedRateCensusVO steadyExceedRateCensusVO = new SteadyExceedRateCensusVO();
        List<String> type = new ArrayList<>(), time = new ArrayList<>();
        List<List<Double>> steadyExceedList = new ArrayList<>();
        List<List<String>> tempIndex = new ArrayList<>();

        //按部门分类的实际运行终端综合信息
        List<GeneralDeviceDTO> deviceDataList = generalDeviceInfoClient.getPracticalRunDeviceInfo(steadyExceedCensusParam).getData();
        if (!CollectionUtils.isEmpty(deviceDataList)) {
            List<Map<String,Double>> maps=new ArrayList<>();
            for (GeneralDeviceDTO generalDeviceDTO: deviceDataList) {
                type.add("("+generalDeviceDTO.getLineIndexes().size()+")"+generalDeviceDTO.getName());

                List<String> lineIndexes = generalDeviceDTO.getLineIndexes();
                Map<String, Double> collect=new HashMap<>();
                if (CollUtil.isNotEmpty(lineIndexes)) {
                    List<MonitorOverLimitVO.DataVO> percentages = rateDMapper.getPercentages(lineIndexes, steadyExceedCensusParam.getSearchBeginTime(), steadyExceedCensusParam.getSearchEndTime());
                    collect = percentages.stream().collect(Collectors.toMap(MonitorOverLimitVO.DataVO::getTime, MonitorOverLimitVO.DataVO::getData));
                }
                maps.add(collect);
                //按部门分类的监测点索引集
                tempIndex.add(lineIndexes);
            }

            int timed = 0;
            switch (steadyExceedCensusParam.getTimeFlag()) {
                case 0:
                    //查询是年
                    time = getSteadyTimesByMouth(steadyExceedCensusParam.getSearchBeginTime(), steadyExceedCensusParam.getSearchEndTime());
                    timed = getSteadyByMouth(steadyExceedCensusParam.getSearchBeginTime(), steadyExceedCensusParam.getSearchEndTime());
                    for (int i =0; i<timed; i++) {
                        List<Double> steadyExceedRate = new ArrayList<>();
                        for (List<String> lineIndexes: tempIndex) {
                            if (!CollectionUtils.isEmpty(lineIndexes)) {
                                String beginTime = time.get(i)+"-01";
                                DateTime date = DateUtil.endOfMonth(new DateTime(beginTime));
                                String endTime = date.toString(DatePattern.NORM_DATE_PATTERN);

                                List<LimitRatePO> qualifiesRate = getQualifiesRate(lineIndexes, beginTime, endTime);
                                SteadyExceedRateVO dataMoreMonitorMoreDay = getDataMoreMonitorMoreDay(qualifiesRate);
                                steadyExceedRate.add(dataMoreMonitorMoreDay.getSteadyExceedRate());
                            } else {
                                steadyExceedRate.add(3.14159);
                            }
                        }
                        steadyExceedList.add(steadyExceedRate);
                    }
                    break;
                case 1:
                    //查询是天
                    List<String> intervalTime = PubUtils.getIntervalTime(steadyExceedCensusParam.getSearchBeginTime(),steadyExceedCensusParam.getSearchEndTime());
                    for (int j = 0; j < intervalTime.size(); j++) {

                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        Date dt ;
                        Date dtDate;
                        int beginDay;
                        if(j==0){
                            dt= simpleDateFormat.parse(steadyExceedCensusParam.getSearchBeginTime());
                            beginDay = Integer.valueOf(String.format("%td", dt));
                        }else{
                            String startTime = PublicDateUtil.getFisrtDayOfMonth(Integer.parseInt(intervalTime.get(j).substring(0, 4)), Integer.parseInt(intervalTime.get(j).substring(5)));
                            dt= simpleDateFormat.parse(startTime);
                            beginDay = Integer.valueOf(String.format("%td", dt));
                        }
                        if(j==intervalTime.size()-1){
                            dtDate= simpleDateFormat.parse(steadyExceedCensusParam.getSearchEndTime());
                        }else{
                            String startTime = PublicDateUtil.getLastDayOfMonth(Integer.parseInt(intervalTime.get(j).substring(0, 4)), Integer.parseInt(intervalTime.get(j).substring(5)));
                            dtDate= simpleDateFormat.parse(startTime);
                        }
                        Integer year = Integer.valueOf(String.format("%tY", dt));
                        Integer mon = Integer.valueOf(String.format("%tm", dt));

                        Integer day = Integer.valueOf(String.format("%td", dtDate));
                        List<String> dayTime = PubUtils.getIntervalDateTime(year,beginDay, mon, day);
                        for (String s : dayTime) {
                            List<Double> steadyExceedRate = new ArrayList<>();
                            for (int i = 0; i < tempIndex.size(); i++) {

                                if (CollUtil.isNotEmpty(maps)&&CollUtil.isNotEmpty(maps.get(i))) {
                                    if (maps.get(i).containsKey(s)) {
                                        Double data = maps.get(i).get(s);
                                        steadyExceedRate.add(data);
                                    } else {
                                        steadyExceedRate.add(3.14159);
                                    }
                                } else {
                                    steadyExceedRate.add(3.14159);
                                }
                            }
                            steadyExceedList.add(steadyExceedRate);
                            time.add(s);
                        }
                    }
                    break;
                case 2:
                    time = getSteadyTimesByDay(steadyExceedCensusParam.getSearchBeginTime(), steadyExceedCensusParam.getSearchEndTime());
                    List<Double> steadyExceedRate = new ArrayList<>();
                    for (List<String> lineIndexes: tempIndex) {
                        if (!CollectionUtils.isEmpty(lineIndexes)) {
                            List<LimitRatePO> qualifiesRate = getQualifiesRate(lineIndexes, steadyExceedCensusParam.getSearchBeginTime(), steadyExceedCensusParam.getSearchEndTime());
                            SteadyExceedRateVO dataMoreMonitorSingleDay = getDataMoreMonitorSingleDay(qualifiesRate, lineIndexes, steadyExceedCensusParam.getSearchBeginTime());
                            steadyExceedRate.add(dataMoreMonitorSingleDay.getSteadyExceedRate());
                        } else {
                            steadyExceedRate.add(3.14159);
                        }
                    }
                    steadyExceedList.add(steadyExceedRate);
                    break;
            }
        }
        steadyExceedRateCensusVO.setType(type);
        steadyExceedRateCensusVO.setTime(time);
        steadyExceedRateCensusVO.setSteadyExceedRate(steadyExceedList);
        return steadyExceedRateCensusVO;
    }



    /** 根据时间范围返回相应单位的时间整数
     */
    private int getSteadyByMouth(String searchBeginTime, String searchEndTime) {
        int beginMouthTime = Integer.parseInt(searchBeginTime.substring(5, 7));
        int endMouthTime = Integer.parseInt(searchEndTime.substring(5, 7));
        int mouth = endMouthTime - beginMouthTime + 1;
        return mouth;
    }
    private int getSteadyByDay(String searchBeginTime, String searchEndTime) {
        int beginTime = Integer.parseInt(searchBeginTime.substring(8, 10));
        int endTime = Integer.parseInt(searchEndTime.substring(8, 10));
        int day = endTime - beginTime + 1;
        return day;
    }
    /** 根据时间范围返回相应单位的时间格式字符串
     */
    private List<String> getSteadyTimesByMouth(String searchBeginTime, String searchEndTime) {
        List<String> string = new ArrayList<>();
        int beginMouthTime = Integer.parseInt(searchBeginTime.substring(5, 7));
        int endMouthTime = Integer.parseInt(searchEndTime.substring(5, 7));
        int size=(endMouthTime - beginMouthTime) + 1;
        for (int i =0; i<size; i++) {
            string.add(searchBeginTime.substring(0, 5)+(beginMouthTime++));
        }
        return string;
    }


    public static List<String> getSteadyTimesByDay(String searchBeginTime, String searchEndTime) {
        List<String> string = new ArrayList<>();
        int beginTime = Integer.parseInt(searchBeginTime.substring(8, 10));
        int endTime = Integer.parseInt(searchEndTime.substring(8, 10));
        int a =0;
        for (int i =0; i<endTime - beginTime + 1; i++) {
            if (a<9) {
                a = beginTime + i;
                string.add(searchBeginTime.substring(0, 8)+"0"+a);
            } else {
                a = beginTime + i;
                string.add(searchBeginTime.substring(0, 8)+a);
            }
        }
        return string;
    }


    /**
     * 获取父级每层数据
     */
    private List<SteadyExceedRateVO> getTreeData(List<String> lineIndexes, DeviceInfoParam.BusinessParam steadyExceedParam,Map<String,UserLedgerVO> userLedgerVOMap,Integer powerFlag) {
        //监测点集合
        List<SteadyExceedRateVO> monitorList = steadyExceedRateMapper.getSteadyExceedRateData(lineIndexes);

        List<LimitRatePO> qualifiesRate = getQualifiesRate(lineIndexes, steadyExceedParam.getSearchBeginTime(), steadyExceedParam.getSearchEndTime());
        //根据监测点分组
        Map<String, List<LimitRatePO>> lineList = qualifiesRate.stream().collect(Collectors.groupingBy(LimitRatePO::getLineId));
        monitorList.forEach(steadyExceedRateVO -> {
            if(lineList.containsKey(steadyExceedRateVO.getId())){
                SteadyExceedRateVO dataSingleMonitorMoreDay = getDataSingleMonitorMoreDay(lineList.get(steadyExceedRateVO.getId()));
                steadyExceedRateVO.setSteadyExceedRate(PubUtils.dataLimits(dataSingleMonitorMoreDay.getSteadyExceedRate()));
            }else{
                steadyExceedRateVO.setSteadyExceedRate(3.14159);
            }
        });


        List<SteadyExceedRateVO> userLedgerList = new ArrayList<>();
        List<SteadyExceedRateVO> powerLedgerList = new ArrayList<>();
        if(Objects.equals(PowerFlagEnum.NO_GRID_SIDE.getCode(),powerFlag)){
            userLedgerList = monitorList.stream().filter(it -> StrUtil.isNotBlank(it.getObjId())).collect(Collectors.toList());
        }else if(Objects.equals(PowerFlagEnum.GRID_SIDE.getCode(),powerFlag)){
            powerLedgerList = monitorList.stream().filter(it -> StrUtil.isBlank(it.getObjId())).collect(Collectors.toList());
        }else {
            userLedgerList = monitorList.stream().filter(it -> StrUtil.isNotBlank(it.getObjId())).collect(Collectors.toList());
            powerLedgerList = monitorList.stream().filter(it -> StrUtil.isBlank(it.getObjId())).collect(Collectors.toList());
        }

        List<SteadyExceedRateVO> userTemList = new ArrayList<>();
        if(CollUtil.isNotEmpty(userLedgerList)){
            Map<String,List<SteadyExceedRateVO>> objMap = userLedgerList.stream().collect(Collectors.groupingBy(SteadyExceedRateVO::getObjId));
            objMap.forEach((obj,list) -> {
                SteadyExceedRateVO thDistortionVO = new SteadyExceedRateVO();
                if (userLedgerVOMap.containsKey(obj)) {
                    UserLedgerVO userLedgerVO = userLedgerVOMap.get(obj);
                    thDistortionVO.setId(userLedgerVO.getId());
                    thDistortionVO.setName(userLedgerVO.getProjectName());
                    thDistortionVO.setPid(userLedgerVO.getStationId());
                    thDistortionVO.setSteadyExceedRate(list.stream().filter(it->it.getSteadyExceedRate()!=3.14159).mapToDouble(SteadyExceedRateVO::getSteadyExceedRate).average().orElse(3.14159));
                    thDistortionVO.setChildren(list);
                    userTemList.add(thDistortionVO);
                }
            });
        }


        //变电站集合
        List<SteadyExceedRateVO> substationList = steadyExceedRateMapper.getLineInfoByList(monitorList.stream().map(it->it.getPidS().split(StrUtil.COMMA)[LineBaseEnum.SUB_LEVEL.getCode()])
                .distinct().collect(Collectors.toList()));
        //供电公司集合
        List<SteadyExceedRateVO> powerCompanyList = steadyExceedRateMapper.getLineInfoByList(monitorList.stream().map(it->it.getPidS().split(StrUtil.COMMA)[LineBaseEnum.GD_LEVEL.getCode()])
                .distinct().collect(Collectors.toList()));

        setChildesList(substationList,powerLedgerList,userTemList);
        setFatherDistortion(substationList);
        setSubstationData(substationList);
        powerCompanyList.stream().peek(item -> item.setChildren(getChildCategoryList(item, substationList))).collect(Collectors.toList());
        setFatherDistortion(powerCompanyList);
        return powerCompanyList;
    }

    //查变电站信息
    private void setSubstationData(List<SteadyExceedRateVO> substationList) {
        List<String> ids = new ArrayList<>();
        substationList.forEach(steadyExceedRateVO -> {
            ids.add(steadyExceedRateVO.getId());
        });
        List<SteadyExceedRateVO> substation = steadyExceedRateMapper.getSubstationList(ids);
        substationList.stream().map(list1 -> substation.stream().filter(list2 -> Objects.equals(list1.getId(), list2.getId())).findAny().map(m -> {
            list1.setVoltageLevel(m.getVoltageLevel());
            return list1;
        })).collect(Collectors.toList());
    }
    /**
     * 计算父级合格率
     */
    private void setFatherDistortion(List<SteadyExceedRateVO> list) {
        list.forEach(steadyExceedRateVO -> {
            List<SteadyExceedRateVO> children = steadyExceedRateVO.getChildren();
            List<SteadyExceedRateVO> flicker = children.stream().filter(child -> !Objects.equals(child.getSteadyExceedRate(), 3.14159)).collect(Collectors.toList());

            if (!CollectionUtils.isEmpty(flicker)) {
                steadyExceedRateVO.setSteadyExceedRate(PubUtils.dataLimits(NumberUtil.round(flicker.stream().mapToDouble(SteadyExceedRateVO::getSteadyExceedRate).average().orElse(1.2345), 2).doubleValue()));
            }
        });
    }
    /**
     * 组装树层级
     */
    private List<SteadyExceedRateVO> getChildCategoryList(SteadyExceedRateVO item, List<SteadyExceedRateVO> child) {
        return child.stream().filter(allItem -> allItem.getPid().equals(item.getId())).collect(Collectors.toList());
    }
    /**
     * @Description:
     * @param item
     * @param childes 用户
     * @param userList 变电站
     * @Author: wr
     * @Date: 2025/5/13 9:27
     */
    private void setChildesList(List<SteadyExceedRateVO> item, List<SteadyExceedRateVO> childes,List<SteadyExceedRateVO> userList) {
        //groupLine变电站索引和监测点集合
        Map<String, List<SteadyExceedRateVO>> groupLine;
        groupLine = childes.stream().collect(Collectors.groupingBy(thDistortionVO -> {
            String[] pid = thDistortionVO.getPidS().split(StrUtil.COMMA);
            return pid[LineBaseEnum.SUB_LEVEL.getCode()];
        }));

        Map<String,List<SteadyExceedRateVO>> userMap = userList.stream().collect(Collectors.groupingBy(SteadyExceedRateVO::getPid));
        item.forEach(thDistortionVO -> {
            List<SteadyExceedRateVO> temList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(groupLine.get(thDistortionVO.getId()))) {
                temList.addAll(groupLine.get(thDistortionVO.getId()));
            }
            if(userMap.containsKey(thDistortionVO.getId())){
                temList.addAll(userMap.get(thDistortionVO.getId()));
            }
            thDistortionVO.setChildren(temList);
        });
    }

    /**
     * 计算一个监测点日统计占比率
     */
    public List<SteadyExceedRateVO> getDataSingleMonitorSingeDay(List<LimitRatePO> qualifiesRate) {
        List<SteadyExceedRateVO> list=new ArrayList<>();
        SteadyExceedRateVO steadyExceedRateVO = new SteadyExceedRateVO();
        if (!CollectionUtil.isEmpty(qualifiesRate)) {
            for (LimitRatePO limitRatePO : qualifiesRate) {
                steadyExceedRateVO = new SteadyExceedRateVO();

                double calculate = calculate(limitRatePO.getAllTime(),
                        limitRatePO.getFlickerOverTime() +
                                limitRatePO.getFreqDevOverTime() +
                                limitRatePO.getINegOverTime() +
                                limitRatePO.getUAberranceOverTime() +
                                limitRatePO.getUBalanceOverTime() +
                                limitRatePO.getVoltageDevOverTime() +
                                limitRatePO.getFlickerAllTime() +
                                limitRatePO.getIHarm2OverTime() + limitRatePO.getIHarm3OverTime() + limitRatePO.getIHarm4OverTime() + limitRatePO.getIHarm5OverTime() + limitRatePO.getIHarm6OverTime() + limitRatePO.getIHarm7OverTime() + limitRatePO.getIHarm8OverTime() + limitRatePO.getIHarm9OverTime() + limitRatePO.getIHarm10OverTime() + limitRatePO.getIHarm11OverTime() + limitRatePO.getIHarm12OverTime() + limitRatePO.getIHarm13OverTime() + limitRatePO.getIHarm14OverTime() + limitRatePO.getIHarm15OverTime() + limitRatePO.getIHarm16OverTime() + limitRatePO.getIHarm17OverTime() + limitRatePO.getIHarm18OverTime() + limitRatePO.getIHarm19OverTime() + limitRatePO.getIHarm20OverTime() + limitRatePO.getIHarm21OverTime() + limitRatePO.getIHarm22OverTime() + limitRatePO.getIHarm23OverTime() + limitRatePO.getIHarm24OverTime() + limitRatePO.getIHarm25OverTime() +
                                limitRatePO.getUHarm2OverTime() + limitRatePO.getUHarm3OverTime() + limitRatePO.getUHarm4OverTime() + limitRatePO.getUHarm5OverTime() + limitRatePO.getUHarm6OverTime() + limitRatePO.getUHarm7OverTime() + limitRatePO.getUHarm8OverTime() + limitRatePO.getUHarm9OverTime() + limitRatePO.getUHarm10OverTime() + limitRatePO.getUHarm11OverTime() + limitRatePO.getUHarm12OverTime() + limitRatePO.getUHarm13OverTime() + limitRatePO.getUHarm14OverTime() + limitRatePO.getUHarm15OverTime() + limitRatePO.getUHarm16OverTime() + limitRatePO.getUHarm17OverTime() + limitRatePO.getUHarm18OverTime() + limitRatePO.getUHarm19OverTime() + limitRatePO.getUHarm20OverTime() + limitRatePO.getUHarm21OverTime() + limitRatePO.getUHarm22OverTime() + limitRatePO.getUHarm23OverTime() + limitRatePO.getUHarm24OverTime() + limitRatePO.getUHarm25OverTime() +
                                limitRatePO.getInUHARM1OverTime() + limitRatePO.getInUHARM2OverTime() + limitRatePO.getInUHARM3OverTime() + limitRatePO.getInUHARM4OverTime() + limitRatePO.getInUHARM5OverTime() + limitRatePO.getInUHARM6OverTime() + limitRatePO.getInUHARM7OverTime() + limitRatePO.getInUHARM8OverTime() + limitRatePO.getInUHARM9OverTime() + limitRatePO.getInUHARM10OverTime() + limitRatePO.getInUHARM11OverTime() + limitRatePO.getInUHARM12OverTime() + limitRatePO.getInUHARM13OverTime() + limitRatePO.getInUHARM14OverTime() + limitRatePO.getInUHARM15OverTime() + limitRatePO.getInUHARM16OverTime());
                steadyExceedRateVO.setSteadyExceedRate(calculate);
                list.add(steadyExceedRateVO);
            }
        }
        return list;
    }
    /**
     * 计算一个监测点月统计占比率
     */
    public SteadyExceedRateVO getDataSingleMonitorMouth(List<LimitRatePO> qualifiesRate, String lineId, String time) {
        SteadyExceedRateVO steadyExceedRateVO = new SteadyExceedRateVO();
        LimitRatePO limitRatePO;
        List<LimitRatePO> limitRatePOList = qualifiesRate.stream().filter(
                temp -> temp.getLineId().equalsIgnoreCase(lineId) && temp.getMouthStr().equalsIgnoreCase(time)
        ).collect(Collectors.toList());
        if (!CollectionUtil.isEmpty(limitRatePOList)) {
            limitRatePO = limitRatePOList.get(0);

            double calculate = calculate(limitRatePO.getAllTime(),
                    limitRatePO.getFlickerOverTime() +
                            limitRatePO.getFreqDevOverTime() +
                            limitRatePO.getINegOverTime() +
                            limitRatePO.getUAberranceOverTime() +
                            limitRatePO.getUBalanceOverTime() +
                            limitRatePO.getVoltageDevOverTime() +
                            limitRatePO.getFlickerAllTime() +
                            limitRatePO.getIHarm2OverTime() + limitRatePO.getIHarm3OverTime() + limitRatePO.getIHarm4OverTime() + limitRatePO.getIHarm5OverTime() + limitRatePO.getIHarm6OverTime() + limitRatePO.getIHarm7OverTime() + limitRatePO.getIHarm8OverTime() + limitRatePO.getIHarm9OverTime() + limitRatePO.getIHarm10OverTime() + limitRatePO.getIHarm11OverTime() + limitRatePO.getIHarm12OverTime() + limitRatePO.getIHarm13OverTime() + limitRatePO.getIHarm14OverTime() + limitRatePO.getIHarm15OverTime() + limitRatePO.getIHarm16OverTime() + limitRatePO.getIHarm17OverTime() + limitRatePO.getIHarm18OverTime() + limitRatePO.getIHarm19OverTime() + limitRatePO.getIHarm20OverTime() + limitRatePO.getIHarm21OverTime() + limitRatePO.getIHarm22OverTime() + limitRatePO.getIHarm23OverTime() + limitRatePO.getIHarm24OverTime() + limitRatePO.getIHarm25OverTime() +
                            limitRatePO.getUHarm2OverTime() + limitRatePO.getUHarm3OverTime() + limitRatePO.getUHarm4OverTime() + limitRatePO.getUHarm5OverTime() + limitRatePO.getUHarm6OverTime() + limitRatePO.getUHarm7OverTime() + limitRatePO.getUHarm8OverTime() + limitRatePO.getUHarm9OverTime() + limitRatePO.getUHarm10OverTime() + limitRatePO.getUHarm11OverTime() + limitRatePO.getUHarm12OverTime() + limitRatePO.getUHarm13OverTime() + limitRatePO.getUHarm14OverTime() + limitRatePO.getUHarm15OverTime() + limitRatePO.getUHarm16OverTime() + limitRatePO.getUHarm17OverTime() + limitRatePO.getUHarm18OverTime() + limitRatePO.getUHarm19OverTime() + limitRatePO.getUHarm20OverTime() + limitRatePO.getUHarm21OverTime() + limitRatePO.getUHarm22OverTime() + limitRatePO.getUHarm23OverTime() + limitRatePO.getUHarm24OverTime() + limitRatePO.getUHarm25OverTime() +
                            limitRatePO.getInUHARM1OverTime() + limitRatePO.getInUHARM2OverTime() + limitRatePO.getInUHARM3OverTime() + limitRatePO.getInUHARM4OverTime() + limitRatePO.getInUHARM5OverTime() + limitRatePO.getInUHARM6OverTime() + limitRatePO.getInUHARM7OverTime() + limitRatePO.getInUHARM8OverTime() + limitRatePO.getInUHARM9OverTime() + limitRatePO.getInUHARM10OverTime() + limitRatePO.getInUHARM11OverTime() + limitRatePO.getInUHARM12OverTime() + limitRatePO.getInUHARM13OverTime() + limitRatePO.getInUHARM14OverTime() + limitRatePO.getInUHARM15OverTime() + limitRatePO.getInUHARM16OverTime());
                steadyExceedRateVO.setSteadyExceedRate(calculate);
            } else {
                steadyExceedRateVO.setSteadyExceedRate(0.00);
        }

        return steadyExceedRateVO;
    }

    /**
     * 计算一个监测点时间范围统计占比率
     */
    public SteadyExceedRateVO getDataSingleMonitorMoreDay(List<LimitRatePO> qualifiesRate) {
        SteadyExceedRateVO steadyExceedRateVO = new SteadyExceedRateVO();
        List<SteadyExceedRateVO> steadyExceedRateVOS = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(qualifiesRate)) {
            //直接把所有的时间的信息返回出来
            steadyExceedRateVOS.addAll(getDataSingleMonitorSingeDay(qualifiesRate));
            //求时间范围的占比率平均值
            steadyExceedRateVO.setSteadyExceedRate(NumberUtil.round(steadyExceedRateVOS.stream().filter(x->x.getSteadyExceedRate()!=3.14159)
                    .mapToDouble(SteadyExceedRateVO::getSteadyExceedRate).average().orElse(0), 2).doubleValue());

        }
        return steadyExceedRateVO;
    }

    /**
     * 计算区域监测点时间范围统计占比率
     */
    public SteadyExceedRateVO getDataMoreMonitorMoreDay(List<LimitRatePO> qualifiesRate) {
        SteadyExceedRateVO steadyExceedRateVO = new SteadyExceedRateVO();
        List<SteadyExceedRateVO> steadyResults = new ArrayList<>();
        //以时间分组的各项数据
//        Map<String, List<LimitRatePO>> groupByTimeData = qualifiesRate.stream().collect(Collectors.groupingBy(LimitRatePO::getDayStr));
//        if (CollectionUtil.isNotEmpty(groupByTimeData)) {
//            Set<String> times = groupByTimeData.keySet();
//            for (String time : times) {
//                List<String> ids = groupByTimeData.get(time).stream().map(LimitRatePO::getLineId).collect(Collectors.toList());
//                steadyResults.add(getDataMoreMonitorSingleDay(qualifiesRate, ids, time));
//            }
//        }
        if(CollUtil.isNotEmpty(qualifiesRate)){
            steadyResults.add(getDataMoreMonitorSingleDay(qualifiesRate,null,null));
        }
        if (CollectionUtil.isNotEmpty(steadyResults)) {
            //求区域监测点多天的平均值
            steadyExceedRateVO.setSteadyExceedRate(PubUtils.dataLimits(NumberUtil.round(steadyResults.stream().filter(item -> item.getSteadyExceedRate()!=3.14159)
                    .mapToDouble(SteadyExceedRateVO::getSteadyExceedRate).average().orElse(0), 2).doubleValue()));
        }
        return steadyExceedRateVO;
    }

    /**
     * 计算区域监测点日统计占比率
     */
    public SteadyExceedRateVO getDataMoreMonitorSingleDay(List<LimitRatePO> qualifiesRate, List<String> lineIds, String time) {
        SteadyExceedRateVO steadyExceedRateVO = new SteadyExceedRateVO();
        List<SteadyExceedRateVO> steadyResults = new ArrayList<>();
//        for (String lineId : lineIds) {
//            steadyResults.add(getDataSingleMonitorSingeDay(qualifiesRate, lineId, time));
//        }
        //直接统计当前部门下面的全部监测点信息
        steadyResults.addAll(getDataSingleMonitorSingeDay(qualifiesRate));
        steadyResults = steadyResults.stream().filter(item -> item.getSteadyExceedRate()!=3.14159).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(steadyResults)) {
            //求多个监测点的平均值
            steadyExceedRateVO.setSteadyExceedRate(PubUtils.dataLimits(NumberUtil.round(steadyResults.stream().mapToDouble(SteadyExceedRateVO::getSteadyExceedRate).average().orElse(0), 2).doubleValue()));

        }
        steadyExceedRateVO.setTime(time);
        return steadyExceedRateVO;
    }

    /**
     * 计算区域监测点月统计占比率
     */
    public SteadyExceedRateVO getDataMoreMonitorMouth(List<LimitRatePO> qualifiesRate, List<String> lineIds, String time) {
        SteadyExceedRateVO steadyExceedRateVO = new SteadyExceedRateVO();
        List<SteadyExceedRateVO> steadyResults = new ArrayList<>();
        for (String lineId : lineIds) {
            steadyResults.add(getDataSingleMonitorMouth(qualifiesRate, lineId, time));
        }
        if (CollectionUtil.isNotEmpty(steadyResults)) {
            //求多个监测点的平均值
            steadyExceedRateVO.setSteadyExceedRate(NumberUtil.round(steadyResults.stream().mapToDouble(SteadyExceedRateVO::getSteadyExceedRate).average().orElse(0), 2).doubleValue());
            steadyExceedRateVO.setTime(time);
        }
        return steadyExceedRateVO;
    }

    /**
     * influxDB查询稳态监测点相关信息
     * @param lineIndexes
     * @param startTime
     * @param endTime
     */
    private List<LimitRatePO> getQualifiesRate(List<String> lineIndexes, String startTime, String endTime) {
        List<LimitRatePO> limitRatePOS = new ArrayList<>();
        List<RStatLimitRateDPO> limitRates = rateDMapper.selectList(new LambdaQueryWrapper<RStatLimitRateDPO>()
                .in(RStatLimitRateDPO::getLineId, lineIndexes)
                .eq(RStatLimitRateDPO::getPhasicType, InfluxDBTableConstant.PHASE_TYPE_T)
                .ge(StrUtil.isNotBlank(startTime), RStatLimitRateDPO::getTime, DateUtil.beginOfDay(DateUtil.parse(startTime)))
                .le(StrUtil.isNotBlank(endTime), RStatLimitRateDPO::getTime, DateUtil.endOfDay(DateUtil.parse(endTime)))
        );
        if(CollUtil.isNotEmpty(limitRates)){
            limitRates.forEach(list ->{
                LimitRatePO limitRatePO = new LimitRatePO();
                limitRatePO.setDayStr(list.getTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                limitRatePO.setMouthStr(list.getTime().format(DateTimeFormatter.ofPattern("yyyy-MM")));
                LocalDateTime localDateTime = list.getTime().atStartOfDay();

                Instant instant = localDateTime.toInstant(ZoneOffset.ofHours(8));
                limitRatePO.setTime(instant);

                limitRatePO.setLineId(list.getLineId());
                limitRatePO.setPhasicType(list.getPhasicType());
                limitRatePO.setAllTime(list.getAllTime());
                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.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.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());
                limitRatePOS.add(limitRatePO);
            });
        }
        return  limitRatePOS;

    }

    /**
     * 总占比
     *
     * @param allTime
     * @param overTime
     * @return
     */
    private static double calculate(Integer allTime, Integer overTime) {
        if (allTime == 0) {
            return 3.14159;
        } else {
            return NumberUtil.round((1 - (overTime / (allTime * 71.0))) * 100, 2).doubleValue();
        }
    }

}
