package com.njcn.device.pq.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.enums.common.DataStateEnum;
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.biz.enums.DeviceResponseEnum;
import com.njcn.device.biz.pojo.po.Overlimit;
import com.njcn.device.pq.enums.LineBaseEnum;
import com.njcn.device.pq.pojo.dto.GeneralDeviceDTO;
import com.njcn.device.pq.pojo.dto.PollutionLineDTO;
import com.njcn.device.pq.pojo.dto.PollutionParamDTO;
import com.njcn.device.pq.pojo.dto.PollutionSubstationDTO;
import com.njcn.device.pq.pojo.param.DeviceInfoParam;
import com.njcn.device.pq.pojo.param.PqsParam;
import com.njcn.device.pq.pojo.po.*;
import com.njcn.device.pq.pojo.vo.*;
import com.njcn.device.pq.mapper.*;
import com.njcn.device.pq.service.LineService;
import com.njcn.influx.constant.InfluxDbSqlConstant;
import com.njcn.influx.imapper.PqsCommunicateMapper;
import com.njcn.influx.pojo.po.PqsCommunicate;
import com.njcn.influx.query.InfluxQueryWrapper;
import com.njcn.system.api.AreaFeignClient;
import com.njcn.system.api.DicDataFeignClient;
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.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.time.Instant;
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 GeneralDeviceService generalDeviceService;

    private final LineMapper lineMapper;

    private final TopMsgMapper topMsgMapper;

   private final PqsCommunicateMapper pqsCommunicateMapper;

    @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());
        lineDetailDataVO.setTimeInterval (lineDetail.getTimeInterval ());
        lineDetailDataVO.setOwner(lineDetail.getOwner());
        lineDetailDataVO.setOwnerDuty(lineDetail.getOwnerDuty());
        lineDetailDataVO.setOwnerTel(lineDetail.getOwnerTel());
        lineDetailDataVO.setWiringDiagram(lineDetail.getWiringDiagram());
        lineDetailDataVO.setPtPhaseType(lineDetail.getPtPhaseType());
        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) {
        String devId = lineMapper.getDevIndex(id);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<PqsCommunicate> communicateList = getCommunicate(devId, searchBeginTime, searchEndTime);
        CommunicateVO communicateVOList = new CommunicateVO();
        List<String> updateTime = new ArrayList<>();
        List<Integer> comType = new ArrayList<>();
        //开始时间
        Boolean beginFly =false;
        if(CollUtil.isNotEmpty(communicateList)){
            if(!communicateList.get(0).getTime().equals(DateUtil.beginOfDay(DateUtil.parse(searchBeginTime)).toInstant())){
                beginFly =true;
            }
        }else{
            beginFly =true;
        }

        if(beginFly){
            Instant instant = DateUtil.beginOfDay(DateUtil.parse(searchBeginTime)).toInstant();
            Long time = instant.toEpochMilli();
            String timeText = df.format(time);
            updateTime.add(timeText);
            if(CollUtil.isNotEmpty(communicateList)){
                if(communicateList.get(0).getType()==0){
                    comType.add(1);
                }else{
                    comType.add(0);
                }
            }else{
                comType.add(1);
            }

        }
        for (PqsCommunicate communicate : communicateList) {
            //转化时间
            Instant now = communicate.getTime();
            Long time = now.toEpochMilli();
            String timeText = df.format(time);
            updateTime.add(timeText);
            comType.add(communicate.getType());
        }
        //拼接最后时间
        SimpleDateFormat times = new SimpleDateFormat("HH:mm:ss");
        DateTime date = DateTime.now();
        String format = times.format(date);
        Instant endTime = DateUtil.parse(searchEndTime + " " + format).toInstant();

        Boolean endFly =false;
        if(CollUtil.isNotEmpty(communicateList)){
            if(!communicateList.get(communicateList.size()-1).getTime().equals(endTime)){
                endFly =true;
            }
        }else{
            endFly =true;
        }
        if(endFly){
            Long time = endTime.toEpochMilli();
            String timeText = df.format(time);
            updateTime.add(timeText);
            if(CollUtil.isNotEmpty(communicateList)){
                comType.add(communicateList.get(communicateList.size()-1).getType());
            }else{
                comType.add(1);
            }
        }
        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去获取省份信息
            LineDistributionVO lineDistributionVO = new LineDistributionVO();
            lineDistributionVO.setName(generalDeviceDTO.getName());
            lineDistributionVO.setValue(generalDeviceDTO.getLineIndexes().size());
            lineDistributionVOList.add(lineDistributionVO);
        }
        return  lineDistributionVOList;
    }



    @Override
    public List<LineStatisticsDetailVO> getLineStatisticsDetail(DeviceInfoParam.BusinessParam deviceInfoParam) {
        List<LineStatisticsDetailVO> lineStatisticsDetailList = new ArrayList<>();
        int deviceAddNumTail=0,deviceNumTail = 0, 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();
            // 区域id
            lineStatisticsDetail.setId(generalDeviceDTO.getIndex());
            // 区域/电压等级/干扰源类型/终端厂家
            lineStatisticsDetail.setAreaName(generalDeviceDTO.getName());
            // 区域监测点总数
            lineStatisticsDetail.setLineNum(generalDeviceDTO.getLineIndexes().size());
            // 区域装置总数
            lineStatisticsDetail.setDeviceNum(generalDeviceDTO.getDeviceIndexes().size());
            // 总计装置总数
            deviceNumTail += generalDeviceDTO.getDeviceIndexes().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);

                // 获取装置新增数量
                QueryWrapper<Line> deviceQueryWrapper = new QueryWrapper<>();
                deviceQueryWrapper.in("pq_line.id", generalDeviceDTO.getDeviceIndexes());
                deviceQueryWrapper.between("pq_line.Create_Time",
                        DateUtil.beginOfDay(DateUtil.parse(deviceInfoParam.getSearchBeginTime())),
                        DateUtil.endOfDay(DateUtil.parse(deviceInfoParam.getSearchEndTime())));
                int deviceAddNum = lineMapper.selectCount(deviceQueryWrapper);
                deviceAddNumTail += deviceAddNum;
                lineStatisticsDetail.setAddDeviceNum(deviceAddNum);

                LineStateVO lineStateVO;
                //获取状态
               // lineStateVO = lineMapper.getLineStatisticsDetail(generalDeviceDTO.getLineIndexes());
                lineStateVO = lineMapper.getDeviceStatus(generalDeviceDTO.getDeviceIndexes());
                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);
                lineStatisticsDetail.setAddDeviceNum(0);
            }
            lineStatisticsDetailList.add(lineStatisticsDetail);
        }
        LineStatisticsDetailVO lineStatisticsDetailVO = new LineStatisticsDetailVO();
        lineStatisticsDetailVO.setAreaName("总计");
        lineStatisticsDetailVO.setAddDeviceNum(deviceAddNumTail);
        lineStatisticsDetailVO.setDeviceNum(deviceNumTail);
        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 Page<LineFlowMealDetailVO> getNewDeviceRunStatistics(PqsParam deviceInfoParam) {
        List<String> deviceIndexes = new ArrayList<>();
        List<GeneralDeviceDTO> deviceInfoList = generalDeviceService.getDeviceInfo(deviceInfoParam, null, Stream.of(1).collect(Collectors.toList()));
        deviceInfoList.stream().map(GeneralDeviceDTO::getDeviceIndexes).forEach(deviceIndexes::addAll);
        Page<LineFlowMealDetailVO> page = lineMapper.getNewDeviceRunStatistics(
                new Page(deviceInfoParam.getPageNum(), deviceInfoParam.getPageSize()),
                deviceIndexes,
                DateUtil.beginOfDay(DateUtil.parse(deviceInfoParam.getSearchBeginTime())),
                DateUtil.endOfDay(DateUtil.parse(deviceInfoParam.getSearchEndTime())));
        return page;
    }

    @Override
    public Page<TopMsgPO> dailyDeviceAbnormalStatistics(PqsParam param) {
        Page topMsg = topMsgMapper.dailyDeviceAbnormalStatistics(
                new Page(param.getPageNum(), param.getPageSize()),
                param.getLineGrade(),
                DateUtil.beginOfDay(DateUtil.parse(param.getSearchBeginTime())),
                DateUtil.endOfDay(DateUtil.parse(param.getSearchEndTime())));
        return topMsg;
    }

    @Override
    public List<TopMsgPO> dailyDeviceAbnormal(DeviceInfoParam.BusinessParam param) {
        List<TopMsgPO> topMsgDetails = topMsgMapper.dailyDeviceAbnormal(
                param.getLineGrade(),
                DateUtil.beginOfDay(DateUtil.parse(param.getSearchBeginTime())));
        return topMsgDetails;
    }

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

    /**
     * 获取父级每层数据
     */
    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<PqsCommunicate> getCommunicate(String devId, String startTime, String endTime) {
        InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(PqsCommunicate.class);
        influxQueryWrapper.between(InfluxDbSqlConstant.TIME,DateUtil.beginOfDay(DateUtil.parse(startTime)),DateUtil.beginOfDay(DateUtil.parse(endTime)))
                .eq(PqsCommunicate::getDevId,devId);
        return pqsCommunicateMapper.selectByQueryWrapper(influxQueryWrapper);
    }

    @Override
    public List<AreaLineInfoVO> getBaseLineAreaInfo(List<String> lineIndex, String searchValue, Integer comFlag) {
        return this.baseMapper.getBaseLineAreaInfo(lineIndex, searchValue, comFlag);
    }

    @Override
    public List<Line> getBaseLineList(List<String> lineIndex) {
        LambdaQueryWrapper<Line> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Line::getState, DataStateEnum.ENABLE.getCode()).in(Line::getId, lineIndex);
        return this.list(lambdaQueryWrapper);
    }


    /**
     * @Description: 通过部门索引查询其下监测点数
     * @Param: [deviceInfoParam] 监测点查询条件
    * @return: java.util.List<com.njcn.device.pq.pojo.vo.DeptLineCountVO>
    * @Author: clam
    * @Date: 2022/10/10
    */
    @Override
    public  List<DeptLineCountVO> getDeptLineCount(DeviceInfoParam deviceInfoParam) {
        List<DeptLineCountVO> deptLineCountVOList = new ArrayList<> ();
        //获取所有监测点
        List<GeneralDeviceDTO> generalDeviceDTOList = generalDeviceService.getDeviceInfoAsDept(deviceInfoParam, null, Stream.of(1).collect(Collectors.toList()));
        for (GeneralDeviceDTO generalDeviceDTO : generalDeviceDTOList) {
            //根据部门id去获取省份信息
            DeptLineCountVO deptLineCountVO = new DeptLineCountVO();
            deptLineCountVO.setIndex (generalDeviceDTO.getIndex ());
            deptLineCountVO.setName(generalDeviceDTO.getName());
            deptLineCountVO.setNumber (generalDeviceDTO.getLineIndexes().size());
            deptLineCountVOList.add(deptLineCountVO);
        }

/*        Map<String, Integer> collect = deptLineCountVOList.stream ( ).collect (Collectors.groupingBy (DeptLineCountVO::getName, Collectors.summingInt (DeptLineCountVO::getNumber)));
        List<DeptLineCountVO> result = new ArrayList<DeptLineCountVO>();

        for (Map.Entry<String, Integer> entry : collect.entrySet()) {
            DeptLineCountVO deptLineCountVO = new DeptLineCountVO();
            deptLineCountVO.setName (entry.getKey());
            deptLineCountVO.setNumber (entry.getValue());
            result.add(deptLineCountVO);
        }*/
        deptLineCountVOList = deptLineCountVOList.stream ().sorted (Comparator.comparing (DeptLineCountVO::getNumber,Comparator.reverseOrder())).collect(Collectors.toList());
        return deptLineCountVOList;
    }

    /**
     * @param devDataType
     * @Description: 获取变电站和监测点的关系（分稳态暂态）
     * @Param: [devDataType]
     * @return: java.util.Map<java.lang.String, java.util.List < java.lang.String>>
     * @Author: clam
     * @Date: 2022/10/20
     */
    @Override
    public Map<String, List<String>> getLineBySubstationRelation(Integer devDataType) {

        Map<String, List<String>> map = new HashMap<> ();

        List<Line> deptLines = lineMapper.getLineBySubstationRelation(devDataType);
        Map<String, List<String>> collect = deptLines.stream ( ).collect (Collectors.groupingBy (Line::getPids, Collectors.mapping (Line::getId,Collectors.toList ())));

        return collect;
    }

    @Override
    public List<LineDetailDataVO> getLineDetailList(List<String> lineIds){

        return lineDetailMapper.getLineDetailInfo(lineIds);
    }

    /**
     * @param subIndex
     * @Description: 获取变电站下终端数
     * @Param: [subIndex]
     * @return: java.lang.Integer
     * @Author: clam
     * @Date: 2022/11/9
     */
    @Override
    public Integer getDeviceCountBySubstation(String subIndex) {

        Integer count = lineDetailMapper.getDeviceCountBySubstation(subIndex);

        return count;
    }

    /**
     * @param subIndex
     * @Description: 获取变电站下监测点数
     * @Param: [subIndex]
     * @return: java.lang.Integer
     * @Author: clam
     * @Date: 2022/11/9
     */
    @Override
    public Integer getLineCountBySubstation(String subIndex) {

        Integer count = lineDetailMapper.getLineCountBySubstation(subIndex);

        return count;
    }



    /**
     * 根据用户选择的时间区间返回月份日期
     */
    @SneakyThrows
    private List<String> getIntervalTime(String startTime, String endTime) {
        List<String> times = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Date start = sdf.parse(startTime);
        Date end = sdf.parse(endTime);
        // 同月
        if (start.getTime() == end.getTime()) {
            String time = startTime.substring(0, 7);
            times.add(time);
        } else if (start.getYear() == end.getYear()) {
            // 同年
            int startM = start.getMonth() + 1;
            int endM = end.getMonth() + 1;
            int temp = endM - startM;
            for (int i = 0; i <= temp; i++) {
                String time = start.getYear() + 1900 + "";
                int month = startM + i;
                if (month < 10) {
                    time = time + "-0" + month;
                } else {
                    time = time + "-" + month;
                }
                times.add(time);
            }
        } else {
            // 不同年!!!!这里忽略了年份之间跨年的情况
            int startY = start.getYear() + 1900;
            int startM = start.getMonth() + 1;
            int endY = end.getYear() + 1900;
            int endM = end.getMonth() + 1;
            int tempS = 12 - startM;
            // 连续的年份
            if (endY - startY == 1) {
                // 第一年的时间获取
                for (int i = 0; i <= tempS; i++) {
                    int month = startM + i;
                    String time = startY + "-";
                    if (month < 10) {
                        time = time + "0" + month;
                    } else {
                        time = time + month;
                    }
                    times.add(time);
                }
                // 第二年的时间获取

                for (int i = 1; i <= endM; i++) {
                    String time = endY + "-";
                    if (i < 10) {
                        time = time + "0" + i;
                    } else {
                        time = time + i;
                    }
                    times.add(time);
                }
            } else {
                // 不连续的年份
                // 第一年的时间获取
                for (int i = 0; i <= tempS; i++) {
                    int month = startM + i;
                    String time = startY + "-";
                    if (month < 10) {
                        time = time + "0" + month;
                    } else {
                        time = time + month;
                    }
                    times.add(time);
                }
                int tempY = endY - startY;
                // 中间年份的时间
                for (int i = 1; i < tempY; i++) {
                    for (int j = 1; j <= 12; j++) {
                        String time = startY + i + "-";
                        if (j < 10) {
                            time = time + "0" + j;
                        } else {
                            time = time + j;
                        }
                        times.add(time);
                    }
                }
                // 最后一年的时间获取
                for (int i = 1; i <= endM; i++) {
                    String time = endY + "-";
                    if (i < 10) {
                        time = time + "0" + i;
                    } else {
                        time = time + i;
                    }
                    times.add(time);
                }
            }

        }
        return times;
    }
}
