package com.njcn.harmonic.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjUtil;
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.LineFeignClient;
import com.njcn.device.pq.api.UserLedgerFeignClient;
import com.njcn.device.pq.enums.LineBaseEnum;
import com.njcn.device.pq.pojo.dto.GeneralDeviceDTO;
import com.njcn.device.pq.pojo.param.DeviceInfoParam;
import com.njcn.device.pq.pojo.vo.LineDetailVO;
import com.njcn.harmonic.mapper.RStatLimitRateDMapper;
import com.njcn.harmonic.mapper.SteadyQualifyMapper;
import com.njcn.harmonic.pojo.po.day.RStatLimitRateDPO;
import com.njcn.harmonic.pojo.vo.SteadyQualifyCensusVO;
import com.njcn.harmonic.pojo.vo.SteadyQualifyDetailVO;
import com.njcn.harmonic.pojo.vo.SteadyQualifyVO;
import com.njcn.harmonic.service.SteadyQualifyService;
import com.njcn.harmonic.utils.PubUtils;
import com.njcn.supervision.pojo.param.user.UserReportParam;
import com.njcn.supervision.pojo.vo.user.UserLedgerVO;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author: chenchao
 * @date: 2022/04/01 16:10
 * @Description: <描述>
 */
@Service
@RequiredArgsConstructor
public class SteadyQualifyServiceImpl implements SteadyQualifyService {

    private final GeneralDeviceInfoClient generalDeviceInfoClient;

    private final SteadyQualifyMapper steadyQualifyMapper;

    private final RStatLimitRateDMapper rStatLimitRateDMapper;

    private final UserLedgerFeignClient userLedgerFeignClient;

    private final LineFeignClient lineFeignClient;

    /**
     *
     */
    @Value("${version.used:master}")
    private String versionUsed;


    @Override
    public List<SteadyQualifyVO> getSteadyQualifyData(DeviceInfoParam.BusinessParam steadyParam) {
        List<SteadyQualifyVO> steadyQualifyList = new ArrayList<>();

        UserReportParam userReportParam = new UserReportParam();
        Map<String, UserLedgerVO> userMap = new HashMap<>();
        if (steadyParam.isUserLedger()) {
            List<UserLedgerVO> userLedgerList = userLedgerFeignClient.selectUserList(userReportParam).getData();
            userMap.putAll(userLedgerList.stream().collect(Collectors.toMap(UserLedgerVO::getId, Function.identity())));
        }

        //按照条件获取实际运行终端综合信息
        List<GeneralDeviceDTO> deviceDataList = generalDeviceInfoClient.getPracticalRunDeviceInfo(steadyParam).getData();
        //组装监测点Top层集合
        for (GeneralDeviceDTO generalDeviceDTO : deviceDataList) {
            if (CollectionUtils.isEmpty(generalDeviceDTO.getLineIndexes())) {
                continue;
            }
            SteadyQualifyVO steadyQualifyVO = new SteadyQualifyVO();
            steadyQualifyVO.setId(generalDeviceDTO.getIndex());
            steadyQualifyVO.setName(generalDeviceDTO.getName());
            List<RStatLimitRateDPO> qualifiesRate = getQualifiesRate(generalDeviceDTO.getLineIndexes(), steadyParam.getSearchBeginTime(), steadyParam.getSearchEndTime());
            //组装子集级数据树
            List<SteadyQualifyVO> treeList = getTreeData(qualifiesRate, generalDeviceDTO, userMap);
            if (CollectionUtil.isNotEmpty(treeList)) {
                setFatherDistortion(steadyQualifyVO, treeList);
            }
            steadyQualifyVO.setChildren(treeList);
            steadyQualifyList.add(steadyQualifyVO);
        }
        return steadyQualifyList;
    }

    @Override
    public SteadyQualifyCensusVO getSteadyQualifyCensus(DeviceInfoParam.BusinessParam steadyCensusParam) {
        List<SteadyQualifyVO> steadyQualifyList = getSteadyQualifyData(steadyCensusParam);
        SteadyQualifyCensusVO steadyQualifyCensusVO = new SteadyQualifyCensusVO();
        List<String> type = new ArrayList<>();
        List<Double> harmonicVoltage = new ArrayList<>(), voltageOffset = new ArrayList<>(),
                VoltageUnbalance = new ArrayList<>(), interHarmonic = new ArrayList<>(),
                harmonicCurrent = new ArrayList<>(), negativeCurrent = new ArrayList<>(),
                freqOffset = new ArrayList<>(), flicker = new ArrayList<>();
        if (CollUtil.isNotEmpty(steadyQualifyList)) {
            for (SteadyQualifyVO steadyQualifyVO : steadyQualifyList) {
                // 还需要递归出有多少个测点
                int lineNum = seekLineNum(steadyQualifyVO);
                type.add(steadyQualifyVO.getName() + "\n(" + lineNum + ")");
                harmonicVoltage.add(steadyQualifyVO.getHarmonicVoltage());
                voltageOffset.add(steadyQualifyVO.getVoltageOffset());
                VoltageUnbalance.add(steadyQualifyVO.getVoltageUnbalance());
                interHarmonic.add(steadyQualifyVO.getInterHarmonic());
                harmonicCurrent.add(steadyQualifyVO.getHarmonicCurrent());
                negativeCurrent.add(steadyQualifyVO.getNegativeCurrent());
                freqOffset.add(steadyQualifyVO.getFreqOffset());
                flicker.add(steadyQualifyVO.getFlicker());
            }
        }


//        List<String> type = new ArrayList<>();
//        //按照条件获取实际运行终端综合信息
//        List<GeneralDeviceDTO> deviceDataList = generalDeviceInfoClient.getPracticalRunDeviceInfo(steadyCensusParam).getData();
//        List<Double> harmonicVoltage = new ArrayList<>(), voltageOffset = new ArrayList<>(),
//                VoltageUnbalance = new ArrayList<>(), interHarmonic = new ArrayList<>(),
//                harmonicCurrent = new ArrayList<>(), negativeCurrent = new ArrayList<>(),
//                freqOffset = new ArrayList<>(), flicker = new ArrayList<>();
//        if (!CollectionUtils.isEmpty(deviceDataList)) {
//            for (GeneralDeviceDTO generalDeviceDTO : deviceDataList) {
//                List<String> lineIndexes = generalDeviceDTO.getLineIndexes();
//                if (CollectionUtils.isEmpty(lineIndexes)) {
//                    continue;
//                }
//                type.add(generalDeviceDTO.getName() + "\n(" + generalDeviceDTO.getLineIndexes().size() + ")");
//                List<RStatLimitRateDPO> qualifiesRate = getQualifiesRate(lineIndexes, steadyCensusParam.getSearchBeginTime(), steadyCensusParam.getSearchEndTime());
//                SteadyQualifyVO dataMoreMonitorMoreDay = getDataMoreMonitorMoreDay(qualifiesRate);
//                harmonicVoltage.add(dataMoreMonitorMoreDay.getHarmonicVoltage());
//                voltageOffset.add(dataMoreMonitorMoreDay.getVoltageOffset());
//                VoltageUnbalance.add(dataMoreMonitorMoreDay.getVoltageUnbalance());
//                interHarmonic.add(dataMoreMonitorMoreDay.getInterHarmonic());
//                harmonicCurrent.add(dataMoreMonitorMoreDay.getHarmonicCurrent());
//                negativeCurrent.add(dataMoreMonitorMoreDay.getNegativeCurrent());
//                freqOffset.add(dataMoreMonitorMoreDay.getFreqOffset());
//                flicker.add(dataMoreMonitorMoreDay.getFlicker());
//            }
//        }
        steadyQualifyCensusVO.setHarmonicVoltage(harmonicVoltage);
        steadyQualifyCensusVO.setVoltageOffset(voltageOffset);
        steadyQualifyCensusVO.setVoltageUnbalance(VoltageUnbalance);
        steadyQualifyCensusVO.setInterHarmonic(interHarmonic);
        steadyQualifyCensusVO.setHarmonicCurrent(harmonicCurrent);
        steadyQualifyCensusVO.setNegativeCurrent(negativeCurrent);
        steadyQualifyCensusVO.setFreqOffset(freqOffset);
        steadyQualifyCensusVO.setFlicker(flicker);
        steadyQualifyCensusVO.setType(type);

        return steadyQualifyCensusVO;
    }

    /**
     * 递归出有多少个测点
     *
     * @param steadyQualifyVO 最上层的信息
     */
    private int seekLineNum(SteadyQualifyVO steadyQualifyVO) {
        List<SteadyQualifyVO> children = steadyQualifyVO.getChildren();
        // 如果没有子节点，说明当前就是最底层节点，计数1
        if (children == null || children.isEmpty()) {
            return 1;
        }
        // 如果有子节点，递归计算所有子节点的最底层节点总数
        int total = 0;
        for (SteadyQualifyVO child : children) {
            total += seekLineNum(child);
        }
        return total;
    }

    @Override
    public List<SteadyQualifyVO> getEnterpriseSteadyQualify(DeviceInfoParam.BusinessParam steadyParam) {
        List<SteadyQualifyVO> steadyQualifyList = new ArrayList<>();

        //按照条件获取实际运行终端综合信息
        List<GeneralDeviceDTO> deviceDataList = generalDeviceInfoClient.getPracticalRunDeviceInfo(steadyParam).getData();
        //组装监测点Top层集合
        for (GeneralDeviceDTO generalDeviceDTO : deviceDataList) {
            List<String> lineIndexes = generalDeviceDTO.getLineIndexes();
            if (CollectionUtils.isEmpty(lineIndexes)) {
                continue;
            }
            SteadyQualifyVO steadyQualifyVO = new SteadyQualifyVO();
            steadyQualifyVO.setId(generalDeviceDTO.getIndex());
            steadyQualifyVO.setName(generalDeviceDTO.getName());
            List<RStatLimitRateDPO> qualifiesRate = getQualifiesRate(lineIndexes, steadyParam.getSearchBeginTime(), steadyParam.getSearchEndTime());
            //组装子集级数据树
            List<SteadyQualifyVO> treeList = getCompanyTreeData(qualifiesRate, lineIndexes);
            if (CollectionUtil.isNotEmpty(treeList)) {
                setFatherDistortion(steadyQualifyVO, treeList);
            }
            steadyQualifyVO.setChildren(treeList);
            steadyQualifyList.add(steadyQualifyVO);
        }
        return steadyQualifyList;
    }

    @Override
    public List<SteadyQualifyDetailVO> getSteadyQualifyTableData(DeviceInfoParam.BusinessParam steadyParam) {
        List<SteadyQualifyDetailVO> steadyQualifyDetailVOList = new ArrayList<>();
        //获取终端台账类信息
        List<GeneralDeviceDTO> deviceDataList = generalDeviceInfoClient.getPracticalRunDeviceInfo(steadyParam).getData();

        //收集所有lineIndexes并去重
        List<String> lineIdList = deviceDataList.stream()
                .filter(generalDeviceDTO -> CollectionUtil.isNotEmpty(generalDeviceDTO.getLineIndexes()))
                .flatMap(generalDeviceDTO -> generalDeviceDTO.getLineIndexes().stream())
                .distinct()
                .collect(Collectors.toList());

        if (CollectionUtil.isEmpty(lineIdList)) {
            return steadyQualifyDetailVOList;
        }

        //获取稳态合格率数据
        List<RStatLimitRateDPO> qualifiesRate = getQualifiesRate(lineIdList, steadyParam.getSearchBeginTime(), steadyParam.getSearchEndTime());

        //获取监测点集合
        List<SteadyQualifyVO> monitorList = steadyQualifyMapper.getSteadyQualifyData(lineIdList);

        //获取所有监测点信息信息
        List<LineDetailVO.Detail> lineInfoByIds = lineFeignClient.getLineDetailByIds(lineIdList).getData();
        Map<String, LineDetailVO.Detail> lineDetailMap = lineInfoByIds.stream()
                .collect(Collectors.toMap(LineDetailVO.Detail::getLineId, Function.identity()));

        //组装列表数据
        for (SteadyQualifyVO monitor : monitorList) {
            SteadyQualifyDetailVO detailVO = new SteadyQualifyDetailVO();

            //填充监测点详细信息
            LineDetailVO.Detail lineDetail = lineDetailMap.get(monitor.getId());
            if (lineDetail != null) {
                detailVO.setCity(lineDetail.getDeptName());
                detailVO.setCompany(lineDetail.getGdName());
                detailVO.setSubStation(lineDetail.getSubName());
                detailVO.setDeviceId(lineDetail.getDevId());
                detailVO.setDeviceName(lineDetail.getDevName());
                detailVO.setManufacturer(lineDetail.getManufacturer());
                detailVO.setIp(lineDetail.getIp());
                detailVO.setLineName(lineDetail.getLineName());
            }

            //计算单个监测点的合格率
            SteadyQualifyVO dataSingleMonitorMoreDay = getDataSingleMonitorMoreDay(qualifiesRate, monitor.getId());
            detailVO.setFlicker(PubUtils.dataLimits(dataSingleMonitorMoreDay.getFlicker()));
            detailVO.setFreqOffset(PubUtils.dataLimits(dataSingleMonitorMoreDay.getFreqOffset()));
            detailVO.setVoltageOffset(PubUtils.dataLimits(dataSingleMonitorMoreDay.getVoltageOffset()));
            detailVO.setVoltageUnbalance(PubUtils.dataLimits(dataSingleMonitorMoreDay.getVoltageUnbalance()));
            detailVO.setNegativeCurrent(PubUtils.dataLimits(dataSingleMonitorMoreDay.getNegativeCurrent()));
            detailVO.setHarmonicVoltage(PubUtils.dataLimits(dataSingleMonitorMoreDay.getHarmonicVoltage()));
            detailVO.setHarmonicCurrent(PubUtils.dataLimits(dataSingleMonitorMoreDay.getHarmonicCurrent()));
            detailVO.setInterHarmonic(PubUtils.dataLimits(dataSingleMonitorMoreDay.getInterHarmonic()));

            steadyQualifyDetailVOList.add(detailVO);
        }

        //先按变电站排序，再按地市排序
        steadyQualifyDetailVOList.sort(Comparator
                .comparing(SteadyQualifyDetailVO::getSubStation, Comparator.nullsLast(String::compareTo))
                .thenComparing(SteadyQualifyDetailVO::getCity, Comparator.nullsLast(String::compareTo)));

        return steadyQualifyDetailVOList;
    }

    /**
     * 获取父级每层数据
     */
    private List<SteadyQualifyVO> getTreeData(List<RStatLimitRateDPO> qualifiesRate, GeneralDeviceDTO generalDeviceDTO, Map<String, UserLedgerVO> userMap) {
        //监测点集合
        List<SteadyQualifyVO> treeMonitorList = steadyQualifyMapper.getSteadyQualifyData(generalDeviceDTO.getLineIndexes());
        treeMonitorList.forEach(steadyQualifyVO -> {
            SteadyQualifyVO dataSingleMonitorMoreDay = getDataSingleMonitorMoreDay(qualifiesRate, steadyQualifyVO.getId());
            steadyQualifyVO.setFlicker(PubUtils.dataLimits(dataSingleMonitorMoreDay.getFlicker()));
            steadyQualifyVO.setFreqOffset(PubUtils.dataLimits(dataSingleMonitorMoreDay.getFreqOffset()));
            steadyQualifyVO.setVoltageOffset(PubUtils.dataLimits(dataSingleMonitorMoreDay.getVoltageOffset()));
            steadyQualifyVO.setVoltageUnbalance(PubUtils.dataLimits(dataSingleMonitorMoreDay.getVoltageUnbalance()));
            steadyQualifyVO.setNegativeCurrent(PubUtils.dataLimits(dataSingleMonitorMoreDay.getNegativeCurrent()));
            steadyQualifyVO.setHarmonicVoltage(PubUtils.dataLimits(dataSingleMonitorMoreDay.getHarmonicVoltage()));
            steadyQualifyVO.setHarmonicCurrent(PubUtils.dataLimits(dataSingleMonitorMoreDay.getHarmonicCurrent()));
            steadyQualifyVO.setInterHarmonic(PubUtils.dataLimits(dataSingleMonitorMoreDay.getInterHarmonic()));
        });

        List<SteadyQualifyVO> userLineList = treeMonitorList.stream().filter(it -> StrUtil.isNotBlank(it.getObjId())).collect(Collectors.toList());
        List<SteadyQualifyVO> otherLineList = treeMonitorList.stream().filter(it -> StrUtil.isBlank(it.getObjId())).collect(Collectors.toList());

        Map<String, List<SteadyQualifyVO>> temMap = new HashMap<>();
        if (CollUtil.isNotEmpty(userLineList)) {
            Map<String, List<SteadyQualifyVO>> objMap = userLineList.stream().collect(Collectors.groupingBy(SteadyQualifyVO::getObjId));
            List<SteadyQualifyVO> temList = new ArrayList<>();
            objMap.forEach((objId, monitorList) -> {
                UserLedgerVO userLedgerVO = userMap.get(objId);
                SteadyQualifyVO tree = new SteadyQualifyVO();
                tree.setPid(userLedgerVO.getStationId());
                tree.setId(userLedgerVO.getId());
                tree.setChildren(monitorList);
                tree.setName(userLedgerVO.getProjectName());
                setFatherDistortion(tree, monitorList);
                temList.add(tree);
            });
            temMap = temList.stream().collect(Collectors.groupingBy(SteadyQualifyVO::getPid));
        }
        //变电站集合
        List<SteadyQualifyVO> substationList = steadyQualifyMapper.getLineInfoByList(generalDeviceDTO.getSubIndexes());
        //供电公司集合
        List<SteadyQualifyVO> powerCompanyList = steadyQualifyMapper.getLineInfoByList(generalDeviceDTO.getGdIndexes());
        dealChildrenData(substationList, otherLineList, temMap, true);

        if("liaoning".equals(versionUsed)){
            return substationList;
        }else {
            dealChildrenData(powerCompanyList, substationList, temMap, false);
            return powerCompanyList;
        }
    }


    /**
     * 处理变电站
     *
     * @param targetData
     * @param childrenData
     * @param isLine
     */
    private void dealChildrenData(List<SteadyQualifyVO> targetData, List<SteadyQualifyVO> childrenData, Map<String, List<SteadyQualifyVO>> userLineMap, boolean isLine) {
        // 创建一个map集合，用于封装对象
        Map<String, List<SteadyQualifyVO>> groupLine;
        if (isLine) {
            // 通过stream流分组
            groupLine = childrenData.stream().collect(Collectors.groupingBy(terminalTree -> {
                // 获取父id字符串，通过 逗号 分割 成一个数组
                String[] pid = terminalTree.getPids().split(StrUtil.COMMA);
                return pid[LineBaseEnum.SUB_LEVEL.getCode()];
            }));
        } else {
            groupLine = childrenData.stream().collect(Collectors.groupingBy(SteadyQualifyVO::getPid));
        }
        //变电站
        targetData.forEach(terminalTree -> {
            List<SteadyQualifyVO> terminalTrees = new ArrayList<>();
            if (groupLine.containsKey(terminalTree.getId())) {
                terminalTrees.addAll(groupLine.get(terminalTree.getId()).stream().sorted(Comparator.comparing(SteadyQualifyVO::getSort)).collect(Collectors.toList()));
            }
            if (isLine) {
                //变电站集合
                if (userLineMap.containsKey(terminalTree.getId())) {
                    List<SteadyQualifyVO> userList = userLineMap.get(terminalTree.getId());
                    terminalTrees.addAll(userList);
                }
                terminalTree.setChildren(terminalTrees);
            } else {
                terminalTree.setChildren(terminalTrees);
            }
            setFatherDistortion(terminalTree, terminalTrees);
        });
    }

    private Boolean isData(Double data) {
        return ObjUtil.isNotNull(data) && data != 3.14159;
    }

    /**
     * 计算父级合格率
     */
    private void setFatherDistortion(SteadyQualifyVO steadyQualifyVO, List<SteadyQualifyVO> steadyResults) {
        List<Double> flicker = steadyResults.stream().filter(s -> isData(s.getFlicker())).map(SteadyQualifyVO::getFlicker).collect(Collectors.toList());
        List<Double> freqOffset = steadyResults.stream().filter(s -> isData(s.getFreqOffset())).map(SteadyQualifyVO::getFreqOffset).collect(Collectors.toList());
        List<Double> voltageOffset = steadyResults.stream().filter(s -> isData(s.getVoltageOffset())).map(SteadyQualifyVO::getVoltageOffset).collect(Collectors.toList());
        List<Double> voltageUnbalance = steadyResults.stream().filter(s -> isData(s.getVoltageUnbalance())).map(SteadyQualifyVO::getVoltageUnbalance).collect(Collectors.toList());
        List<Double> negativeCurrent = steadyResults.stream().filter(s -> isData(s.getNegativeCurrent())).map(SteadyQualifyVO::getNegativeCurrent).collect(Collectors.toList());
        List<Double> harmonicVoltage = steadyResults.stream().filter(s -> isData(s.getHarmonicVoltage())).map(SteadyQualifyVO::getHarmonicVoltage).collect(Collectors.toList());
        List<Double> harmonicCurrent = steadyResults.stream().filter(s -> isData(s.getHarmonicCurrent())).map(SteadyQualifyVO::getHarmonicCurrent).collect(Collectors.toList());
        List<Double> interHarmonic = steadyResults.stream().filter(s -> isData(s.getInterHarmonic())).map(SteadyQualifyVO::getInterHarmonic).collect(Collectors.toList());
        //求各项平均值
        if (!CollectionUtils.isEmpty(flicker)) {
            steadyQualifyVO.setFlicker(PubUtils.dataLimits(NumberUtil.round(flicker.stream().mapToDouble(Double::valueOf).average().orElse(100), 2).doubleValue()));
        }
        if (!CollectionUtils.isEmpty(freqOffset)) {
            steadyQualifyVO.setFreqOffset(PubUtils.dataLimits(NumberUtil.round(freqOffset.stream().mapToDouble(Double::valueOf).average().orElse(100), 2).doubleValue()));
        }
        if (!CollectionUtils.isEmpty(voltageOffset)) {
            steadyQualifyVO.setVoltageOffset(PubUtils.dataLimits(NumberUtil.round(voltageOffset.stream().mapToDouble(Double::valueOf).average().orElse(100), 2).doubleValue()));
        }
        if (!CollectionUtils.isEmpty(voltageUnbalance)) {
            steadyQualifyVO.setVoltageUnbalance(PubUtils.dataLimits(NumberUtil.round(voltageUnbalance.stream().mapToDouble(Double::valueOf).average().orElse(100), 2).doubleValue()));
        }
        if (!CollectionUtils.isEmpty(negativeCurrent)) {
            steadyQualifyVO.setNegativeCurrent(PubUtils.dataLimits(NumberUtil.round(negativeCurrent.stream().mapToDouble(Double::valueOf).average().orElse(100), 2).doubleValue()));
        }
        if (!CollectionUtils.isEmpty(harmonicVoltage)) {
            steadyQualifyVO.setHarmonicVoltage(PubUtils.dataLimits(NumberUtil.round(harmonicVoltage.stream().mapToDouble(Double::valueOf).average().orElse(100), 2).doubleValue()));
        }
        if (!CollectionUtils.isEmpty(harmonicCurrent)) {
            steadyQualifyVO.setHarmonicCurrent(PubUtils.dataLimits(NumberUtil.round(harmonicCurrent.stream().mapToDouble(Double::valueOf).average().orElse(100), 2).doubleValue()));
        }
        if (!CollectionUtils.isEmpty(interHarmonic)) {
            steadyQualifyVO.setInterHarmonic(PubUtils.dataLimits(NumberUtil.round(interHarmonic.stream().mapToDouble(Double::valueOf).average().orElse(100), 2).doubleValue()));
        }
    }


    private void setChildesList(List<SteadyQualifyVO> item, List<SteadyQualifyVO> childes) {
        Map<String, List<SteadyQualifyVO>> groupLine;
        groupLine = childes.stream().collect(Collectors.groupingBy(steadyQualifyVO -> {
            String[] pid = steadyQualifyVO.getPids().split(",");
            return pid[LineBaseEnum.SUB_LEVEL.getCode()];
        }));
        item.stream().peek(steadyQualifyVO -> {
            if (!CollectionUtils.isEmpty(groupLine.get(steadyQualifyVO.getId()))) {
                steadyQualifyVO.setChildren(groupLine.get(steadyQualifyVO.getId()));
                setFatherDistortion(steadyQualifyVO, steadyQualifyVO.getChildren());

            }
        }).collect(Collectors.toList());
    }

    /**
     * 计算监测点日统计合格率
     */
    public List<SteadyQualifyVO> getDataSingleMonitorSingeDay(List<RStatLimitRateDPO> qualifiesRate) {
        List<SteadyQualifyVO> list = new ArrayList<>();
        SteadyQualifyVO steadyQualifyVO;
        if (!CollectionUtil.isEmpty(qualifiesRate)) {
            for (RStatLimitRateDPO steadyQualifyDTO : qualifiesRate) {
                steadyQualifyVO = new SteadyQualifyVO();
                //闪变合格率
                steadyQualifyVO.setFlicker(calculate(steadyQualifyDTO.getFlickerAllTime(), steadyQualifyDTO.getFlickerOvertime()));
                //频率偏差合格率
                steadyQualifyVO.setFreqOffset(calculate(steadyQualifyDTO.getAllTime(), steadyQualifyDTO.getFreqDevOvertime()));
                //计算电压偏差
                steadyQualifyVO.setVoltageOffset(calculate(steadyQualifyDTO.getAllTime(), steadyQualifyDTO.getVoltageDevOvertime()));
                //相电压不平衡度
                steadyQualifyVO.setVoltageUnbalance(calculate(steadyQualifyDTO.getAllTime(), steadyQualifyDTO.getUbalanceOvertime()));
                //负序电流
                steadyQualifyVO.setNegativeCurrent(calculate(steadyQualifyDTO.getAllTime(), steadyQualifyDTO.getINegOvertime()));
                //谐波电压
                steadyQualifyVO.setHarmonicVoltage(calculateV(steadyQualifyDTO.getAllTime(), (steadyQualifyDTO.getUaberranceOvertime() +
                        steadyQualifyDTO.getUharm2Overtime() +
                        steadyQualifyDTO.getUharm3Overtime() +
                        steadyQualifyDTO.getUharm4Overtime() +
                        steadyQualifyDTO.getUharm5Overtime() +
                        steadyQualifyDTO.getUharm6Overtime() +
                        steadyQualifyDTO.getUharm7Overtime() +
                        steadyQualifyDTO.getUharm8Overtime() +
                        steadyQualifyDTO.getUharm9Overtime() +
                        steadyQualifyDTO.getUharm10Overtime() +
                        steadyQualifyDTO.getUharm11Overtime() +
                        steadyQualifyDTO.getUharm12Overtime() +
                        steadyQualifyDTO.getUharm13Overtime() +
                        steadyQualifyDTO.getUharm14Overtime() +
                        steadyQualifyDTO.getUharm15Overtime() +
                        steadyQualifyDTO.getUharm16Overtime() +
                        steadyQualifyDTO.getUharm17Overtime() +
                        steadyQualifyDTO.getUharm18Overtime() +
                        steadyQualifyDTO.getUharm19Overtime() +
                        steadyQualifyDTO.getUharm20Overtime() +
                        steadyQualifyDTO.getUharm21Overtime() +
                        steadyQualifyDTO.getUharm22Overtime() +
                        steadyQualifyDTO.getUharm23Overtime() +
                        steadyQualifyDTO.getUharm24Overtime() +
                        steadyQualifyDTO.getUharm25Overtime())));
                //谐波电流
                steadyQualifyVO.setHarmonicCurrent(calculateI(steadyQualifyDTO.getAllTime(), (steadyQualifyDTO.getIharm2Overtime() +
                        steadyQualifyDTO.getIharm3Overtime() +
                        steadyQualifyDTO.getIharm4Overtime() +
                        steadyQualifyDTO.getIharm5Overtime() +
                        steadyQualifyDTO.getIharm6Overtime() +
                        steadyQualifyDTO.getIharm7Overtime() +
                        steadyQualifyDTO.getIharm8Overtime() +
                        steadyQualifyDTO.getIharm9Overtime() +
                        steadyQualifyDTO.getIharm10Overtime() +
                        steadyQualifyDTO.getIharm11Overtime() +
                        steadyQualifyDTO.getIharm12Overtime() +
                        steadyQualifyDTO.getIharm13Overtime() +
                        steadyQualifyDTO.getIharm14Overtime() +
                        steadyQualifyDTO.getIharm15Overtime() +
                        steadyQualifyDTO.getIharm16Overtime() +
                        steadyQualifyDTO.getIharm17Overtime() +
                        steadyQualifyDTO.getIharm18Overtime() +
                        steadyQualifyDTO.getIharm19Overtime() +
                        steadyQualifyDTO.getIharm20Overtime() +
                        steadyQualifyDTO.getIharm21Overtime() +
                        steadyQualifyDTO.getIharm22Overtime() +
                        steadyQualifyDTO.getIharm23Overtime() +
                        steadyQualifyDTO.getIharm24Overtime() +
                        steadyQualifyDTO.getIharm25Overtime())));
                //间谐波电压含有率
                steadyQualifyVO.setInterHarmonic(calculateIN(steadyQualifyDTO.getAllTime() * 16, (steadyQualifyDTO.getInuharm1Overtime() +
                        steadyQualifyDTO.getInuharm2Overtime() +
                        steadyQualifyDTO.getInuharm3Overtime() +
                        steadyQualifyDTO.getInuharm4Overtime() +
                        steadyQualifyDTO.getInuharm5Overtime() +
                        steadyQualifyDTO.getInuharm6Overtime() +
                        steadyQualifyDTO.getInuharm7Overtime() +
                        steadyQualifyDTO.getInuharm8Overtime() +
                        steadyQualifyDTO.getInuharm9Overtime() +
                        steadyQualifyDTO.getInuharm10Overtime() +
                        steadyQualifyDTO.getInuharm11Overtime() +
                        steadyQualifyDTO.getInuharm12Overtime() +
                        steadyQualifyDTO.getInuharm13Overtime() +
                        steadyQualifyDTO.getInuharm14Overtime() +
                        steadyQualifyDTO.getInuharm15Overtime() +
                        steadyQualifyDTO.getInuharm16Overtime())));
                list.add(steadyQualifyVO);
            }
        }
        return list;
    }

    /**
     * 监测点时间范围统计合格率
     */
    public SteadyQualifyVO getDataSingleMonitorMoreDay(List<RStatLimitRateDPO> qualifiesRate, String lineId) {
        SteadyQualifyVO steadyQualifyVO = new SteadyQualifyVO();
        //从数据里筛选出指定监测点的数据
        List<RStatLimitRateDPO> steadyQualifyDTOList = qualifiesRate.stream().filter(
                temp -> temp.getLineId().equalsIgnoreCase(lineId)).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(steadyQualifyDTOList)) {
            List<SteadyQualifyVO> steadyQualifyVOS = new ArrayList<>();
            //获取出时间和id，调用第一个方法(改展示一条数据，可以不用每天都统计)
            steadyQualifyVOS.addAll(getDataSingleMonitorSingeDay(steadyQualifyDTOList));
            if (CollectionUtil.isNotEmpty(steadyQualifyVOS)) {
                setFatherDistortion(steadyQualifyVO, steadyQualifyVOS);
            }
        }
        return steadyQualifyVO;
    }

    /**
     * 计算区域监测点时间范围统计合格率
     */
    public SteadyQualifyVO getDataMoreMonitorMoreDay(List<RStatLimitRateDPO> qualifiesRate) {
        SteadyQualifyVO steadyQualifyVO = new SteadyQualifyVO();
        List<SteadyQualifyVO> steadyResults = new ArrayList<>();
        //获取所有监测点每天信息(根本不需要时间分组，只是要所有的统计)
        steadyResults.addAll(getDataSingleMonitorSingeDay(qualifiesRate));
        if (CollectionUtil.isNotEmpty(steadyResults)) {
            setFatherDistortion(steadyQualifyVO, steadyResults);
        }
        return steadyQualifyVO;
    }


    /**
     * influxDB查询稳态监测点相关信息
     *
     * @param lineIndexes
     * @param startTime
     * @param endTime
     */
    private List<RStatLimitRateDPO> getQualifiesRate(List<String> lineIndexes, String startTime, String endTime) {
        return rStatLimitRateDMapper.selectList(new LambdaQueryWrapper<RStatLimitRateDPO>()
                .in(RStatLimitRateDPO::getLineId, lineIndexes)
                .eq(RStatLimitRateDPO::getPhasicType, "T")
                .ge(StrUtil.isNotBlank(startTime), RStatLimitRateDPO::getTime, DateUtil.beginOfDay(DateUtil.parse(startTime)))
                .le(StrUtil.isNotBlank(endTime), RStatLimitRateDPO::getTime, DateUtil.endOfDay(DateUtil.parse(endTime)))
        );
    }


    private static double calculate(Integer allTime, Integer overTime) {
        if (allTime == 0) {
            return 3.14159;
        } else {
            if (allTime >= overTime) {
                return NumberUtil.round((allTime - overTime) * 1.0 / allTime * 100.0, 2).doubleValue();
            }
            return 0.0;
        }
    }

    /**
     * 电压
     *
     * @param allTime  总条数
     * @param overTime 相加
     * @return
     */
    private static double calculateV(Integer allTime, Integer overTime) {
        if (allTime == 0) {
            return 3.14159;
        } else {
            if (allTime >= overTime) {
                return NumberUtil.round((1 - (overTime / (allTime * 25.0))) * 100, 2).doubleValue();
            }
            return 0.0;
        }
    }

    /**
     * 电流
     *
     * @param allTime
     * @param overTime
     * @return
     */
    private static double calculateI(Integer allTime, Integer overTime) {
        if (allTime == 0) {
            return 3.14159;
        } else {
            if (allTime >= overTime) {
                return NumberUtil.round((1 - (overTime / (allTime * 24.0))) * 100, 2).doubleValue();
            }
            return 0.0;
        }
    }

    /**
     * 间谐波
     *
     * @param allTime
     * @param overTime
     * @return
     */
    private static double calculateIN(Integer allTime, Integer overTime) {
        if (allTime == 0) {
            return 3.14159;
        } else {
            if (allTime >= overTime) {
                return NumberUtil.round((1 - ((double) overTime / allTime)) * 100, 2).doubleValue();
            }
            return 0.0;
        }
    }


    /**
     * 获取父级每层数据
     */
    private List<SteadyQualifyVO> getCompanyTreeData(List<RStatLimitRateDPO> qualifiesRate, List<String> lineIndexes) {
        //监测点集合
        List<SteadyQualifyVO> monitorList = steadyQualifyMapper.getSteadyQualifyData(lineIndexes);
        //母线集合
        List<SteadyQualifyVO> busBarList = steadyQualifyMapper.getLineInfoByList(monitorList.stream().map(SteadyQualifyVO::getPid).distinct().collect(Collectors.toList()));
        //终端集合
        List<SteadyQualifyVO> deviceList = steadyQualifyMapper.getLineInfoByList(busBarList.stream().map(SteadyQualifyVO::getPid).distinct().collect(Collectors.toList()));
        //变电站集合
        List<SteadyQualifyVO> substationList = steadyQualifyMapper.getLineInfoByList(deviceList.stream().map(SteadyQualifyVO::getPid).distinct().collect(Collectors.toList()));
        //供电公司集合
        List<SteadyQualifyVO> powerCompanyList = steadyQualifyMapper.getLineInfoByList(substationList.stream().map(SteadyQualifyVO::getPid).distinct().collect(Collectors.toList()));

//        List<SteadyQualifyDTO> qualifiesRate = getQualifiesRate(lineIndexes, steadyParam.getSearchBeginTime(), steadyParam.getSearchEndTime());
        monitorList.forEach(steadyQualifyVO -> {
            SteadyQualifyVO dataSingleMonitorMoreDay = getDataSingleMonitorMoreDay(qualifiesRate, steadyQualifyVO.getId());
            steadyQualifyVO.setFlicker(PubUtils.dataLimits(dataSingleMonitorMoreDay.getFlicker()));
            steadyQualifyVO.setFreqOffset(PubUtils.dataLimits(dataSingleMonitorMoreDay.getFreqOffset()));
            steadyQualifyVO.setVoltageOffset(PubUtils.dataLimits(dataSingleMonitorMoreDay.getVoltageOffset()));
            steadyQualifyVO.setVoltageUnbalance(PubUtils.dataLimits(dataSingleMonitorMoreDay.getVoltageUnbalance()));
            steadyQualifyVO.setNegativeCurrent(PubUtils.dataLimits(dataSingleMonitorMoreDay.getNegativeCurrent()));
            steadyQualifyVO.setHarmonicVoltage(PubUtils.dataLimits(dataSingleMonitorMoreDay.getHarmonicVoltage()));
            steadyQualifyVO.setHarmonicCurrent(PubUtils.dataLimits(dataSingleMonitorMoreDay.getHarmonicCurrent()));
            steadyQualifyVO.setInterHarmonic(PubUtils.dataLimits(dataSingleMonitorMoreDay.getInterHarmonic()));
        });
        setChildesList(substationList, monitorList);


        return substationList;
    }

}
