package com.njcn.device.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.enums.common.ServerEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.utils.EnumUtils;
import com.njcn.common.utils.PubUtils;
import com.njcn.device.enums.DeviceResponseEnum;
import com.njcn.device.enums.LineBaseEnum;
import com.njcn.device.mapper.*;
import com.njcn.device.pojo.dto.GeneralDeviceDTO;
import com.njcn.device.pojo.dto.PollutionLineDTO;
import com.njcn.device.pojo.dto.PollutionParamDTO;
import com.njcn.device.pojo.dto.PollutionSubstationDTO;
import com.njcn.device.pojo.param.DeviceInfoParam;
import com.njcn.device.pojo.po.*;
import com.njcn.device.pojo.vo.*;
import com.njcn.device.service.LineService;
import com.njcn.influxdb.utils.InfluxDbUtils;
import com.njcn.system.api.AreaFeignClient;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.pojo.po.Area;
import com.njcn.web.pojo.vo.LineDataVO;
import com.njcn.web.utils.GeneralUtil;
import com.njcn.web.utils.RequestUtil;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.influxdb.dto.QueryResult;
import org.influxdb.impl.InfluxDBResultMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 监测点类
 *
 * @author denghuajun
 * @date 2022/2/23
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LineServiceImpl extends ServiceImpl<LineMapper, Line> implements LineService {

    private final AreaFeignClient areaFeignClient;

    private final DicDataFeignClient dicDataFeignClient;

    private final VoltageMapper voltageMapper;

    private final LineDetailMapper lineDetailMapper;

    private final DeviceMapper deviceMapper;

    private final OverlimitMapper overlimitMapper;

    private final SubstationMapper substationMapper;

    private final CommunicateMapper communicateMapper;

    private final GeneralDeviceService generalDeviceService;

    private final LineMapper lineMapper;

    private final InfluxDbUtils influxDbUtils;

    @Override
    public LineDetailDataVO getLineDetailData(String id) {
        //根据id查询当前信息的pids
        List<String> pids = Arrays.asList(this.baseMapper.selectById(id).getPids().split(","));
        List<String> list = new ArrayList(pids);
        list.add(id);
        List<LineDataVO> lineDataVOList = this.baseMapper.getLineDetail(list);
        LineDetailDataVO lineDetailDataVO = new LineDetailDataVO();
        String areaId = "", devId = "", voId = "";
        for (LineDataVO lineDataVO : lineDataVOList) {
            switch (lineDataVO.getLevel()) {
                case 1:
                    areaId = lineDataVO.getName();
                    break;
                case 2:
                    lineDetailDataVO.setGdName(lineDataVO.getName());
                    break;
                case 3:
                    lineDetailDataVO.setBdName(lineDataVO.getName());
                    break;
                case 4:
                    devId = lineDataVO.getId();
                    lineDetailDataVO.setDevName(lineDataVO.getName());
                    break;
                case 5:
                    voId = lineDataVO.getId();
                    break;
                case 6:
                    lineDetailDataVO.setLineName(lineDataVO.getName());
                    break;
                default:
                    break;
            }
        }
        lineDetailDataVO.setAreaName(areaFeignClient.selectIdArea(areaId).getData().getName());
        lineDetailDataVO.setScale(dicDataFeignClient.getDicDataById(voltageMapper.selectById(voId).getScale()).getData().getName());
        LineDetail lineDetail = lineDetailMapper.selectById(id);
        Device device = deviceMapper.selectById(devId);
        lineDetailDataVO.setManufacturer(dicDataFeignClient.getDicDataById(device.getManufacturer()).getData().getName());
        lineDetailDataVO.setComFlag(PubUtils.comFlag(device.getComFlag()));
        lineDetailDataVO.setRunFlag(PubUtils.runFlag(device.getRunFlag()));
        lineDetailDataVO.setIp(device.getIp());
        lineDetailDataVO.setBusinessType(dicDataFeignClient.getDicDataById(lineDetail.getBusinessType()).getData().getName());
        lineDetailDataVO.setLoadType(dicDataFeignClient.getDicDataById(lineDetail.getLoadType()).getData().getName());
        lineDetailDataVO.setObjName(lineDetail.getObjName());
        lineDetailDataVO.setId(lineDetail.getNum());
        lineDetailDataVO.setPtType(PubUtils.ptType(lineDetail.getPtType()));
        lineDetailDataVO.setPt(lineDetail.getPt1() + "/" + lineDetail.getPt2());
        lineDetailDataVO.setCt(lineDetail.getCt1() + "/" + lineDetail.getCt2());
        lineDetailDataVO.setDealCapacity(lineDetail.getDealCapacity());
        lineDetailDataVO.setDevCapacity(lineDetail.getDevCapacity());
        lineDetailDataVO.setShortCapacity(lineDetail.getShortCapacity());
        lineDetailDataVO.setStandardCapacity(lineDetail.getStandardCapacity());
        return lineDetailDataVO;
    }

    @Override
    public LineOverLimitVO getLineOverLimitData(String id) {
        //根据监测点id查询所在监测点的限值表数据
        Overlimit overlimit = overlimitMapper.selectById(id);
        LineOverLimitVO lineOverLimitVO = new LineOverLimitVO();
        BeanUtil.copyProperties(overlimit, lineOverLimitVO);
        lineOverLimitVO.setOddHarm(overlimit.getUharm3());
        lineOverLimitVO.setEvenHarm(overlimit.getUharm2());
        lineOverLimitVO.setInUharm(overlimit.getInuharm1());
        lineOverLimitVO.setInUharm16(overlimit.getInuharm16());
        return lineOverLimitVO;
    }

    @Override
    public List<SubstationDetailVO> getSubstationData(List<String> id) {
        return substationMapper.getSubstationData(id);
    }

    @Override
    public CommunicateVO getComFlagInfoData(String id, String searchBeginTime, String searchEndTime) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String devId = getLineIdByDevId(id);
        QueryWrapper<Communicate> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Communicate::getId, devId)
                .between(Communicate::getUpdateTime, PubUtils.beginTimeToLocalDateTime(searchBeginTime), PubUtils.endTimeToLocalDateTime(searchEndTime));
        queryWrapper.orderBy(true, true, "pq_communicate.update_time");
        List<Communicate> communicateList = communicateMapper.selectList(queryWrapper);
        CommunicateVO communicateVOList = new CommunicateVO();
        List<String> updateTime = new ArrayList<>();
        List<Integer> comType = new ArrayList<>();
        for (Communicate communicate : communicateList) {
            updateTime.add(df.format(communicate.getUpdateTime()));
            comType.add(communicate.getType());
        }
        communicateVOList.setUpdateTime(updateTime);
        communicateVOList.setType(comType);
        return communicateVOList;
    }

    @Override
    public String getLineIdByDevId(String id) {
        //根据id查询当前信息的pids
        List<String> pids = Arrays.asList(this.baseMapper.selectById(id).getPids().split(","));
        List<LineDataVO> lineDataVOList = this.baseMapper.getLineDetail(pids);
        String devId = "";
        for (LineDataVO lineDataVO : lineDataVOList) {
            if (lineDataVO.getLevel() == 4) {
                devId = lineDataVO.getId();
            }
        }
        return devId;
    }

    @Override
    public Overlimit getOverLimitData(String id) {
        return overlimitMapper.selectById(id);
    }

    @Override
    public List<Overlimit> getAllLineOverLimit(String serverType, String deptId) {
        List<Overlimit> overlimitList = new ArrayList<>();
        ServerEnum serverEnum = EnumUtils.getServerEnumByName(serverType);
        List<Integer> dataType = new ArrayList<>();
        dataType.add(2);
        switch (serverEnum) {
            case EVENT:
                dataType.add(0);
                break;
            case HARMONIC:
                dataType.add(1);
                break;
            default:
                dataType.add(0);
                dataType.add(1);
                break;
        }

        if (StrUtil.isBlank(deptId)) {
            //不传部门id情况,默认查询所有的投运在线的监测点
            overlimitList = this.baseMapper.getAllLineOverLimit(dataType);

        } else {

            DeviceInfoParam deviceInfoParam = new DeviceInfoParam(RequestUtil.getDeptIndex(), serverType);
            List<GeneralDeviceDTO> generalDeviceDTOList = generalDeviceService.getDeviceInfoAsDept(deviceInfoParam, Stream.of(0).collect(Collectors.toList()), Stream.of(1).collect(Collectors.toList()));
            if (CollectionUtil.isNotEmpty(generalDeviceDTOList)) {
                List<String> lineIndexes = new ArrayList<>();
                generalDeviceDTOList.forEach((item) -> lineIndexes.addAll(item.getLineIndexes()));

                if (lineIndexes.size() > 1000) {
                    List<List<String>> index = GeneralUtil.splitList(lineIndexes, 1000);
                    for (List<String> item : index) {
                        List<Overlimit> tem = overlimitMapper.selectBatchIds(item);
                        if (CollectionUtil.isNotEmpty(tem)) {
                            overlimitList.addAll(tem);
                        }
                    }
                } else {
                    overlimitList = overlimitMapper.selectBatchIds(lineIndexes);
                }
            } else {
                throw new BusinessException(DeviceResponseEnum.LINE_EMPTY);
            }
        }
        return overlimitList;
    }

    @Override
    public PollutionSubstationDTO getSubstationInfo(String id) {
        return this.baseMapper.getSubstationInfo(id);
    }

    @Override
    public List<PollutionLineDTO> getLineInfo(PollutionParamDTO pollutionParamDTO) {
        return this.baseMapper.getLineInfo(pollutionParamDTO.getLineList());
    }

    @Override
    public List<LineDistributionVO> getLineDistribution(DeviceInfoParam deviceInfoParam) {
        List<LineDistributionVO> lineDistributionVOList = new ArrayList<>();
        //获取所有监测点
        List<GeneralDeviceDTO> generalDeviceDTOList = generalDeviceService.getDeviceInfo(deviceInfoParam, Stream.of(0).collect(Collectors.toList()), Stream.of(1).collect(Collectors.toList()));
        for (GeneralDeviceDTO generalDeviceDTO : generalDeviceDTOList) {
            //根据部门id去获取省份信息
            Area area = areaFeignClient.areaDeptPro(generalDeviceDTO.getIndex()).getData();
            LineDistributionVO lineDistributionVO = new LineDistributionVO();
            lineDistributionVO.setName(generalDeviceDTO.getName());
            lineDistributionVO.setValue(generalDeviceDTO.getLineIndexes().size());
            lineDistributionVOList.add(lineDistributionVO);
        }

        List<LineDistributionVO> result =new ArrayList<LineDistributionVO>();
        Map<String, Integer> map = new HashMap<String, Integer>();
        for(LineDistributionVO lineDistributionVO:lineDistributionVOList){
            if (map.containsKey(lineDistributionVO.getName())) {
                map.put(lineDistributionVO.getName(), map.get(lineDistributionVO.getName())+lineDistributionVO.getValue());
            } else {
                map.put(lineDistributionVO.getName(), lineDistributionVO.getValue());
            }
        }
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            result.add(new LineDistributionVO(entry.getKey(),entry.getValue()));
        }
        return result;
    }

    @Override
    public List<LineStatisticsDetailVO> getLineStatisticsDetail(DeviceInfoParam.BusinessParam deviceInfoParam) {
        List<LineStatisticsDetailVO> lineStatisticsDetailList = new ArrayList<>();
        int lineTail = 0, lineSaveTail = 0, normalStateTail = 0, suspendStateTail = 0, offStreamStateTail = 0, hotSpareStateTail = 0;
        //按照条件获取实际运行终端综合信息
        List<GeneralDeviceDTO> generalDeviceDTOList = generalDeviceService.getDeviceInfo(deviceInfoParam, null, Stream.of(1).collect(Collectors.toList()));
        for (GeneralDeviceDTO generalDeviceDTO : generalDeviceDTOList) {
            LineStatisticsDetailVO lineStatisticsDetail = new LineStatisticsDetailVO();
            lineStatisticsDetail.setId(generalDeviceDTO.getIndex());
            lineStatisticsDetail.setAreaName(generalDeviceDTO.getName());
            lineStatisticsDetail.setLineNum(generalDeviceDTO.getLineIndexes().size());
            lineTail += generalDeviceDTO.getLineIndexes().size();
            if (generalDeviceDTO.getLineIndexes().size() > 0) {
                //获取监测点新增数
                QueryWrapper<Line> lineQueryWrapper = new QueryWrapper<>();
                lineQueryWrapper.in("pq_line.id", generalDeviceDTO.getLineIndexes());
                lineQueryWrapper.between("pq_line.Create_Time", DateUtil.beginOfDay(DateUtil.parse(deviceInfoParam.getSearchBeginTime())), DateUtil.endOfDay(DateUtil.parse(deviceInfoParam.getSearchEndTime())));
                int countNum = lineMapper.selectCount(lineQueryWrapper);
                lineSaveTail += countNum;
                lineStatisticsDetail.setAddLineNum(countNum);
                LineStateVO lineStateVO;
                //获取状态
                lineStateVO = lineMapper.getLineStatisticsDetail(generalDeviceDTO.getLineIndexes());
                BeanUtil.copyProperties(lineStateVO, lineStatisticsDetail);
                normalStateTail += lineStateVO.getNormalStateNum();
                suspendStateTail += lineStateVO.getSuspendStateNum();
                offStreamStateTail += lineStateVO.getOffStreamStateNum();
                hotSpareStateTail += lineStateVO.getHotSpareStateNum();
            } else {
                lineStatisticsDetail.setAddLineNum(0);
                lineStatisticsDetail.setHotSpareStateNum(0);
                lineStatisticsDetail.setOffStreamStateNum(0);
                lineStatisticsDetail.setNormalStateNum(0);
                lineStatisticsDetail.setSuspendStateNum(0);
            }
            lineStatisticsDetailList.add(lineStatisticsDetail);
        }
        LineStatisticsDetailVO lineStatisticsDetailVO = new LineStatisticsDetailVO();
        lineStatisticsDetailVO.setAreaName("总计");
        lineStatisticsDetailVO.setLineNum(lineTail);
        lineStatisticsDetailVO.setAddLineNum(lineSaveTail);
        lineStatisticsDetailVO.setNormalStateNum(normalStateTail);
        lineStatisticsDetailVO.setSuspendStateNum(suspendStateTail);
        lineStatisticsDetailVO.setHotSpareStateNum(hotSpareStateTail);
        lineStatisticsDetailVO.setOffStreamStateNum(offStreamStateTail);
        lineStatisticsDetailList.add(lineStatisticsDetailVO);
        int i = 1;
        for (LineStatisticsDetailVO statisticsDetailVO : lineStatisticsDetailList) {
            statisticsDetailVO.setOrderNo(i);
            i++;
        }
        return lineStatisticsDetailList;
    }

    @Override
    public List<LineStatisticsTableVO> getLineStatisticsTable(DeviceInfoParam.BusinessParam deviceInfoParam) {
        List<LineStatisticsTableVO> lineStatisticsTableList = new ArrayList<>();
        List<GeneralDeviceDTO> generalDeviceDTOList = generalDeviceService.getDeviceInfo(deviceInfoParam, null, Stream.of(1).collect(Collectors.toList()));
        for (GeneralDeviceDTO generalDeviceDTO : generalDeviceDTOList) {
            List<String> lineIndexes = generalDeviceDTO.getLineIndexes();
            if (CollectionUtils.isEmpty(lineIndexes)) {
                continue;
            }
            LineStatisticsTableVO lineStatisticsTableVO = new LineStatisticsTableVO();
            lineStatisticsTableVO.setId(generalDeviceDTO.getIndex());
            lineStatisticsTableVO.setName(generalDeviceDTO.getName());
            //组装父级数据树
            List<LineStatisticsTableVO> treeList = getTreeData(lineIndexes, deviceInfoParam);
            lineStatisticsTableVO.setChildren(treeList);
            lineStatisticsTableList.add(lineStatisticsTableVO);
        }
        return lineStatisticsTableList;
    }

    @Override
    public List<LineFlowMealDetailVO> getLineRunStatistics(DeviceInfoParam.BusinessParam deviceInfoParam) {
        List<LineFlowMealDetailVO> lineFlowMealDetailList = new ArrayList<>();
        List<GeneralDeviceDTO> generalDeviceDTOList = generalDeviceService.getDeviceInfo(deviceInfoParam, null, Stream.of(1).collect(Collectors.toList()));
        for (GeneralDeviceDTO generalDeviceDTO : generalDeviceDTOList) {
            List<String> lineIndexes = generalDeviceDTO.getLineIndexes();
            List<String> devIndexs = generalDeviceDTO.getDeviceIndexes();
            if (CollectionUtils.isEmpty(lineIndexes)) {
                continue;
            }
            LineFlowMealDetailVO lineFlowMealDetailVO = new LineFlowMealDetailVO();
            lineFlowMealDetailVO.setId(generalDeviceDTO.getIndex());
            lineFlowMealDetailVO.setName(generalDeviceDTO.getName());
            lineFlowMealDetailVO.setLevel(1);
            //组装父级数据树
            List<LineFlowMealDetailVO> treeList = getFlowTreeData(lineIndexes, devIndexs, deviceInfoParam);
            lineFlowMealDetailVO.setChildren(treeList);
            lineFlowMealDetailList.add(lineFlowMealDetailVO);
        }
        return lineFlowMealDetailList;
    }

    @Override
    public LineStaticsViewVO getLineStaticsView(String startTime, String endTime, String lineId) {
        //根据监测点id获取终端id
        String devIndex = lineMapper.getDevIndex(lineId);
        //获取在线率
        List<LineStaticsValueVO> onlineRateValue = getDevOnline(devIndex,startTime,endTime);
        //获取数据完整性
        List<LineStaticsValueVO> integrityValue = getInegrity(lineId,startTime,endTime);
        //获取流量占比
        List<LineStaticsValueVO> flowMealValue = new ArrayList<>();
        //组装
        LineStaticsViewVO lineStaticsViewVO = new LineStaticsViewVO();
        lineStaticsViewVO.setOnlineRateValue(onlineRateValue);
        lineStaticsViewVO.setIntegrityValue(integrityValue);
        lineStaticsViewVO.setFlowMealValue(flowMealValue);

        return lineStaticsViewVO;
    }

    @Override
    public List<Overlimit> getOverLimitByList(PollutionParamDTO pollutionParamDTO) {
        return overlimitMapper.selectBatchIds(pollutionParamDTO.getLineList());
    }

    /**
     * 获取父级每层数据
     */
    private List<LineFlowMealDetailVO> getFlowTreeData(List<String> lineIndexes, List<String> devIndexs, DeviceInfoParam.BusinessParam steadyParam) {
        //在线率
        List<LineInfluxDbOnlineVO> lineInfluxDbOnlineVO = getOnlineData(devIndexs, steadyParam);
        //数据完整性
        List<LineInfluxDbInegrityVO> lineInfluxDbInegrityVO = getInegrityData(lineIndexes, steadyParam);
        //监测点集合
        List<LineFlowMealDetailVO> monitorList = lineMapper.getLineRunStatistics(lineIndexes, DateUtil.beginOfDay(DateUtil.parse(steadyParam.getSearchBeginTime())), DateUtil.beginOfDay(DateUtil.parse(steadyParam.getSearchEndTime())));
        for (LineFlowMealDetailVO lineFlowMealDetailVO : monitorList) {
            for (LineInfluxDbInegrityVO lineInfluxDbInegrity : lineInfluxDbInegrityVO) {
                if (lineFlowMealDetailVO.getId().equals(lineInfluxDbInegrity.getLineId())) {
                    BigDecimal flow =new  BigDecimal(lineInfluxDbInegrity.getIntegrity().floatValue());
                    lineFlowMealDetailVO.setIntegrity(flow.setScale(2,  BigDecimal.ROUND_HALF_UP).floatValue());
                }
            }
        }
        //母线集合
        List<LineFlowMealDetailVO> busBarList = lineMapper.getFlowLineInfoByTableList(monitorList.stream().map(LineFlowMealDetailVO::getPid).distinct().collect(Collectors.toList()));
        //终端集合
        List<LineFlowMealDetailVO> deviceList = lineMapper.getFlowLineRunStatistics(busBarList.stream().map(LineFlowMealDetailVO::getPid).distinct().collect(Collectors.toList()), DateUtil.endOfDay(DateUtil.parse(steadyParam.getSearchBeginTime())), DateUtil.beginOfDay(DateUtil.parse(steadyParam.getSearchEndTime())));
        for (LineFlowMealDetailVO lineFlowMealDetailVO : deviceList) {
            System.out.println(lineFlowMealDetailVO.getId());
            Float staticsValue = getStatisValueFlow(lineFlowMealDetailVO.getId(),steadyParam);
            BigDecimal b  =   new  BigDecimal(staticsValue);
            float   f1   =  b.setScale(2,  BigDecimal.ROUND_HALF_UP).floatValue();
            lineFlowMealDetailVO.setStatisValue(f1);
            BigDecimal flow =new  BigDecimal(f1/lineFlowMealDetailVO.getFlowMeal()*100);
            //获取流量占比
            lineFlowMealDetailVO.setFlowProportion(flow.setScale(2,  BigDecimal.ROUND_HALF_UP).floatValue());

            for (LineInfluxDbOnlineVO lineInfluxDbOnline : lineInfluxDbOnlineVO) {
                if (lineFlowMealDetailVO.getId().equals(lineInfluxDbOnline.getDevIndex())) {
                    BigDecimal flowValue =new  BigDecimal(lineInfluxDbOnline.getOnlineRate().floatValue());
                    lineFlowMealDetailVO.setOnlineRate(flowValue.setScale(2,  BigDecimal.ROUND_HALF_UP).floatValue());
                }
            }
        }
        //变电站集合
        List<LineFlowMealDetailVO> substationList = lineMapper.getFlowLineInfoByTableList(deviceList.stream().map(LineFlowMealDetailVO::getPid).distinct().collect(Collectors.toList()));
        //供电公司集合
        List<LineFlowMealDetailVO> powerCompanyList = lineMapper.getFlowLineInfoByTableList(substationList.stream().map(LineFlowMealDetailVO::getPid).distinct().collect(Collectors.toList()));

        setFlowChildesList(substationList, deviceList);

        setFlowDeChildesList(deviceList, monitorList);

        powerCompanyList.stream().peek(item -> item.setChildren(getFlowChildCategoryList(item, substationList))).collect(Collectors.toList());

        return powerCompanyList;
    }

    private void setFlowDeChildesList(List<LineFlowMealDetailVO> item, List<LineFlowMealDetailVO> childes) {
        Map<String, List<LineFlowMealDetailVO>> groupLine;
        groupLine = childes.stream().collect(Collectors.groupingBy(steadyQualifyVO -> {
            String[] pid = steadyQualifyVO.getPids().split(",");
            List<String> value = new ArrayList<>();
            value.add(pid[LineBaseEnum.DEVICE_LEVEL.getCode()]);
            System.out.printf(steadyQualifyVO.getName());
            return pid[LineBaseEnum.DEVICE_LEVEL.getCode()];
        }));
        item.stream().peek(steadyQualifyVO -> {
            if (!CollectionUtils.isEmpty(groupLine.get(steadyQualifyVO.getId()))) {
                steadyQualifyVO.setChildren(groupLine.get(steadyQualifyVO.getId()));
            }
        }).collect(Collectors.toList());
    }

    private void setFlowChildesList(List<LineFlowMealDetailVO> item, List<LineFlowMealDetailVO> childes) {
        Map<String, List<LineFlowMealDetailVO>> 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()));
            }
        }).collect(Collectors.toList());
    }

    /**
     * 组装树层级
     */
    private List<LineFlowMealDetailVO> getFlowChildCategoryList(LineFlowMealDetailVO item, List<LineFlowMealDetailVO> child) {
        return child.stream().filter(allItem -> allItem.getPid().equals(item.getId())).collect(Collectors.toList());
    }

    /**
     * 获取父级每层数据
     */
    private List<LineStatisticsTableVO> getTreeData(List<String> lineIndexes, DeviceInfoParam.BusinessParam steadyParam) {
        //监测点集合
        List<LineStatisticsTableVO> monitorList = lineMapper.getLineStatisticsTableData(lineIndexes);
        //母线集合
        List<LineStatisticsTableVO> busBarList = lineMapper.getLineInfoByTableList(monitorList.stream().map(LineStatisticsTableVO::getPid).distinct().collect(Collectors.toList()));
        //终端集合
        List<LineStatisticsTableVO> deviceList = lineMapper.getLineInfoByTableList(busBarList.stream().map(LineStatisticsTableVO::getPid).distinct().collect(Collectors.toList()));
        //变电站集合
        List<LineStatisticsTableVO> substationList = lineMapper.getLineInfoByTableList(deviceList.stream().map(LineStatisticsTableVO::getPid).distinct().collect(Collectors.toList()));
        //供电公司集合
        List<LineStatisticsTableVO> powerCompanyList = lineMapper.getLineInfoByTableList(substationList.stream().map(LineStatisticsTableVO::getPid).distinct().collect(Collectors.toList()));

        setChildesList(substationList, monitorList);

        powerCompanyList.stream().peek(item -> item.setChildren(getChildCategoryList(item, substationList))).collect(Collectors.toList());

        return powerCompanyList;
    }

    private void setChildesList(List<LineStatisticsTableVO> item, List<LineStatisticsTableVO> childes) {
        Map<String, List<LineStatisticsTableVO>> 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()));
            }
        }).collect(Collectors.toList());
    }

    /**
     * 组装树层级
     */
    private List<LineStatisticsTableVO> getChildCategoryList(LineStatisticsTableVO item, List<LineStatisticsTableVO> child) {
        return child.stream().filter(allItem -> allItem.getPid().equals(item.getId())).collect(Collectors.toList());
    }

    public List<LineInfluxDbOnlineVO> getOnlineData(List<String> devIndexs, DeviceInfoParam.BusinessParam deviceInfoParam) {
        //组装sql语句
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("time >= '").append(DateUtil.beginOfDay(DateUtil.parse(deviceInfoParam.getSearchBeginTime()))).append("' and ").append("time <= '").append(DateUtil.endOfDay(DateUtil.parse(deviceInfoParam.getSearchEndTime()))).append("' and ");

        for (int i = 0; i < devIndexs.size(); i++) {
            if (devIndexs.size() - i != 1) {
                stringBuilder.append("dev_index ='").append(devIndexs.get(i)).append("' or ");
            } else {
                stringBuilder.append("dev_index ='").append(devIndexs.get(i)).append("' ");
            }
        }
        String sql = "select sum(onlinemin)/(sum(onlinemin) +sum(offlinemin))*100 as onlinerate from pqs_onlinerate  where " + stringBuilder.toString() + "group by dev_index";
        //获取暂降事件
        QueryResult result = influxDbUtils.query(sql);
        InfluxDBResultMapper influxDBResultMapper = new InfluxDBResultMapper();
        List<LineInfluxDbOnlineVO> eventDetailList = influxDBResultMapper.toPOJO(result, LineInfluxDbOnlineVO.class);
        return eventDetailList;
    }

    public List<LineInfluxDbInegrityVO> getInegrityData(List<String> lineIndexes, DeviceInfoParam.BusinessParam deviceInfoParam) {
        //组装sql语句
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("time >= '").append(DateUtil.beginOfDay(DateUtil.parse(deviceInfoParam.getSearchBeginTime()))).append("' and ").append("time <= '").append(DateUtil.endOfDay(DateUtil.parse(deviceInfoParam.getSearchEndTime()))).append("' and ");
        for (int i = 0; i < lineIndexes.size(); i++) {
            if (lineIndexes.size() - i != 1) {
                stringBuilder.append("line_id ='").append(lineIndexes.get(i)).append("' or ");
            } else {
                stringBuilder.append("line_id ='").append(lineIndexes.get(i)).append("' ");
            }
        }

        String sql = "select sum(real)/(sum(due))*100 as integrity from pqs_integrity where " + stringBuilder.toString() + "group by line_id";
        //获取暂降事件
        QueryResult result = influxDbUtils.query(sql);
        InfluxDBResultMapper influxDBResultMapper = new InfluxDBResultMapper();
        List<LineInfluxDbInegrityVO> eventDetailList = influxDBResultMapper.toPOJO(result, LineInfluxDbInegrityVO.class);
        return eventDetailList;
    }

    @SneakyThrows
    public List<LineStaticsValueVO> getDevOnline(String devIndex, String startTime, String endTime) {
        //组装sql语句
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("time >= '").append(DateUtil.beginOfDay(DateUtil.parse(startTime))).append("' and ").append("time <= '").append(DateUtil.endOfDay(DateUtil.parse(endTime))).append("' and ");
        stringBuilder.append("dev_index ='").append(devIndex).append("' ");

        String sql = "select time,onlinemin/(onlinemin+offlinemin)*100 as value from pqs_onlinerate where " + stringBuilder.toString() + "group by dev_index tz('Asia/Shanghai')";
        //获取在线率
        List<LineStaticsValueVO> lineInfluxDbOnline = new ArrayList<>();
        QueryResult result = influxDbUtils.query(sql);
        List<QueryResult.Series> list = result.getResults().get(0).getSeries();
        if (!CollectionUtils.isEmpty(list)) {
            List<List<Object>> listData = list.get(0).getValues();
            for (int i = 0; i < listData.size(); i++) {
                LineStaticsValueVO lineStaticsValueVO =new LineStaticsValueVO();
                List<Object> objectList = listData.get(i);
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                lineStaticsValueVO.setTime(formatter.parse(objectList.get(0).toString()).toString());
                lineStaticsValueVO.setValue((Double) objectList.get(1));
                lineInfluxDbOnline.add(lineStaticsValueVO);
            }
        }
        return lineInfluxDbOnline;
    }

    @SneakyThrows
    public List<LineStaticsValueVO> getInegrity(String lineIndex, String startTime, String endTime) {
        //组装sql语句
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("time >= '").append(DateUtil.beginOfDay(DateUtil.parse(startTime))).append("' and ").append("time <= '").append(DateUtil.endOfDay(DateUtil.parse(endTime))).append("' and ");
        stringBuilder.append("line_id ='").append(lineIndex).append("' ");
        String sql = "select time,(real/due)*100 as value from pqs_integrity where " + stringBuilder.toString() + " group by line_id tz('Asia/Shanghai')";
        //获取数据完整性
        List<LineStaticsValueVO> lineInfluxDbInegrity = new ArrayList<>();
        QueryResult result = influxDbUtils.query(sql);
        List<QueryResult.Series> list = result.getResults().get(0).getSeries();
        if (!CollectionUtils.isEmpty(list)) {
            List<List<Object>> listData = list.get(0).getValues();
            for (int i = 0; i < listData.size(); i++) {
                LineStaticsValueVO lineStaticsValueVO =new LineStaticsValueVO();
                List<Object> objectList = listData.get(i);
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                lineStaticsValueVO.setTime(formatter.parse(objectList.get(0).toString()).toString());
                lineStaticsValueVO.setValue((Double) objectList.get(1));
                lineInfluxDbInegrity.add(lineStaticsValueVO);
            }
        }
        return lineInfluxDbInegrity;
    }

    @SneakyThrows
    public Float getStatisValueFlow(String lineIndex,DeviceInfoParam.BusinessParam steadyParam) {
        //组装sql语句
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("time >= '").append(DateUtil.beginOfDay(DateUtil.parse(steadyParam.getSearchBeginTime()))).append("' and ").append("time <= '").append(DateUtil.endOfDay(DateUtil.parse(steadyParam.getSearchEndTime()))).append("' and ");
        stringBuilder.append("line_id ='").append(lineIndex).append("' ");
        String sql = "select sum(statis_value)/1024/1024 as statisValue from pqs_statis_flow where " + stringBuilder.toString() + " group by line_id tz('Asia/Shanghai')";
        //获取统计流量
        Float staticsValue = 0f;
        QueryResult result = influxDbUtils.query(sql);
        List<QueryResult.Series> list = result.getResults().get(0).getSeries();
        if (!CollectionUtils.isEmpty(list)) {
            List<List<Object>> listData = list.get(0).getValues();
            List<Object> objectList = listData.get(0);
            staticsValue = ((Double)objectList.get(1)).floatValue();
        }else {
            staticsValue = 0f;
        }
        return staticsValue;
    }

}
