package com.njcn.harmonic.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import com.njcn.common.utils.PubUtils;
import com.njcn.device.biz.commApi.CommTerminalGeneralClient;
import com.njcn.device.biz.pojo.dto.DeptGetChildrenMoreDTO;
import com.njcn.device.biz.pojo.dto.LineDevGetDTO;
import com.njcn.device.biz.pojo.param.DeptGetLineParam;
import com.njcn.device.pq.api.GeneralDeviceInfoClient;
import com.njcn.device.pq.api.LineFeignClient;
import com.njcn.device.pq.pojo.po.LineDetail;
import com.njcn.device.pq.pojo.vo.AreaLineInfoVO;
import com.njcn.harmonic.mapper.*;
import com.njcn.harmonic.pojo.param.hebeinorth.AssessParam;
import com.njcn.harmonic.pojo.po.PQSComAssesPO;
import com.njcn.harmonic.pojo.po.PqsComasses;
import com.njcn.harmonic.pojo.po.RStatDataVD;
import com.njcn.harmonic.pojo.po.day.*;
import com.njcn.harmonic.pojo.vo.RStatLimitTargetVO;
import com.njcn.harmonic.pojo.vo.hebeinorth.AssessDetailVo;
import com.njcn.harmonic.pojo.vo.hebeinorth.AssessVo;
import com.njcn.harmonic.pojo.vo.hebeinorth.EvaluationLevelVo;
import com.njcn.harmonic.pojo.vo.hebeinorth.EvaluationVo;
import com.njcn.harmonic.common.mapper.RStatDataIDMapper;
import com.njcn.harmonic.common.mapper.RStatDataInharmVDMapper;
import com.njcn.harmonic.common.mapper.RStatDataVDMapper;
import com.njcn.harmonic.common.mapper.RStatLimitRateDMapper;
import com.njcn.harmonic.service.hebeinorth.IGridService;
import com.njcn.harmonic.util.ComAssesUtil;
import com.njcn.harmonic.util.TimeUtil;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.system.enums.DicDataTypeEnum;
import com.njcn.system.pojo.po.DictData;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.user.pojo.dto.DeptDTO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 类的介绍：
 *
 * @author xuyang
 * @version 1.0.0
 * @createTime 2024/4/24 17:21
 */
@Service
@RequiredArgsConstructor
public class GridServiceImpl implements IGridService {

    private final CommTerminalGeneralClient commTerminalGeneralClient;
    private final RStatAssesDMapper rStatAssesDMapper;
    private final RStatComassesDMapper rStatComassesDMapper;
    private final RStatLimitRateDMapper rStatLimitRateDMapper;
    private final ComAssesUtil comAssesUtil;
    private final LineFeignClient lineFeignClient;
    private final RStatDataVDMapper statDataVDMapper;
    private final RStatDataIDMapper statDataIDMapper;
    private final RStatDataPltDMapper statDataPltDMapper;
    private final RStatDataInharmVDMapper rStatDataInharmVDMapper;
    private final RStatLimitTargetDMapper rStatLimitTargetDMapper;
    private final GeneralDeviceInfoClient generalDeviceInfoClient;
    private final DeptFeignClient deptFeignClient;
    private final DicDataFeignClient dicDataFeignClient;

    @Override
    public AssessVo.AssessOverview getAssessOverview(AssessParam param) {
        AssessVo.AssessOverview overview = new AssessVo.AssessOverview();
        List<AssessVo> children = new ArrayList<>();
        DeptGetLineParam deptGetLineParam = new DeptGetLineParam();
        deptGetLineParam.setDeptId(param.getDeptIndex());
        deptGetLineParam.setLineRunFlag(0);
        List<DeptGetChildrenMoreDTO> list = commTerminalGeneralClient.deptGetLine(deptGetLineParam).getData();
        //获取监测点集合
        Map<String, List<String>> lineMap = this.getLineMap(list, param.getIsUpToGrid(), null);
        List<String> lineList = lineMap.values().stream()
                .flatMap(List::stream)
                .distinct()
                .collect(Collectors.toList());
        if (CollUtil.isNotEmpty(lineList)) {
            List<PqsComasses> comasses = new ArrayList<>();
            //获取监测点详细信息
            List<LineDetail> lineDetailList = lineFeignClient.getLineDetail(lineList).getData();
            Map<String, List<LineDetail>> lineDetailMap = lineDetailList.stream().collect(Collectors.groupingBy(LineDetail::getActualArea));
            //获取综合评估
            List<PQSComAssesPO> assesList = rStatComassesDMapper.getAvgCount(lineList, param.getStartTime(), param.getEndTime());
            //获取部门
            List<DeptDTO> deptList = deptFeignClient.getDepSonDetailByDeptId(param.getDeptIndex()).getData();
            deptList.forEach(item -> {
                if (lineDetailMap.containsKey(item.getArea())) {
                    AssessVo assessVo = new AssessVo();
                    assessVo.setName(item.getName());
                    assessVo.setCode(item.getCode());
                    List<String> ll = lineDetailMap.get(item.getArea()).stream().map(LineDetail::getId).collect(Collectors.toList());
                    List<PQSComAssesPO> deptAssessList = assesList.stream().filter(it -> ll.contains(it.getLineId())).collect(Collectors.toList());
                    List<PqsComasses> communicateList = BeanUtil.copyToList(deptAssessList, PqsComasses.class);
                    if (CollUtil.isNotEmpty(communicateList)) {
                        float synData = comAssesUtil.getAllComAss(communicateList);
                        assessVo.setScore(PubUtils.floatRound(2, synData));
                        assessVo.setLevel(getLevel(synData));
                        comasses.addAll(communicateList);
                    }
                    children.add(assessVo);
                }
            });
            //计算冀北整体
            if (CollUtil.isNotEmpty(comasses)) {
                float synData = comAssesUtil.getAllComAss(comasses);
                overview.setScore(PubUtils.floatRound(2, synData));
                overview.setLevel(getLevel(synData));
            }
            overview.setChildren(children);
        }
        return overview;
    }

    @Override
    public List<AssessDetailVo> getData(AssessParam param) {
        List<AssessDetailVo> result = new ArrayList<>();
        //查询部门监测点关系
        DeptGetLineParam deptGetLineParam = new DeptGetLineParam();
        deptGetLineParam.setDeptId(param.getDeptIndex());
        deptGetLineParam.setLineRunFlag(0);
        List<DeptGetChildrenMoreDTO> list = commTerminalGeneralClient.deptGetLine(deptGetLineParam).getData();
        //获取监测点集合
        Map<String, List<String>> lineMap = this.getLineMap(list, param.getIsUpToGrid(), null);
        List<String> lineList = lineMap.values().stream()
                .flatMap(List::stream)
                .distinct()
                .collect(Collectors.toList());
        if (CollUtil.isNotEmpty(lineList)) {
            //获取监测点详细信息
            List<LineDetail> lineDetailList = lineFeignClient.getLineDetail(lineList).getData();
            Map<String, List<LineDetail>> lineDetailMap = lineDetailList.stream().collect(Collectors.groupingBy(LineDetail::getActualArea));
            //获取部门
            List<DeptDTO> deptList = deptFeignClient.getDepSonDetailByDeptId(param.getDeptIndex()).getData();
            //获取所有监测点r_stat_asses_d数据
            List<RStatAssesDPO> list1 = rStatAssesDMapper.getData(param.getStartTime(), param.getEndTime(), lineList);
            //获取所有监测点r_stat_comasses_d数据
            List<PQSComAssesPO> list2 = rStatComassesDMapper.getAvgCount(lineList, param.getStartTime(), param.getEndTime());
            //获取所有监测点r_stat_limit_rate_d数据
            List<RStatLimitRateDPO> list3 = rStatLimitRateDMapper.getAssessTargetRate(lineList, param.getStartTime(), param.getEndTime());
            //数据处理
            deptList.forEach(item -> {
                if (lineDetailMap.containsKey(item.getArea())) {
                    AssessVo assessVo = new AssessVo();
                    assessVo.setName(item.getName());
                    List<String> ll = lineDetailMap.get(item.getArea()).stream().map(LineDetail::getId).collect(Collectors.toList());
                    AssessDetailVo comAssess = getAssessData(item.getId(), item.getName(), ll, list1, list2, list3);
                    result.add(comAssess);
                } else {
                    AssessVo assessVo = new AssessVo();
                    assessVo.setName(item.getName());
                    List<String> ll = lineDetailList.stream().map(LineDetail::getId).collect(Collectors.toList());
                    AssessDetailVo comAssess = getAssessData(item.getId(), item.getName(), ll, list1, list2, list3);
                    result.add(comAssess);
                }
            });
        }
        return result;
    }

    @Override
    public List<AssessVo.AssessTrendVo> getAssessTrend(AssessParam param) {
        List<AssessVo.AssessTrendVo> result = new ArrayList<>();
        LinkedHashMap<String, List<PQSComAssesPO>> map = new LinkedHashMap<>();
        //查询部门监测点关系
        DeptGetLineParam deptGetLineParam = new DeptGetLineParam();
        deptGetLineParam.setDeptId(param.getDeptIndex());
        deptGetLineParam.setLineRunFlag(0);
        List<DeptGetChildrenMoreDTO> list = commTerminalGeneralClient.deptGetLine(deptGetLineParam).getData();
        //获取监测点集合
        Map<String, List<String>> lineMap = this.getLineMap(list, param.getIsUpToGrid(), null);
        List<String> lineList = lineMap.values().stream()
                .flatMap(List::stream)
                .distinct()
                .collect(Collectors.toList());
        if (CollUtil.isNotEmpty(lineList)) {
            //获取监测点详细信息
            List<LineDetail> lineDetailList = lineFeignClient.getLineDetail(lineList).getData();
            Map<String, List<LineDetail>> lineDetailMap = lineDetailList.stream().collect(Collectors.groupingBy(LineDetail::getActualArea));
            //获取部门
            List<DeptDTO> deptList = deptFeignClient.getDepSonDetailByDeptId(param.getDeptIndex()).getData();
            //按月、年来展示数据
            if (Objects.equals(param.getType(), 1)) {
                List<Integer> yearList = TimeUtil.getLastFiveYear(2);
                yearList.forEach(year -> {
                    String firstDayOfYear = TimeUtil.getYearFirst(year);
                    String lastDayOfYear = TimeUtil.getYearLast(year);
                    List<PQSComAssesPO> comAssesList = rStatComassesDMapper.getAvgCount(lineList, firstDayOfYear, lastDayOfYear);
                    map.put(year.toString(), comAssesList);
                });
            } else if (Objects.equals(param.getType(), 3)) {
                List<YearMonth> monthList = TimeUtil.getLastThreeMonth(5);
                monthList.forEach(month -> {
                    String firstDayOfMonth = month.atDay(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                    String lastDayOfMonth = month.atEndOfMonth().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                    List<PQSComAssesPO> comAssesList = rStatComassesDMapper.getAvgCount(lineList, firstDayOfMonth, lastDayOfMonth);
                    map.put(month.toString(), comAssesList);
                });
            }
            //数据处理
            if (param.getAreaType() == 0) {
                AssessVo.AssessTrendVo vo = new AssessVo.AssessTrendVo();
                vo.setDeptId(param.getDeptIndex());
                vo.setDeptName(deptFeignClient.getDeptById(param.getDeptIndex()).getData().getName());
                List<AssessVo> children = new ArrayList<>();
                map.forEach((k1, v1) -> {
                    AssessVo assessVo = new AssessVo();
                    assessVo.setDataTime(k1);
                    List<PqsComasses> communicateList = BeanUtil.copyToList(v1, PqsComasses.class);
                    float synData = comAssesUtil.getAllComAss(communicateList);
                    assessVo.setScore(CollUtil.isEmpty(communicateList) ? 3.14159f : PubUtils.floatRound(2, synData));
                    assessVo.setLevel(getLevel(assessVo.getScore()));
                    children.add(assessVo);
                });
                vo.setChildren(children);
                result.add(vo);
            } else {
                deptList.forEach(item -> {
                    if (lineDetailMap.containsKey(item.getArea())) {
                        AssessVo.AssessTrendVo vo = new AssessVo.AssessTrendVo();
                        vo.setDeptId(item.getId());
                        vo.setDeptName(item.getName());
                        List<AssessVo> children = new ArrayList<>();
                        List<String> ll = lineDetailMap.get(item.getArea()).stream().map(LineDetail::getId).collect(Collectors.toList());
                        map.forEach((k1, v1) -> {
                            AssessVo assessVo = new AssessVo();
                            assessVo.setDataTime(k1);
                            List<PQSComAssesPO> poList = v1.stream().filter(it -> ll.contains(it.getLineId())).collect(Collectors.toList());
                            List<PqsComasses> communicateList = BeanUtil.copyToList(poList, PqsComasses.class);
                            float synData = comAssesUtil.getAllComAss(communicateList);
                            assessVo.setScore(CollUtil.isEmpty(communicateList) ? 3.14159f : PubUtils.floatRound(2, synData));
                            assessVo.setLevel(getLevel(assessVo.getScore()));
                            children.add(assessVo);
                        });
                        vo.setChildren(children);
                        result.add(vo);
                    }
                });
            }
        }
        return result;
    }

    @Override
    public AssessDetailVo getLineAssess(String lineId, String startTime, String endTime) {
        AssessDetailVo vo = new AssessDetailVo();
        vo.setDeptId(lineId);
        List<String> lineList = Collections.singletonList(lineId);
        //获取监测点r_stat_asses_d数据 各指标评估
        List<RStatAssesDPO> list1 = rStatAssesDMapper.getData(startTime, endTime, lineList);
        //获取监测点r_stat_comasses_d数据 综合评估
        List<PQSComAssesPO> list2 = rStatComassesDMapper.getAvgCount(lineList, startTime, endTime);
        if (CollUtil.isNotEmpty(list1)) {
            this.chanelTargetAssess(list1, vo);
        }
        if (CollUtil.isNotEmpty(list2)) {
            List<PqsComasses> communicateList = BeanUtil.copyToList(list2, PqsComasses.class);
            float synData = comAssesUtil.getAllComAss(communicateList);
            vo.setAssessData(PubUtils.floatRound(2, synData));
            vo.setAssessLevel(getLevel(synData));
        }
        return vo;
    }

    @Override
    public EvaluationVo getEvaluationOverview(AssessParam param) {
        EvaluationVo result = new EvaluationVo();
        List<EvaluationVo.Children> childrenList = new ArrayList<>();
        DeptGetLineParam deptGetLineParam = new DeptGetLineParam();
        deptGetLineParam.setDeptId(param.getDeptIndex());
        deptGetLineParam.setLineRunFlag(0);
        List<DeptGetChildrenMoreDTO> list = commTerminalGeneralClient.deptGetLine(deptGetLineParam).getData();
        //获取监测点集合
        Map<String, List<String>> lineMap = this.getLineMap(list, param.getIsUpToGrid(), null);
        List<String> lineList = lineMap.values().stream()
                .flatMap(List::stream)
                .distinct()
                .collect(Collectors.toList());
        if (CollUtil.isNotEmpty(lineList)) {
            //获取监测点所有指标数据
            List<RStatLimitRateDPO> limitRateList = rStatLimitRateDMapper.getAssessTargetRate(lineList, param.getStartTime(), param.getEndTime());
            //获取部门
            List<DeptDTO> deptList = deptFeignClient.getDepSonDetailByDeptId(param.getDeptIndex()).getData();
            deptList.forEach(item -> {
                if (lineMap.containsKey(item.getId())) {
                    EvaluationVo.Children children = new EvaluationVo.Children();
                    children.setDeptId(item.getId());
                    children.setDeptName(item.getName());
                    List<String> ll = lineMap.get(item.getId());
                    if (CollUtil.isNotEmpty(limitRateList)) {
                        List<RStatLimitRateDPO> l1 = limitRateList.stream().filter(it -> ll.contains(it.getLineId())).collect(Collectors.toList());
                        if (CollUtil.isNotEmpty(l1)) {
                            this.getDataByTarget(param.getHarmonicType(), l1, children, ll.size());
                        }
                    }
                    childrenList.add(children);
                }
            });
            result.setChildrenList(childrenList);
            int overCount = 0;
            if (CollUtil.isNotEmpty(childrenList)) {
                for (EvaluationVo.Children children : childrenList) {
                    overCount = overCount + children.getSize();
                }
            }
            if (!lineList.isEmpty()) {
                result.setLineRatio(NumberUtil.round(overCount * 100.0/lineList.size(),2).doubleValue());
            }
        }
        return result;
    }

    @Override
    public List<EvaluationLevelVo> getEvaluationData(AssessParam param) {
        List<EvaluationLevelVo> result = new ArrayList<>();
        DeptGetLineParam deptGetLineParam = new DeptGetLineParam();
        deptGetLineParam.setDeptId(param.getDeptIndex());
        deptGetLineParam.setLineRunFlag(0);
        List<DeptGetChildrenMoreDTO> list = commTerminalGeneralClient.deptGetLine(deptGetLineParam).getData();

        DictData dictData = dicDataFeignClient.getDicDataById(param.getVoltageLevel()).getData();
        DictData standVoltageDic = dicDataFeignClient.getDicDataByNameAndTypeName(DicDataTypeEnum.DEV_VOLTAGE_STAND.getName(),dictData.getName()).getData();
        //获取监测点集合
        Map<String, List<String>> lineMap = this.getLineMap(list, param.getIsUpToGrid(),standVoltageDic.getId());
        List<String> lineList = lineMap.values().stream()
                .flatMap(List::stream)
                .distinct()
                .collect(Collectors.toList());
        //获取数据
        EvaluationLevelVo vo1 = new EvaluationLevelVo();
        vo1.setTargetName(DicDataEnum.FREQUENCY_DEV.getName() + "(Hz)");
        EvaluationLevelVo vo2 = new EvaluationLevelVo();
        vo2.setTargetName(DicDataEnum.VOLTAGE_DEV.getName() + "(%)");
        EvaluationLevelVo vo3 = new EvaluationLevelVo();
        vo3.setTargetName(DicDataEnum.THD_V.getName() + "(%)");
        EvaluationLevelVo vo4 = new EvaluationLevelVo();
        vo4.setTargetName(DicDataEnum.phase_Voltage.getName() + "(%)");
        EvaluationLevelVo vo5 = new EvaluationLevelVo();
        vo5.setTargetName(DicDataEnum.FLICKER.getName());
        if (CollUtil.isNotEmpty(lineList)) {
            List<RStatDataVD> list1 = getList1(lineList, param.getStartTime(), param.getEndTime());
            List<RStatDataVD> list2 = getList2(lineList, param.getStartTime(), param.getEndTime());
            List<RStatDataVD> list3 = getList3(lineList, param.getStartTime(), param.getEndTime());
            List<RStatDataPltDPO> list4 = getList4(lineList, param.getStartTime(), param.getEndTime());
            List<RStatDataVD> list5 = getList5(lineList, param.getStartTime(), param.getEndTime());
            if (CollUtil.isNotEmpty(list1)) {
                //List<Double> d = list1.stream().map(o -> o.getFreqDev().doubleValue()).collect(Collectors.toList());
                List<Double> d = list1.stream()
                        .map(o -> o.getFreqDev().doubleValue())
                        .filter(value -> value >= -7.5 && value <= 7.5)
                        .collect(Collectors.toList());
                double avg = d.stream().collect(Collectors.averagingDouble(x -> x));
                vo1.setAvg(PubUtils.doubleRound(2, avg));
                vo1.setSd(targetSd(d, avg));
            }
            if (CollUtil.isNotEmpty(list2)) {
                //List<Double> d = list2.stream().map(o -> o.getVuDev().doubleValue()).collect(Collectors.toList());
                List<Double> d = list2.stream()
                        .map(o -> o.getVuDev().doubleValue())
                        .filter(value -> value >= -90 && value <= 50)
                        .collect(Collectors.toList());
                double avg = d.stream().collect(Collectors.averagingDouble(x -> x));
                vo2.setAvg(PubUtils.doubleRound(2, avg));
                vo2.setSd(targetSd(d, avg));
            }
            if (CollUtil.isNotEmpty(list3)) {
                //List<Double> d = list3.stream().map(o -> o.getVThd().doubleValue()).collect(Collectors.toList());
                List<Double> d = list3.stream()
                        .map(o -> o.getVThd().doubleValue())
                        .filter(value -> value >= 0 && value <= 50)
                        .collect(Collectors.toList());
                double avg = d.stream().collect(Collectors.averagingDouble(x -> x));
                vo3.setAvg(PubUtils.doubleRound(2, avg));
                vo3.setSd(targetSd(d, avg));
            }
            if (CollUtil.isNotEmpty(list5)) {
                //List<Double> d = list5.stream().map(o -> o.getVUnbalance().doubleValue()).collect(Collectors.toList());
                List<Double> d = list5.stream()
                        .map(o -> o.getVUnbalance().doubleValue())
                        .filter(value -> value >= 0 && value <= 40)
                        .collect(Collectors.toList());
                double avg = d.stream().collect(Collectors.averagingDouble(x -> x));
                vo4.setAvg(PubUtils.doubleRound(2, avg));
                vo4.setSd(targetSd(d, avg));
            }
            if (CollUtil.isNotEmpty(list4)) {
                //List<Double> d = list4.stream().map(RStatDataPltDPO::getPlt).collect(Collectors.toList());
                List<Double> d = list4.stream()
                        .map(RStatDataPltDPO::getPlt)
                        .filter(value -> value >= 0 && value <= 20)
                        .collect(Collectors.toList());
                double avg = d.stream().collect(Collectors.averagingDouble(x -> x));
                vo5.setAvg(PubUtils.doubleRound(2, avg));
                vo5.setSd(targetSd(d, avg));
            }
        }
        Stream.of(vo1, vo2, vo3, vo4, vo5).forEach(result::add);
        return result;
    }

    @Override
    public List<EvaluationLevelVo.EvaluationRatio> evaluationRatio(AssessParam param) {
        List<EvaluationLevelVo.EvaluationRatio> result = new ArrayList<>();
        DeptGetLineParam deptGetLineParam = new DeptGetLineParam();
        deptGetLineParam.setDeptId(param.getDeptIndex());
        deptGetLineParam.setLineRunFlag(0);
        List<DeptGetChildrenMoreDTO> list = commTerminalGeneralClient.deptGetLine(deptGetLineParam).getData();
        //获取监测点集合
        Map<String, List<String>> lineMap = this.getLineMap(list, param.getIsUpToGrid(), null);
        List<String> lineList = lineMap.values().stream()
                .flatMap(List::stream)
                .distinct()
                .collect(Collectors.toList());
        //按月获取时间集合
        LocalDate currentDate = LocalDate.now();
        // 获取当前年份
        int currentYear = currentDate.getYear();
        LocalDate beginDay = LocalDate.of(currentYear, 1, 1);
        List<YearMonth> monthList = TimeUtil.getMonthsBetween(beginDay, currentDate);
        for (YearMonth month : monthList) {
            String firstDayOfMonth = month.atDay(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            String lastDayOfMonth = month.atEndOfMonth().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            EvaluationLevelVo.EvaluationRatio vo = new EvaluationLevelVo.EvaluationRatio();
            vo.setTime(month.toString());
            vo.setTargetList(Arrays.asList(DicDataEnum.FREQUENCY_DEV.getName(),
                    DicDataEnum.VOLTAGE_DEV.getName(),
                    DicDataEnum.THD_V.getName(),
                    DicDataEnum.phase_Voltage.getName(),
                    DicDataEnum.FLICKER.getName(),

                    DicDataEnum.HARMONIC_VOLTAGE.getName(),
                    DicDataEnum.HARMONIC_CURRENT.getName(),
                    DicDataEnum.INTERHARMONIC_VOLTAGE.getName(),
                    DicDataEnum.NEG_CURRENT.getName()

            ));
            //获取监测点越限集合
            List<RStatLimitRateDPO> overLimitList = rStatLimitRateDMapper.getAssessTargetRate(lineList, firstDayOfMonth, lastDayOfMonth);
            if (CollUtil.isNotEmpty(overLimitList)) {
                long freqDev = overLimitList.stream().filter(obj -> obj.getFreqDevOvertime() > 0).count();
                long vDev = overLimitList.stream().filter(obj -> obj.getVoltageDevOvertime() > 0).count();
                long vThd = overLimitList.stream().filter(obj -> obj.getUaberranceOvertime() > 0).count();
                long ubalance = overLimitList.stream().filter(obj -> obj.getUbalanceOvertime() > 0).count();
                long plt = overLimitList.stream().filter(obj -> obj.getFlickerOvertime() > 0).count();


                long uHarm = overLimitList.stream().filter(x -> getLimitRateStats(x, 2, 26, "uharm", "Overtime")).count();
                long iHarm = overLimitList.stream().filter(x -> getLimitRateStats(x, 2, 26, "iharm", "Overtime")).count();
                long inuHarm = overLimitList.stream().filter(x -> getLimitRateStats(x, 1, 16, "inuharm", "Overtime")).count();
                long iNeg = overLimitList.stream().filter(obj -> obj.getINegOvertime() > 0).count();
                vo.setRatioList(Arrays.asList(PubUtils.doubleRound(2, freqDev * 100.0 / overLimitList.size()),
                        PubUtils.doubleRound(2, vDev * 100.0 / overLimitList.size()),
                        PubUtils.doubleRound(2, vThd * 100.0 / overLimitList.size()),
                        PubUtils.doubleRound(2, ubalance * 100.0 / overLimitList.size()),
                        PubUtils.doubleRound(2, plt * 100.0 / overLimitList.size()),

                        PubUtils.doubleRound(2, uHarm * 100.0 / overLimitList.size()),
                        PubUtils.doubleRound(2, iHarm * 100.0 / overLimitList.size()),
                        PubUtils.doubleRound(2, inuHarm * 100.0 / overLimitList.size()),
                        PubUtils.doubleRound(2, iNeg * 100.0 / overLimitList.size())));
            }
            result.add(vo);
        }
        return result;
    }

    /**
     * @param limitRateDPO 对象
     * @param startNum     循环开始
     * @param endNum       循环结束
     * @param start        属性名开始
     * @param end          属性名结束
     * @return
     */
    public Boolean getLimitRateStats(RStatLimitRateDPO limitRateDPO, Integer startNum, Integer endNum, String start, String end) {
        try {
            for (int i = startNum; i < endNum; i++) {
                String fieldName = start + i + end;
                Field field = limitRateDPO.getClass().getDeclaredField(fieldName);
                //设置对象的访问权限，保证对private的属性的访问
                field.setAccessible(true);
                int v = Integer.parseInt(field.get(limitRateDPO).toString());
                if (v > 0) {
                    return true;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return false;
    }


    @Override
    public List<EvaluationLevelVo.EvaluationDetail> getEvaluationDetail(AssessParam param) {
        List<EvaluationLevelVo.EvaluationDetail> result = new ArrayList<>();
        DeptGetLineParam deptGetLineParam = new DeptGetLineParam();
        deptGetLineParam.setDeptId(param.getDeptIndex());
        List<DeptGetChildrenMoreDTO> list = commTerminalGeneralClient.deptGetAllLine(deptGetLineParam).getData();
        //获取监测点集合
        Map<String, List<String>> lineMap = this.getLineMap(list, param.getIsUpToGrid(), null);
        List<String> lineList = lineMap.values().stream()
                .flatMap(List::stream)
                .distinct()
                .collect(Collectors.toList());
        Map<String, List<String>> lineMap2 = this.getLineMap(list, param.getIsUpToGrid(), null,0);
        List<String> lineList2 = lineMap2.values().stream()
                .flatMap(List::stream)
                .distinct()
                .collect(Collectors.toList());

        List<RStatLimitTargetVO> overLimitList = new ArrayList<>();
        if (CollUtil.isNotEmpty(lineList)) {
            //获取监测点越限集合
            overLimitList.addAll(rStatLimitTargetDMapper.getSumTargetDetails2(lineList,
                    param.getStartTime(),
                    param.getEndTime()));
        }
        //获取部门
        List<DeptDTO> deptList = deptFeignClient.getDepSonDetailByDeptId(param.getDeptIndex()).getData();
        deptList.forEach(item -> {
            EvaluationLevelVo.EvaluationDetail detail = new EvaluationLevelVo.EvaluationDetail();
            detail.setDeptId(item.getId());
            detail.setDeptName(item.getName());
            EvaluationLevelVo.TargetDetail detail1 = new EvaluationLevelVo.TargetDetail();
            detail1.setTargetName(DicDataEnum.FREQUENCY_DEV.getName());
            detail1.setOverDay(0);
            detail1.setOverNum(0);
            EvaluationLevelVo.TargetDetail detail2 = new EvaluationLevelVo.TargetDetail();
            detail2.setTargetName(DicDataEnum.VOLTAGE_DEV.getName());
            detail2.setOverDay(0);
            detail2.setOverNum(0);
            EvaluationLevelVo.TargetDetail detail3 = new EvaluationLevelVo.TargetDetail();
            detail3.setTargetName(DicDataEnum.THD_V.getName());
            detail3.setOverDay(0);
            detail3.setOverNum(0);
            EvaluationLevelVo.TargetDetail detail4 = new EvaluationLevelVo.TargetDetail();
            detail4.setTargetName(DicDataEnum.FLICKER.getName());
            detail4.setOverDay(0);
            detail4.setOverNum(0);
            EvaluationLevelVo.TargetDetail detail5 = new EvaluationLevelVo.TargetDetail();
            detail5.setTargetName(DicDataEnum.phase_Voltage.getName());
            detail5.setOverDay(0);
            detail5.setOverNum(0);
            EvaluationLevelVo.TargetDetail detail6 = new EvaluationLevelVo.TargetDetail();
            detail6.setTargetName(DicDataEnum.NEG_CURRENT.getName());
            detail6.setOverDay(0);
            detail6.setOverNum(0);
            EvaluationLevelVo.TargetDetail detail7 = new EvaluationLevelVo.TargetDetail();
            detail7.setTargetName(DicDataEnum.HARMONIC_CURRENT.getName());
            detail7.setOverDay(0);
            detail7.setOverNum(0);
            EvaluationLevelVo.TargetDetail detail8 = new EvaluationLevelVo.TargetDetail();
            detail8.setTargetName(DicDataEnum.HARMONIC_VOLTAGE.getName());
            detail8.setOverDay(0);
            detail8.setOverNum(0);
            EvaluationLevelVo.TargetDetail detail9 = new EvaluationLevelVo.TargetDetail();
            detail9.setTargetName(DicDataEnum.INTERHARMONIC_VOLTAGE.getName());
            detail9.setOverDay(0);
            detail9.setOverNum(0);
            if (lineMap.containsKey(item.getId())) {
                if (CollUtil.isNotEmpty(lineMap.get(item.getId()))) {
                    List<String> ll = lineMap.get(item.getId());
                    List<String> lll = lineMap2.get(item.getId());
                    detail.setOnlineNum(lll.size());
                    //筛选当前部门下监测点的超标数据
                    List<RStatLimitTargetVO> list2 = overLimitList.stream().filter(it -> ll.contains(it.getLineId())).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(list2)) {
                        //筛选出9项指标(电压偏差、频率偏差、电压总谐波畸变率、电压闪变、三相电压不平衡度、负序电流、谐波电流、间谐波电压、谐波电压)超标监测点
                        long allNum = list2.stream().filter(o -> o.getAllOvertime() > 0 || o.getFlickerAllTime() > 0 ).count();
                        detail.setOverNum((int) allNum);
                        detail.setOverRatio(detail.getOnlineNum() == 0 ? 0 : PubUtils.doubleRound(2, detail.getOverNum() * 100.0 / detail.getOnlineNum()));
                        //筛选出电压偏差超标监测点
                        long num1 = list2.stream().filter(o -> o.getFreqDevOvertime() > 0).count();
                        Integer day1 = list2.stream().max(Comparator.comparingInt(RStatLimitTargetVO::getFreqDevOvertime)).get().getFreqDevOvertime();
                        detail1.setOverNum((int) num1);
                        detail1.setOverDay(day1);

                        //筛选出频率偏差超标监测点
                        long num2 = list2.stream().filter(o -> o.getVoltageDevOvertime() > 0).count();
                        Integer day2 = list2.stream().max(Comparator.comparingInt(RStatLimitTargetVO::getVoltageDevOvertime)).get().getVoltageDevOvertime();
                        detail2.setOverNum((int) num2);
                        detail2.setOverDay(day2);

                        //筛选出电压总谐波畸变率超标监测点
                        long num3 = list2.stream().filter(o -> o.getUaberranceOvertime() > 0).count();
                        Integer day3 = list2.stream().max(Comparator.comparingInt(RStatLimitTargetVO::getUaberranceOvertime)).get().getUaberranceOvertime();
                        detail3.setOverNum((int) num3);
                        detail3.setOverDay(day3);

                        //筛选出电压闪变超标监测点
                        long num4 = list2.stream().filter(o -> o.getFlickerOvertime() > 0).count();
                        Integer day4 = list2.stream().max(Comparator.comparingInt(RStatLimitTargetVO::getFlickerOvertime)).get().getFlickerOvertime();
                        detail4.setOverNum((int) num4);
                        detail4.setOverDay(day4);

                        //筛选出三相电压不平衡度超标监测点
                        long num5 = list2.stream().filter(o -> o.getUbalanceOvertime() > 0).count();
                        Integer day5 = list2.stream().max(Comparator.comparingInt(RStatLimitTargetVO::getUbalanceOvertime)).get().getUbalanceOvertime();
                        detail5.setOverNum((int) num5);
                        detail5.setOverDay(day5);

                        //筛选出负序电流超标监测点
                        long num6 = list2.stream().filter(o -> o.getINegOvertime() > 0).count();
                        Integer day6 = list2.stream().max(Comparator.comparingInt(RStatLimitTargetVO::getINegOvertime)).get().getINegOvertime();
                        detail6.setOverNum((int) num6);
                        detail6.setOverDay(day6);

                        long num7 = list2.stream().filter(o -> o.getIharmOvertime() > 0).count();
                        Integer day7 = list2.stream().max(Comparator.comparingInt(RStatLimitTargetVO::getIharmOvertime)).get().getIharmOvertime();
                        detail7.setOverNum((int) num7);
                        detail7.setOverDay(day7);

                        long num8 = list2.stream().filter(o -> o.getUharmOvertime() > 0).count();
                        Integer day8 = list2.stream().max(Comparator.comparingInt(RStatLimitTargetVO::getUharmOvertime)).get().getUharmOvertime();
                        detail8.setOverNum((int) num8);
                        detail8.setOverDay(day8);

                        long num9 = list2.stream().filter(o -> o.getInuharmOvertime() > 0).count();
                        Integer day9 = list2.stream().max(Comparator.comparingInt(RStatLimitTargetVO::getInuharmOvertime)).get().getInuharmOvertime();
                        detail9.setOverNum((int) num9);
                        detail9.setOverDay(day9);
                    } else {
                        detail.setOverNum(0);
                        detail.setOverRatio(0.0);
                    }
                }
            }
            List<EvaluationLevelVo.TargetDetail> details = Arrays.asList(detail1, detail2, detail3, detail4, detail5, detail6, detail7, detail8, detail9);
            detail.setList(details);
            result.add(detail);
        });
        return result;
    }

    @Override
    public List<EvaluationLevelVo.QualifiedDetail> getQualifiedDetail(AssessParam param) {
        List<EvaluationLevelVo.QualifiedDetail> result = new ArrayList<>();
        DeptGetLineParam deptGetLineParam = new DeptGetLineParam();
        deptGetLineParam.setDeptId(param.getDeptIndex());
        deptGetLineParam.setLineRunFlag(0);
        List<DeptGetChildrenMoreDTO> list = commTerminalGeneralClient.deptGetLine(deptGetLineParam).getData();
        //获取监测点集合
        Map<String, List<String>> lineMap = this.getLineMap(list, param.getIsUpToGrid(), null);
        List<String> lineList = lineMap.values().stream()
                .flatMap(List::stream)
                .distinct()
                .collect(Collectors.toList());
        //获取基础台账信息
        List<AreaLineInfoVO> baseLineInfos = lineFeignClient.getBaseLineAreaInfo(lineList).getData();
        //获取越限详情
        List<RStatLimitRateDPO> overLimitList = rStatLimitRateDMapper.getAssessTargetRate(lineList, param.getStartTime(), param.getEndTime());
        Map<String, RStatLimitRateDPO> map = overLimitList.stream().collect(Collectors.toMap(RStatLimitRateDPO::getLineId, Function.identity()));
        baseLineInfos.forEach(item -> {
            EvaluationLevelVo.QualifiedDetail qualifiedDetail = new EvaluationLevelVo.QualifiedDetail();
            qualifiedDetail.setAreaName(item.getGdName());
            qualifiedDetail.setLineName(item.getLineName());
            qualifiedDetail.setSubstationName(item.getSubName());
            if (map.containsKey(item.getLineId())) {
                RStatLimitRateDPO item2 = map.get(item.getLineId());
                if (!Objects.isNull(item2) && item2.getAllTime() > 0) {
                    addQualifiedDetail(qualifiedDetail, item2);
                }
            }
            result.add(qualifiedDetail);
        });
        if (CollUtil.isNotEmpty(result)) {
            return result.stream().sorted(Comparator.comparing(EvaluationLevelVo.QualifiedDetail::getAreaName)
                            .thenComparing(EvaluationLevelVo.QualifiedDetail::getSubstationName))
                    .collect(Collectors.toList());
        }
        return result;
    }


    @Override
    public EvaluationLevelVo.QualifiedDetail getLineQualifiedDetail(String lineId, String startTime, String endTime) {
        EvaluationLevelVo.QualifiedDetail detail = new EvaluationLevelVo.QualifiedDetail();
        List<String> lineList = Collections.singletonList(lineId);
        List<RStatLimitRateDPO> overLimitList = rStatLimitRateDMapper.getAssessTargetRate(lineList, startTime, endTime);
        if (CollUtil.isNotEmpty(overLimitList)) {
            RStatLimitRateDPO dpo = overLimitList.get(0);
            addQualifiedDetail(detail, dpo);
        }
        return detail;
    }

    private void addQualifiedDetail(EvaluationLevelVo.QualifiedDetail qualifiedDetail, RStatLimitRateDPO item2) {
        if (item2.getAllTime() > 0) {
            qualifiedDetail.setFreqDev(PubUtils.doubleRound(2, 100.0 - (item2.getFreqDevOvertime() * 100.0 / item2.getAllTime())));
            qualifiedDetail.setVDev(PubUtils.doubleRound(2, 100.0 - (item2.getVoltageDevOvertime() * 100.0 / item2.getAllTime())));
            qualifiedDetail.setVThd(PubUtils.doubleRound(2, 100.0 - (item2.getUaberranceOvertime() * 100.0 / item2.getAllTime())));
            qualifiedDetail.setUbalance(PubUtils.doubleRound(2, 100.0 - (item2.getUbalanceOvertime() * 100.0 / item2.getAllTime())));
            //谐波电压
            List<Integer> list1 = getList(2, 25, "getUharm", item2);
            Integer maxValue1 = list1.stream().max(Integer::compareTo).orElse(null);
            qualifiedDetail.setUHarm(Objects.isNull(maxValue1) ? null : PubUtils.doubleRound(2, 100.0 - (maxValue1 * 100.0 / item2.getAllTime())));
            //谐波电流
            List<Integer> list2 = getList(2, 25, "getIharm", item2);
            Integer maxValue2 = list2.stream().max(Integer::compareTo).orElse(null);
            qualifiedDetail.setIHarm(Objects.isNull(maxValue2) ? null : PubUtils.doubleRound(2, 100.0 - (maxValue2 * 100.0 / item2.getAllTime())));
            //间谐波电压
            List<Integer> list3 = getList(1, 16, "getInuharm", item2);
            Integer maxValue3 = list3.stream().max(Integer::compareTo).orElse(null);
            qualifiedDetail.setInuHarm(Objects.isNull(maxValue3) ? null : PubUtils.doubleRound(2, 100.0 - (maxValue3 * 100.0 / item2.getAllTime())));
            //负序电流
            qualifiedDetail.setINeg(PubUtils.doubleRound(2, 100.0 - (item2.getINegOvertime() * 100.0 / item2.getAllTime())));
        }
        if (item2.getFlickerAllTime() > 0) {
            qualifiedDetail.setPlt(PubUtils.doubleRound(2, 100.0 - (item2.getFlickerOvertime() * 100.0 / item2.getFlickerAllTime())));
        }
    }

    /**
     * 使用反射添加list的值
     */
    public List<Integer> getList(Integer start, Integer end, String targetName, RStatLimitRateDPO item2) {
        List<Integer> result = new ArrayList<>();
        for (int i = start; i <= end; i++) {
            try {
                // 构造方法名
                String methodName = targetName + i + "Overtime";
                Method method = item2.getClass().getMethod(methodName);
                // 调用方法并添加到列表中
                Integer value = (Integer) method.invoke(item2);
                if (value != null) {
                    result.add(value);
                }
            } catch (Exception e) {
                e.getMessage();
            }
        }
        return result;
    }

    /**
     * 获取监测点频率偏差 T相最大值
     */
    public List<RStatDataVD> getList1(List<String> lineList, String startTime, String endTime) {
        return statDataVDMapper.getFreqDev(lineList, startTime, endTime);
    }

    /**
     * 获取监测点电压偏差 使用电压上偏差A、B、C三相最大值的平均值
     */
    public List<RStatDataVD> getList2(List<String> lineList, String startTime, String endTime) {
        return statDataVDMapper.getVuDev(lineList, startTime, endTime);
    }

    /**
     * 获取监测点电压总谐波畸变率 A、B、C三相Cp95的平均值
     */
    public List<RStatDataVD> getList3(List<String> lineList, String startTime, String endTime) {
        return statDataVDMapper.getVthd(lineList, startTime, endTime);
    }

    /**
     * 获取监测点闪变 A、B、C三相最大值的平均值
     */
    public List<RStatDataPltDPO> getList4(List<String> lineList, String startTime, String endTime) {
        return statDataPltDMapper.getPlt(lineList, startTime, endTime);
    }

    /**
     * 获取监测点三相电压不平衡度 T相 CP95
     */
    public List<RStatDataVD> getList5(List<String> lineList, String startTime, String endTime) {
        return statDataVDMapper.getUnbalance(lineList, startTime, endTime);
    }

    /**
     * 谐波电压含有率 A、B、C三相最大值的平均值
     */
    private List<RStatDataVD> getList6(List<String> lineList, String startTime, String endTime) {
        return statDataVDMapper.getV(lineList, startTime, endTime);
    }

    /**
     * 谐波电流 A、B、C三相最大值的平均值
     */
    private List<RStatDataIDPO> getList7(List<String> lineList, String startTime, String endTime) {
        return statDataIDMapper.getI(lineList, startTime, endTime);
    }

    /**
     * 间谐波电压含有率 A、B、C三相最大值的平均值
     */
    private List<RStatDataInharmVDPO> getList8(List<String> lineList, String startTime, String endTime) {
        return rStatDataInharmVDMapper.getV(lineList, startTime, endTime);
    }

    /**
     * 获取监测点负序电流 A、B、C三相最大值的平均值
     */
    public List<RStatDataIDPO> getList9(List<String> lineList, String startTime, String endTime) {
        return statDataIDMapper.getINeg(lineList, startTime, endTime);
    }

    /**
     * 计算标准差
     */
    public Double targetSd(List<Double> list, Double avg) {
        double sum = list.stream().mapToDouble(number -> Math.pow(number - avg, 2)).sum();
        double variance = sum / list.size();
        return PubUtils.doubleRound(2, Math.sqrt(variance));
    }


    /**
     * 根据指标类型计算数据
     */
    public void getDataByTarget(Integer type, List<RStatLimitRateDPO> limitRateList, EvaluationVo.Children children,int monitorTotal) {
        switch (type) {
            //全指标
            case 0:
                List<RStatLimitRateDPO> filteredList0 = limitRateList.stream()
                        .filter(data -> data.getFreqDevOvertime() + data.getVoltageDevOvertime() + data.getFlickerOvertime() + data.getUaberranceOvertime() + data.getUbalanceOvertime() > 0)
                        .collect(Collectors.toList());
                children.setSize(filteredList0.size());
                children.setRatio(PubUtils.doubleRound(2, filteredList0.size() * 100.0 / monitorTotal));
                break;
            //电压偏差
            case 1:
                List<RStatLimitRateDPO> filteredList1 = limitRateList.stream()
                        .filter(data -> data.getVoltageDevOvertime() > 0)
                        .collect(Collectors.toList());
                children.setSize(filteredList1.size());
                children.setRatio(PubUtils.doubleRound(2, filteredList1.size() * 100.0 / monitorTotal));
                break;
            //频率偏差
            case 2:
                List<RStatLimitRateDPO> filteredList2 = limitRateList.stream()
                        .filter(data -> data.getFreqDevOvertime() > 0)
                        .collect(Collectors.toList());
                children.setSize(filteredList2.size());
                children.setRatio(PubUtils.doubleRound(2, filteredList2.size() * 100.0 / monitorTotal));
                break;
            //电压总谐波畸变率
            case 3:
                List<RStatLimitRateDPO> filteredList3 = limitRateList.stream()
                        .filter(data -> data.getUaberranceOvertime() > 0)
                        .collect(Collectors.toList());
                children.setSize(filteredList3.size());
                children.setRatio(PubUtils.doubleRound(2, filteredList3.size() * 100.0 / monitorTotal));
                break;
            //电压闪变
            case 4:
                List<RStatLimitRateDPO> filteredList4 = limitRateList.stream()
                        .filter(data -> data.getFlickerOvertime() > 0)
                        .collect(Collectors.toList());
                children.setSize(filteredList4.size());
                children.setRatio(PubUtils.doubleRound(2, filteredList4.size() * 100.0 / monitorTotal));
                break;
            //三相电压不平衡度
            case 5:
                List<RStatLimitRateDPO> filteredList5 = limitRateList.stream()
                        .filter(data -> data.getUbalanceOvertime() > 0)
                        .collect(Collectors.toList());
                children.setSize(filteredList5.size());
                children.setRatio(PubUtils.doubleRound(2, filteredList5.size() * 100.0 / monitorTotal));
                break;
            // 谐波电压
            // 谐波电压含有率 + 谐波电压有效值
            case 6:
                List<RStatLimitRateDPO> filteredList6 = limitRateList.stream()
                        .filter(x -> getLimitRateStats(x, 2, 26, "uharm", "Overtime") || x.getUaberranceOvertime() > 0)
                        .collect(Collectors.toList());
                children.setSize(filteredList6.size());
                children.setRatio(PubUtils.doubleRound(2, filteredList6.size() * 100.0 / monitorTotal));
                break;
            //谐波电流
            case 7:
                List<RStatLimitRateDPO> filteredList7 = limitRateList.stream()
                        .filter(x -> getLimitRateStats(x, 2, 26, "iharm", "Overtime"))
                        .collect(Collectors.toList());
                children.setSize(filteredList7.size());
                children.setRatio(PubUtils.doubleRound(2, filteredList7.size() * 100.0 / monitorTotal));
                break;
            //间谐波电压
            case 8:
                List<RStatLimitRateDPO> filteredList8 = limitRateList.stream()
                        .filter(x -> getLimitRateStats(x, 1, 16, "inuharm", "Overtime"))
                        .collect(Collectors.toList());
                children.setSize(filteredList8.size());
                children.setRatio(PubUtils.doubleRound(2, filteredList8.size() * 100.0 / monitorTotal));
                break;
            //负序电流
            case 9:
                List<RStatLimitRateDPO> filteredList9 = limitRateList.stream()
                        .filter(data -> data.getINegOvertime() > 0)
                        .collect(Collectors.toList());
                children.setSize(filteredList9.size());
                children.setRatio(PubUtils.doubleRound(2, filteredList9.size() * 100.0 / monitorTotal));
                break;
            default:
                break;
        }
    }

    public AssessDetailVo   getAssessData(String deptId, String deptName, List<String> lineList, List<RStatAssesDPO> list1, List<PQSComAssesPO> list2, List<RStatLimitRateDPO> list3) {
        AssessDetailVo comAssess = new AssessDetailVo();
        comAssess.setDeptId(deptId);
        comAssess.setDeptName(deptName);
        //处理区域各个指标的稳态评估
        if (CollUtil.isNotEmpty(list1)) {
            List<RStatAssesDPO> list11 = list1.stream().filter(it -> lineList.contains(it.getLineId())).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(list11)) {
                this.chanelTargetAssess(list11, comAssess);
            }
        }
        //处理区域综合稳态评估
        if (CollUtil.isNotEmpty(list2)) {
            List<PQSComAssesPO> list22 = list2.stream().filter(it -> lineList.contains(it.getLineId())).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(list22)) {
                List<PqsComasses> communicateList = BeanUtil.copyToList(list22, PqsComasses.class);
                float synData = comAssesUtil.getAllComAss(communicateList);
                comAssess.setAssessData(PubUtils.floatRound(2, synData));
                comAssess.setAssessLevel(getLevel(synData));
            }
        }
        //处理区域总指标合格率、各个指标合格率
        if (CollUtil.isNotEmpty(list3)) {
            List<RStatLimitRateDPO> list33 = list3.stream().filter(it -> lineList.contains(it.getLineId())).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(list33)) {
                //总指标次数
                int allTime = list33.stream()
                        .mapToInt(RStatLimitRateDPO::getAllTime)
                        .sum();
                //总闪变次数
                int allFlickerTime = list33.stream()
                        .mapToInt(RStatLimitRateDPO::getFlickerAllTime)
                        .sum();
                //电压偏差
                int devTime = list33.stream()
                        .mapToInt(RStatLimitRateDPO::getVoltageDevOvertime)
                        .sum();
                //频率偏差
                int freqTime = list33.stream()
                        .mapToInt(RStatLimitRateDPO::getFreqDevOvertime)
                        .sum();
                //谐波含量
                int thdTime = list33.stream()
                        .mapToInt(RStatLimitRateDPO::getUaberranceOvertime)
                        .sum();
                //电压闪变
                int pltTime = list33.stream()
                        .mapToInt(RStatLimitRateDPO::getFlickerOvertime)
                        .sum();
                //三相电压不平衡度
                int ubalanceTime = list33.stream()
                        .mapToInt(RStatLimitRateDPO::getUbalanceOvertime)
                        .sum();
                //计算总稳态合格率
                double all1 = 100 - (devTime + freqTime + thdTime + ubalanceTime) * 100.0 / (allTime * 4);
                double all2 = 100 - pltTime * 100.0 / allFlickerTime;

                double data1,data2,data3,data4,data5,data6;
                if (Double.isNaN(all1+all2)) {
                    data1 = 3.14159;
                } else if (Double.isInfinite(all1+all2)) {
                    data1 = 100.0;
                } else {
                    data1 = PubUtils.doubleRound(2, (all1 + all2) / 2.0);
                }

                if (Double.isNaN(100 - devTime * 100.0 / allTime)) {
                    data2 = 3.14159;
                } else if (Double.isInfinite(100 - devTime * 100.0 / allTime)) {
                    data2 = 100.0;
                } else {
                    data2 = PubUtils.doubleRound(2, 100 - devTime * 100.0 / allTime);
                }

                if (Double.isNaN(100 - freqTime * 100.0 / allTime)) {
                    data3 = 3.14159;
                } else if (Double.isInfinite(100 - freqTime * 100.0 / allTime)) {
                    data3 = 100.0;
                } else {
                    data3 = PubUtils.doubleRound(2, 100 - freqTime * 100.0 / allTime);
                }

                if (Double.isNaN(100 - thdTime * 100.0 / allTime)) {
                    data4 = 3.14159;
                } else if (Double.isInfinite(100 - thdTime * 100.0 / allTime)) {
                    data4 = 100.0;
                } else {
                    data4 = PubUtils.doubleRound(2, 100 - thdTime * 100.0 / allTime);
                }

                if (Double.isNaN(100 - pltTime * 100.0 / allFlickerTime)) {
                    data5 = 3.14159;
                } else if (Double.isInfinite(100 - pltTime * 100.0 / allFlickerTime)) {
                    data5 = 100.0;
                } else {
                    data5 = PubUtils.doubleRound(2, 100 - pltTime * 100.0 / allFlickerTime);
                }

                if (Double.isNaN(100 - pltTime * 100.0 / allTime)) {
                    data6 = 3.14159;
                } else if (Double.isInfinite(100 - pltTime * 100.0 / allTime)) {
                    data6 = 100.0;
                } else {
                    data6 = PubUtils.doubleRound(2, 100 - ubalanceTime * 100.0 / allTime);
                }
                comAssess.setQualifyData(allTime <= 0 ? 3.14159 : data1);
                comAssess.setVDevQualifyData(allTime <= 0 ? 3.14159 : data2);
                comAssess.setFreqQualifyData(allTime <= 0 ? 3.14159 : data3);
                comAssess.setHarmQualifyData(allTime <= 0 ? 3.14159 : data4);
                comAssess.setFlickerQualifyData(allTime <= 0 ? 3.14159 : data5);
                comAssess.setUnbalanceQualifyData(allTime <= 0 ? 3.14159 : data6);
            }
        }
        return comAssess;
    }

    public void chanelTargetAssess(List<RStatAssesDPO> list, AssessDetailVo comAssess) {
        double vuDev = list.stream()
                .mapToDouble(RStatAssesDPO::getVuDev)
                .average()
                .orElse(0.0);
        comAssess.setVDevAssessData(PubUtils.doubleRound(2, vuDev));
        comAssess.setVDevAssessLevel(getLevel(vuDev, 0f, 2.5f, 5f, 7.5f, 10f, 12.5f, 15f, 17.5f));
        double freqDev = list.stream()
                .mapToDouble(RStatAssesDPO::getFreqDev)
                .average()
                .orElse(0.0);
        comAssess.setFreqAssessData(PubUtils.doubleRound(2, freqDev));
        comAssess.setFreqAssessLevel(getLevel(freqDev, 0f, 0.05f, 0.1f, 0.15f, 0.2f, 0.25f, 0.30f, 0.35f));
        double dataPlt = list.stream()
                .mapToDouble(RStatAssesDPO::getDataPlt)
                .average()
                .orElse(0.0);
        comAssess.setFlickerAssessData(PubUtils.doubleRound(2, dataPlt));
        comAssess.setFlickerAssessLevel(getLevel(dataPlt, 0f, 0.05f, 0.1f, 0.15f, 0.2f, 0.25f, 0.30f, 0.35f));
        double vUnbalanceCp95 = list.stream()
                .mapToDouble(RStatAssesDPO::getVUnbalanceCp95)
                .average()
                .orElse(0.0);
        comAssess.setUnbalanceAssessData(PubUtils.doubleRound(2, vUnbalanceCp95));
        comAssess.setUnbalanceAssessLevel(getLevel(vUnbalanceCp95, 0f, 0.5f, 1f, 1.5f, 2f, 2.5f, 3f, 3.5f));
        double vThdCp95 = list.stream()
                .mapToDouble(RStatAssesDPO::getVThdCp95)
                .average()
                .orElse(0.0);
        comAssess.setHarmAssessData(PubUtils.doubleRound(2, vThdCp95));
        comAssess.setHarmAssessLevel(getLevel(vThdCp95, 0f, 0.5f, 1f, 1.5f, 2f, 2.5f, 3f, 3.5f));
    }


    /**
     * 获取综合评估等级
     */
    private String getLevel(float synDatas) {
        if (synDatas == 3.14159f) {
            return "暂无数据";
        }
        if (0 <= synDatas && synDatas < 2) {
            return "极差";
        } else if (2 <= synDatas && synDatas < 3) {
            return "较差";
        } else if (3 <= synDatas && synDatas < 4) {
            return "合格";
        } else if (4 <= synDatas && synDatas < 4.5) {
            return "良好";
        } else {
            return "优质";
        }
    }


    /**
     * 获取各个指标对应的等级
     */
    private String getLevel(double value, float f1, float f2, float f3, float f4, float f5, float f6, float f7, float f8) {
        String level;
        if (f1 <= value && value <= f2) {
            level = "特质";
        } else if (f2 < value && value <= f3) {
            level = "优质";
        } else if (f3 < value && value <= f4) {
            level = "优良";
        } else if (f4 < value && value <= f5) {
            level = "良好";
        } else if (f5 < value && value <= f6) {
//            level="轻度污染";
            level = "合格";
        } else if (f6 < value && value <= f7) {
//            level="中度污染";
            level = "较差";
        } else if (f7 < value && value <= f8) {
//            level="重度污染";
            level = "差";
        } else {
//            level="极度污染";
            level = "极差";
        }
        return level;
    }

    /**
     * 过滤监测点
     *
     * @param list
     * @param type
     * @return
     */
    public Map<String, List<String>> getLineMap(List<DeptGetChildrenMoreDTO> list, Integer type, String voltage) {
        Map<String, List<String>> map = new HashMap<>();
        list.forEach(it -> {
            // 默认不过滤
            Predicate<LineDevGetDTO> uploadFilter = item -> true;
            if (Objects.equals(type, 1)) {
                uploadFilter = item -> Objects.equals(item.getIsUpToGrid(), 1);
            }

            Predicate<LineDevGetDTO> voltageFilter = item -> true;
            if (!Objects.isNull(voltage) && !Objects.equals(voltage, "")) {
                voltageFilter = item -> Objects.equals(item.getVoltageLevel(), voltage);
            }
            // 组合两个过滤条件
            Predicate<LineDevGetDTO> combinedFilter = uploadFilter.and(voltageFilter);
            map.put(it.getUnitId(), it.getLineBaseList().stream()
                    .filter(combinedFilter)
                    .map(LineDevGetDTO::getPointId)
                    .distinct()
                    .collect(Collectors.toList()));
        });
        return map;
    }

    public Map<String, List<String>> getLineMap(List<DeptGetChildrenMoreDTO> list, Integer type, String voltage, Integer runFlag) {
        Map<String, List<String>> map = new HashMap<>();
        list.forEach(it -> {
            // 默认不过滤
            Predicate<LineDevGetDTO> uploadFilter = item -> true;
            if (Objects.equals(type, 1)) {
                uploadFilter = item -> Objects.equals(item.getIsUpToGrid(), 1);
            }

            Predicate<LineDevGetDTO> voltageFilter = item -> true;
            if (!Objects.isNull(voltage) && !Objects.equals(voltage, "")) {
                voltageFilter = item -> Objects.equals(item.getVoltageLevel(), voltage);
            }

            Predicate<LineDevGetDTO> runFlagFilter = item -> true;
            if (!Objects.isNull(runFlag)) {
                voltageFilter = item -> Objects.equals(item.getLineRunFlag(), runFlag);
            }

            // 组合两个过滤条件
            Predicate<LineDevGetDTO> combinedFilter = uploadFilter.and(voltageFilter);
            Predicate<LineDevGetDTO> combinedFilter2 = combinedFilter.and(runFlagFilter);
            map.put(it.getUnitId(), it.getLineBaseList().stream()
                    .filter(combinedFilter2)
                    .map(LineDevGetDTO::getPointId)
                    .distinct()
                    .collect(Collectors.toList()));
        });
        return map;
    }

}
