package com.njcn.product.event.transientes.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.*;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.beust.ah.A;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.product.event.config.RedisUtil;
import com.njcn.product.event.devcie.mapper.*;
import com.njcn.product.event.devcie.pojo.dto.*;
import com.njcn.product.event.devcie.pojo.po.*;
import com.njcn.product.event.transientes.mapper.*;
import com.njcn.product.event.transientes.pojo.DicTreeEnum;
import com.njcn.product.event.transientes.pojo.enums.DicTypeEnum;
import com.njcn.product.event.transientes.pojo.param.LargeScreenCountParam;
import com.njcn.product.event.transientes.pojo.param.MessageEventFeedbackParam;
import com.njcn.product.event.transientes.pojo.po.PqsDepts;
import com.njcn.product.event.transientes.pojo.po.MessageEventFeedback;
import com.njcn.product.event.transientes.pojo.po.MsgEventInfo;
import com.njcn.product.event.transientes.pojo.po.PqsEventdetail;
import com.njcn.product.event.transientes.pojo.po.*;
import com.njcn.product.event.transientes.pojo.vo.*;
import com.njcn.product.event.devcie.service.*;
import com.njcn.product.event.transientes.service.*;
import com.njcn.product.event.devcie.service.PqsDeptslineService;
import com.njcn.web.factory.PageFactory;
import com.njcn.web.utils.ExcelUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Description:
 * Date: 2025/06/19  下午 3:06【需求编号】
 *
 * @author clam
 * @version V1.0.0
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class LargeScreenCountServiceImpl implements LargeScreenCountService {

    private final PqsDeptslineService pqsDeptslineService;
    private final PqsDeptsService pqsDeptsService;
    private final PqLineService pqLineService;
    private final PqSubstationService pqSubstationService;
    private final PqDeviceService pqDeviceService;
    private final PqsEventdetailService pqsEventdetailService;
    private final PqLineMapper pqLineMapper;
    private final MsgEventInfoService msgEventInfoService;
    private final MessageEventFeedbackService messageEventFeedbackService;
    private final CommGeneralService commGeneralService;
    private final MsgEventConfigService msgEventConfigService;
    private final PqsUsersetService pqsUsersetService;
    private final PqsUserService pqsUserService;
    private final PqLinedetailMapper pqLinedetailMapper;
    private final RedisUtil redisUtil;
    private final PqsOnlinerateService pqsOnlinerateService;

    private final PqsIntegrityMapper pqsIntegrityMapper;

    private final PqUserLedgerMapper pqUserLedgerMapper;

    private final PqUserLineAssMapper pqUserLineAssMapper;

    private final PqsStationMapMapper pqsStationMapMapper;

    private final PqsDicDataMapper pqsDicDataMapper;

    private final PqGdCompanyMapper pqGdCompanyMapper;

    private final PqSubstationMapper pqSubstationMapper;

    private final PqDeviceDetailMapper pqDeviceDetailMapper;
    private final PqsDicTreeMapper pqsDicTreeMapper;
    private final PqsDicTypeMapper pqsDicTypeMapper;

    @Value("${SYS_TYPE_ZT}")
    private String sysTypeZt;
    private final static String NAME_KEY = "LineCache:";


    private List<Integer> lineIds = new ArrayList<>();


    @Override
    public void initLedger(LargeScreenCountParam largeScreenCountParam) {
        lineIds = commGeneralService.getLineIdsByDept(largeScreenCountParam);
    }

    @Override
    public LedgerCountVO scaleStatistics(LargeScreenCountParam largeScreenCountParam) {
        LedgerCountVO ledgerCountVO = new LedgerCountVO();
        //根据用户获取当前部门及子部门id
        //lineIds = commGeneralService.getLineIdsByDept(largeScreenCountParam);
        if (CollectionUtils.isEmpty(lineIds)) {
            throw new BusinessException("部门下暂无监测点");
        }
        List<PqLine> pqLineList = new ArrayList<>();
        if (lineIds.size() > 1000) {
            List<List<Integer>> listIds = CollUtil.split(lineIds, 1000);
            for (List<Integer> itemIds : listIds) {
                List<PqLine> temp = pqLineService.lambdaQuery().in(PqLine::getLineIndex, itemIds).list();
                pqLineList.addAll(temp);
            }
        } else {
            List<PqLine> temp = pqLineService.lambdaQuery().in(PqLine::getLineIndex, lineIds).list();
            pqLineList.addAll(temp);
        }
        //统计总数
        List<Integer> allLineIds = pqLineList.stream().map(PqLine::getLineIndex).collect(Collectors.toList());
        List<Integer> allSubList = pqLineList.stream().map(PqLine::getSubIndex).distinct().collect(Collectors.toList());
        long allSubCount = allSubList.stream().count();
        List<Integer> devList = pqLineList.stream().map(PqLine::getDevIndex).distinct().collect(Collectors.toList());
        long allDevCount = devList.stream().count();

        long allLineCount = pqLineList.stream().map(PqLine::getLineIndex).distinct().count();
        //在运总数
        List<PqDevice> list = pqDeviceService.lambdaQuery().in(PqDevice::getDevIndex, devList).eq(PqDevice::getDevflag, 0).list();
        List<Integer> runDevList = list.stream().map(PqDevice::getDevIndex).collect(Collectors.toList());
        long runDevCount = runDevList.stream().count();
        List<Integer> runSubList = list.stream().map(PqDevice::getSubIndex).distinct().collect(Collectors.toList());
        long runSubCount = runSubList.stream().count();
        List<LedgerBaseInfoDTO> ledgerBaseInfoDTOS = pqLineService.getBaseLineInfo(allLineIds);
        List<Integer> runLineList = ledgerBaseInfoDTOS.stream().filter(temp -> Objects.equals(temp.getRunFlag(), 1)).map(LedgerBaseInfoDTO::getLineId).collect(Collectors.toList());

        long runLineCount = runLineList.stream().count();


        ledgerCountVO.setAllSubCount(allSubCount);
        ledgerCountVO.setAllDevCount(allDevCount);
        ledgerCountVO.setAllLineCount(allLineCount);
        ledgerCountVO.setRunDevCount(runDevCount);
        ledgerCountVO.setRunSubCount(runSubCount);
        ledgerCountVO.setRunLineCount(runLineCount);

        ledgerBaseInfoDTOS.stream().forEach(temp -> temp.setRunFlag(runLineList.contains(temp.getLineId()) ? 1 : 0));
        ledgerCountVO.setAllLineList(ledgerBaseInfoDTOS);
        List<DeviceDTO> deviceDTOS = pqDeviceService.queryListByIds(devList);
        deviceDTOS = deviceDTOS.stream().distinct().collect(Collectors.toList());
        deviceDTOS.forEach(temp -> temp.setRunFlag(runDevList.contains(temp.getDevId()) ? 1 : 0));
        ledgerCountVO.setAllDevList(deviceDTOS);
        List<SubstationDTO> substationDTOS = pqSubstationService.queryListByIds(allSubList);
        substationDTOS.forEach(temp -> temp.setRunFlag(runSubList.contains(temp.getStationId()) ? 1 : 0));
        ledgerCountVO.setAllSubList(substationDTOS);
        return ledgerCountVO;
    }

    @Override
    public AlarmAnalysisVO alarmAnalysis(LargeScreenCountParam largeScreenCountParam) {
        AlarmAnalysisVO alarmAnalysisVO = new AlarmAnalysisVO();
        //起始时间
        LocalDateTime startTime;
        //结束时间
        LocalDateTime endTime;
        if (largeScreenCountParam.getType() == 3) {
            //起始时间
            startTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.beginOfMonth(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER);
            //结束时间
            endTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.endOfMonth(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER);
        } else if (largeScreenCountParam.getType() == 4) {
            //起始时间
            startTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.beginOfWeek(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER);
            //结束时间
            endTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.endOfWeek(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER);
        } else {
            throw new BusinessException("统计类型有误类型");
        }

        //根据用户获取当前部门及子部门id

        if (CollectionUtils.isEmpty(lineIds)) {
            throw new BusinessException("部门下暂无监测点");

        }
        List<PqsEventdetail> eventdetails = new ArrayList<>();
        if (lineIds.size() > 1000) {
            List<List<Integer>> listIds = CollUtil.split(lineIds, 1000);
            for (List<Integer> itemIds : listIds) {
                List<PqsEventdetail> temp = pqsEventdetailService.lambdaQuery()
                        .between(PqsEventdetail::getTimeid, startTime, endTime)
                        .in(PqsEventdetail::getWavetype, msgEventConfigService.getEventType())
                        .le(PqsEventdetail::getEventvalue, msgEventConfigService.getEventValue())
                        .gt(PqsEventdetail::getPersisttime, msgEventConfigService.getEventDuration())
                        .in(PqsEventdetail::getLineid, listIds)
                        .orderByDesc(PqsEventdetail::getTimeid).list();
                eventdetails.addAll(temp);
            }
        } else {
            List<PqsEventdetail> temp = pqsEventdetailService.lambdaQuery()
                    .between(PqsEventdetail::getTimeid, startTime, endTime)
                    .in(PqsEventdetail::getWavetype, msgEventConfigService.getEventType())
                    .le(PqsEventdetail::getEventvalue, msgEventConfigService.getEventValue())
                    .gt(PqsEventdetail::getPersisttime, msgEventConfigService.getEventDuration())
                    .in(PqsEventdetail::getLineid, lineIds)
                    .orderByDesc(PqsEventdetail::getTimeid).list();
            eventdetails.addAll(temp);
        }

        Integer eventCount = eventdetails.size();
        // 告警
        List<PqsEventdetail> aLarmEvent = eventdetails.stream().filter(temp -> temp.getEventvalue() < 0.5).collect(Collectors.toList());
        // 预警
        List<PqsEventdetail> warnEvent = eventdetails.stream().filter(temp -> temp.getEventvalue() >= 0.5 && temp.getEventvalue() < 0.9).collect(Collectors.toList());
        List<String> eventIds = eventdetails.stream().map(PqsEventdetail::getEventdetailIndex).collect(Collectors.toList());
        //通知

        List<MsgEventInfo> msgEventInfoList = msgEventInfoService.getMsgByIds(eventIds);
        msgEventInfoList = msgEventInfoList.stream().sorted(Comparator.comparing(MsgEventInfo::getSendTime, Comparator.reverseOrder())).collect(Collectors.toList());


        List<PqsEventdetail> lookALarmEvent = aLarmEvent.stream().filter(temp -> Objects.equals(temp.getLookFlag(), 1)).collect(Collectors.toList());
        List<PqsEventdetail> lookWarnEvent = warnEvent.stream().filter(temp -> Objects.equals(temp.getLookFlag(), 1)).collect(Collectors.toList());
        List<MsgEventInfo> handleMsg = msgEventInfoList.stream().filter(temp -> Objects.equals(temp.getIsHandle(), 1)).collect(Collectors.toList());

        Integer aLarmCount = aLarmEvent.size();
        Integer warnCount = warnEvent.size();
        Integer noticeCount = msgEventInfoList.size();
        Integer lookALarmCount = lookALarmEvent.size();
        Integer lookWarnCount = lookWarnEvent.size();
        Integer lookNoticeCount = handleMsg.size();

        alarmAnalysisVO.setEventCount(eventCount);
        alarmAnalysisVO.setALarmCount(aLarmCount);
        alarmAnalysisVO.setWarnCount(warnCount);
        alarmAnalysisVO.setNoticeCount(noticeCount);
        alarmAnalysisVO.setLookALarmCount(lookALarmCount);
        alarmAnalysisVO.setLookWarnCount(lookWarnCount);
        alarmAnalysisVO.setLookNoticeCount(lookNoticeCount);

//
//        alarmAnalysisVO.setEventdetails(change(eventdetails,msgEventInfoList));
//        alarmAnalysisVO.setALarmEvent(change(aLarmEvent,msgEventInfoList));
//        alarmAnalysisVO.setWarnEvent(change(warnEvent,msgEventInfoList));
//        alarmAnalysisVO.setNoticeEvent(msgEventInfoList);
//        alarmAnalysisVO.setLookALarmEvent(change(lookALarmEvent,msgEventInfoList));
//        alarmAnalysisVO.setLookWarnEvent(change(lookWarnEvent,msgEventInfoList));
//        alarmAnalysisVO.setLookNoticeEvent(handleMsg);


        return alarmAnalysisVO;
    }

    @Override
    public List<EventTrendVO> eventTrend(LargeScreenCountParam largeScreenCountParam) {
        List<EventTrendVO> eventTrendVOList = new ArrayList<>();
        //起始时间
        LocalDateTime startTime;
        //结束时间
        LocalDateTime endTime;
        if (largeScreenCountParam.getType() == 3) {
            //起始时间
            startTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.beginOfMonth(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER);
            //结束时间
            endTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.endOfMonth(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER);
        } else if (largeScreenCountParam.getType() == 4) {
            //起始时间
            startTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.beginOfWeek(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER);
            //结束时间
            endTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.endOfWeek(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER);
        } else {
            throw new BusinessException("统计类型有误类型");
        }
        // List<String> deptAndChildren = pqsDeptsService.findDeptAndChildren(largeScreenCountParam.getDeptId());
        //获取对应监测点id
        //List<PqsDeptsline> deptslines = pqsDeptslineService.lambdaQuery().in(PqsDeptsline::getDeptsIndex, deptAndChildren).eq(PqsDeptsline::getSystype, sysTypeZt).list();
        //List<Integer> deptslineIds = deptslines.stream().map(PqsDeptsline::getLineIndex).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(lineIds)) {
            throw new BusinessException("部门下暂无监测点");

        }
        LocalDate startDate = LocalDate.parse(DateUtil.format(startTime, DatePattern.NORM_DATE_PATTERN));
        LocalDate endDate = LocalDate.parse(DateUtil.format(endTime, DatePattern.NORM_DATE_PATTERN));
        List<PqsEventdetail> eventdetails = new ArrayList<>();
        if (lineIds.size() > 1000) {
            List<List<Integer>> listIds = CollUtil.split(lineIds, 1000);
            for (List<Integer> itemIds : listIds) {
                List<PqsEventdetail> temp = pqsEventdetailService.lambdaQuery()
                        .between(PqsEventdetail::getTimeid, startTime, endTime)
                        .in(PqsEventdetail::getWavetype, msgEventConfigService.getEventType())
                        .le(PqsEventdetail::getEventvalue, msgEventConfigService.getEventValue())
                        .gt(PqsEventdetail::getPersisttime, msgEventConfigService.getEventDuration())
                        .in(PqsEventdetail::getLineid, listIds)
                        .orderByDesc(PqsEventdetail::getTimeid).list();
                eventdetails.addAll(temp);
            }
        } else {
            List<PqsEventdetail> temp = pqsEventdetailService.lambdaQuery()
                    .between(PqsEventdetail::getTimeid, startTime, endTime)
                    .in(PqsEventdetail::getWavetype, msgEventConfigService.getEventType())
                    .le(PqsEventdetail::getEventvalue, msgEventConfigService.getEventValue())
                    .gt(PqsEventdetail::getPersisttime, msgEventConfigService.getEventDuration())
                    .in(PqsEventdetail::getLineid, lineIds)
                    .orderByDesc(PqsEventdetail::getTimeid).list();
            eventdetails.addAll(temp);
        }

        if (Objects.equals(largeScreenCountParam.getEventtype(), 1)) {
            List<String> eventIds = eventdetails.stream().map(PqsEventdetail::getEventdetailIndex).collect(Collectors.toList());
            //通知
            List<MsgEventInfo> msgEventInfoList = msgEventInfoService.getMsgByIds(eventIds);
            // 使用 for 循环处理日期范围
            for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
                EventTrendVO eventTrendVO = new EventTrendVO();
                eventTrendVO.setLocalDate(date);
                LocalDate finalDate = date;
                List<MsgEventInfo> collect = msgEventInfoList.stream().filter(temp -> Objects.equals(DateUtil.format(temp.getSendTime(), DatePattern.NORM_DATE_PATTERN), DateUtil.format(finalDate.atStartOfDay(), DatePattern.NORM_DATE_PATTERN))).collect(Collectors.toList());
                eventTrendVO.setEventCount(collect.size());
                eventTrendVOList.add(eventTrendVO);
            }


        } else {

            // 使用 for 循环处理日期范围
            for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
                EventTrendVO eventTrendVO = new EventTrendVO();
                eventTrendVO.setLocalDate(date);
                LocalDate finalDate = date;
                List<PqsEventdetail> collect = eventdetails.stream().filter(temp -> Objects.equals(DateUtil.format(temp.getTimeid(), DatePattern.NORM_DATE_PATTERN), DateUtil.format(finalDate.atStartOfDay(), DatePattern.NORM_DATE_PATTERN))).collect(Collectors.toList());
                eventTrendVO.setEventCount(collect.size());
                eventTrendVOList.add(eventTrendVO);
            }
        }


        return eventTrendVOList;
    }

    @Override
    public Page<EventDetailVO> eventList(LargeScreenCountParam largeScreenCountParam) {
        Page<PqsEventdetail> pqsEventdetailPage = new Page<>(largeScreenCountParam.getPageNum(), largeScreenCountParam.getPageSize());

        //起始时间
        LocalDateTime startTime;
        //结束时间
        LocalDateTime endTime;
        if (largeScreenCountParam.getType() == 3) {
            //起始时间
            startTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.beginOfMonth(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER);
            //结束时间
            endTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.endOfMonth(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER);
        } else if (largeScreenCountParam.getType() == 4) {
            //起始时间
            startTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.beginOfWeek(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER);
            //结束时间
            endTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.endOfWeek(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER);
        } else {
            throw new BusinessException("统计类型有误类型");
        }
        //根据用户获取当前部门及子部门id
        //List<String> deptAndChildren = pqsDeptsService.findDeptAndChildren(largeScreenCountParam.getDeptId());
        //获取对应监测点id
        //List<PqsDeptsline> deptslines = pqsDeptslineService.lambdaQuery().in(PqsDeptsline::getDeptsIndex, deptAndChildren).eq(PqsDeptsline::getSystype, sysTypeZt).list();
        //List<Integer> deptslineIds = deptslines.stream().map(PqsDeptsline::getLineIndex).distinct().collect(Collectors.toList());
        if (CollectionUtils.isEmpty(lineIds)) {
            throw new BusinessException("部门下暂无监测点");

        }
        List<LedgerBaseInfoDTO> pqLineList = pqLineService.getBaseLineInfo(lineIds);
        Map<Integer, LedgerBaseInfoDTO> ledgerBaseInfoDTOMap = pqLineList.stream().collect(Collectors.toMap(LedgerBaseInfoDTO::getLineId, Function.identity()));

        QueryWrapper<PqsEventdetail> queryWrapper = new QueryWrapper<>();
        if (lineIds.size() > 1000) {
            List<List<Integer>> idPartitions = CollUtil.split(lineIds, 1000);

            queryWrapper.lambda()
                    .between(PqsEventdetail::getTimeid, startTime, endTime)
                    .in(PqsEventdetail::getWavetype, msgEventConfigService.getEventType())
                    .le(PqsEventdetail::getEventvalue, msgEventConfigService.getEventValue())
                    .gt(PqsEventdetail::getPersisttime, msgEventConfigService.getEventDuration())
                    .and(ew -> {
                        for (List<Integer> pList : idPartitions) {
                            ew.or(w -> w.in(PqsEventdetail::getLineid, pList));
                        }
                    }).orderByDesc(PqsEventdetail::getTimeid);


        } else {
            queryWrapper.lambda()
                    .between(PqsEventdetail::getTimeid, startTime, endTime)
                    .in(PqsEventdetail::getLineid, lineIds)
                    .in(PqsEventdetail::getWavetype, msgEventConfigService.getEventType())
                    .gt(PqsEventdetail::getPersisttime, msgEventConfigService.getEventDuration())
                    .le(PqsEventdetail::getEventvalue, msgEventConfigService.getEventValue())
                    .orderByDesc(PqsEventdetail::getTimeid);
        }
        //查询需要发送短息处理的部门反推监测点

        List<Integer> noticeLineIds = new ArrayList<>();
        List<PqsUser> pqsUserList = pqsUserService.lambdaQuery().eq(PqsUser::getState, 1).list();
        if (!CollectionUtils.isEmpty(pqsUserList)) {
            List<String> collect = pqsUserList.stream().map(PqsUser::getUserIndex).collect(Collectors.toList());
            List<PqsUserSet> pqsUserSetList = pqsUsersetService.lambdaQuery().eq(PqsUserSet::getIsNotice, 1).in(PqsUserSet::getUserIndex, collect).list();
            List<String> noticeDept = pqsUserSetList.stream().map(temp -> {
                return pqsDeptsService.findDeptAndChildren(temp.getDeptsIndex());
            }).flatMap(Collection::stream).distinct().collect(Collectors.toList());
            //获取对应监测点id
            if (!CollectionUtils.isEmpty(noticeDept)) {
                List<PqsDeptsline> noticeLine = pqsDeptslineService.lambdaQuery().in(PqsDeptsline::getDeptsIndex, noticeDept).eq(PqsDeptsline::getSystype, sysTypeZt).list();
                noticeLineIds = noticeLine.stream().map(PqsDeptsline::getLineIndex).distinct().collect(Collectors.toList());
            }

        }

        IPage<PqsEventdetail> list = pqsEventdetailService.getBaseMapper().selectPage(pqsEventdetailPage, queryWrapper);
        List<Integer> finalNoticeLineIds = noticeLineIds;
        List<EventDetailVO> collect = list.getRecords().stream().map(temp -> {
            EventDetailVO eventDetailVO = new EventDetailVO();
            eventDetailVO.setEventdetail_index(temp.getEventdetailIndex());
            eventDetailVO.setTimeid(temp.getTimeid());
            eventDetailVO.setMs(temp.getMs());
            eventDetailVO.setWavetype(temp.getWavetype().toString());
            eventDetailVO.setPersisttime(BigDecimal.valueOf(temp.getPersisttime() / 1000).setScale(3, RoundingMode.HALF_UP).toString());
            eventDetailVO.setEventvalue(temp.getEventvalue());
            eventDetailVO.setLookFlag(temp.getLookFlag());
            eventDetailVO.setNoticeFlag(temp.getNoticeFlag());
            if (ledgerBaseInfoDTOMap.containsKey(temp.getLineid())) {
                LedgerBaseInfoDTO ledgerBaseInfoDTO = ledgerBaseInfoDTOMap.get(temp.getLineid());
                eventDetailVO.setLineid(ledgerBaseInfoDTO.getLineId());
                eventDetailVO.setPointname(ledgerBaseInfoDTO.getLineName());
                eventDetailVO.setBdname(ledgerBaseInfoDTO.getStationName());
                eventDetailVO.setGdName(ledgerBaseInfoDTO.getGdName());
                eventDetailVO.setBusName(ledgerBaseInfoDTO.getBusBarName());
                eventDetailVO.setObjName(ledgerBaseInfoDTO.getObjName());
            }
            eventDetailVO.setNeedDealFlag(finalNoticeLineIds.contains(temp.getLineid()) ? 1 : 0);
            return eventDetailVO;
        }).collect(Collectors.toList());
        Page<EventDetailVO> returnpage = new Page<>(largeScreenCountParam.getPageNum(), largeScreenCountParam.getPageSize());
        returnpage.setRecords(collect);
        returnpage.setTotal(list.getTotal());
        return returnpage;
    }

    @Override
    public List<EventDetailVO> noDealEventList(LargeScreenCountParam largeScreenCountParam) {
        List<EventDetailVO> result = new ArrayList<>();
        DateTime startTime = DateUtil.beginOfDay(DateUtil.parse(largeScreenCountParam.getSearchBeginTime()));
        DateTime endTime = DateUtil.endOfDay(DateUtil.parse(largeScreenCountParam.getSearchEndTime()));

        List<Integer> deptslineIds = commGeneralService.getLineIdsByRedis(largeScreenCountParam.getDeptId());
        if (CollUtil.isEmpty(deptslineIds)) {
            return result;
        }
        List<PqsEventdetail> allList = new ArrayList<>();
        LambdaQueryWrapper<PqsEventdetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (deptslineIds.size() > 1000) {
            List<List<Integer>> idList = CollUtil.split(deptslineIds, 1000);
            for (List<Integer> ids : idList) {
                lambdaQueryWrapper.clear();
                lambdaQueryWrapper.between(PqsEventdetail::getTimeid, startTime, endTime)
                        .in(PqsEventdetail::getWavetype, msgEventConfigService.getEventType())
                        .gt(PqsEventdetail::getPersisttime, msgEventConfigService.getEventDuration())
                        .le(PqsEventdetail::getEventvalue, msgEventConfigService.getEventValue())
                        .in(PqsEventdetail::getLineid, ids)
                        .and(wrapper -> wrapper.eq(PqsEventdetail::getLookFlag, 0).or().isNull(PqsEventdetail::getLookFlag));
                List<PqsEventdetail> eventList = pqsEventdetailService.list(lambdaQueryWrapper);
                allList.addAll(eventList);
            }
        } else {
            lambdaQueryWrapper.between(PqsEventdetail::getTimeid, startTime, endTime)
                    .in(PqsEventdetail::getWavetype, msgEventConfigService.getEventType())
                    .le(PqsEventdetail::getEventvalue, msgEventConfigService.getEventValue())
                    .gt(PqsEventdetail::getPersisttime, msgEventConfigService.getEventDuration())
                    .in(PqsEventdetail::getLineid, deptslineIds)
                    .and(wrapper -> wrapper.eq(PqsEventdetail::getLookFlag, 0).or().isNull(PqsEventdetail::getLookFlag));
            List<PqsEventdetail> eventList = pqsEventdetailService.list(lambdaQueryWrapper);
            allList.addAll(eventList);
        }


        if (CollUtil.isNotEmpty(allList)) {
            List<Integer> ids = allList.stream().map(PqsEventdetail::getLineid).distinct().collect(Collectors.toList());
            List<LedgerBaseInfoDTO> pqLineList = pqLineService.getBaseLineInfo(ids);
            Map<Integer, LedgerBaseInfoDTO> ledgerBaseInfoDTOMap = pqLineList.stream().collect(Collectors.toMap(LedgerBaseInfoDTO::getLineId, Function.identity()));

            Map<String, PqUserLedgerPO> userMap;
            Map<Integer, List<PqUserLineAssPO>> assMap;
            List<PqUserLineAssPO> assList = pqUserLineAssMapper.selectList(new LambdaQueryWrapper<PqUserLineAssPO>().in(PqUserLineAssPO::getLineIndex, ids));
            if (CollUtil.isNotEmpty(assList)) {
                List<String> userIds = assList.stream().map(PqUserLineAssPO::getUserIndex).distinct().collect(Collectors.toList());
                LambdaQueryWrapper<PqUserLedgerPO> wrapper = new LambdaQueryWrapper<>();
                if(userIds.size()>1000){
                    List<List<String>> userIdsList = CollUtil.split(userIds, 1000);
                    wrapper.and(w -> {
                        for (List<String> teIds : userIdsList) {
                            w.or(wIn -> wIn.in(PqUserLedgerPO::getId, teIds));
                        }
                    });
                }else {
                    wrapper.in(PqUserLedgerPO::getId, userIds);
                }
                List<PqUserLedgerPO> poList = pqUserLedgerMapper.selectList(wrapper);
                userMap = poList.stream().collect(Collectors.toMap(PqUserLedgerPO::getId, Function.identity()));
                assMap = assList.stream().collect(Collectors.groupingBy(PqUserLineAssPO::getLineIndex));
            } else {
                userMap = new HashMap<>();
                assMap = new HashMap<>();
            }

            for (PqsEventdetail it : allList) {
                EventDetailVO eventDetailVO = new EventDetailVO();
                eventDetailVO.setEventdetail_index(it.getEventdetailIndex());
                eventDetailVO.setTimeid(it.getTimeid());
                eventDetailVO.setMs(it.getMs());
                eventDetailVO.setWavetype(it.getWavetype().toString());
                eventDetailVO.setPersisttime(BigDecimal.valueOf(it.getPersisttime() / 1000).setScale(3, RoundingMode.HALF_UP).toString());
                eventDetailVO.setEventvalue(it.getEventvalue());
                if (ledgerBaseInfoDTOMap.containsKey(it.getLineid())) {
                    LedgerBaseInfoDTO ledgerBaseInfoDTO = ledgerBaseInfoDTOMap.get(it.getLineid());
                    eventDetailVO.setLineid(ledgerBaseInfoDTO.getLineId());
                    eventDetailVO.setPointname(ledgerBaseInfoDTO.getLineName());
                    eventDetailVO.setBdname(ledgerBaseInfoDTO.getStationName());
                    eventDetailVO.setGdName(ledgerBaseInfoDTO.getGdName());
                    eventDetailVO.setBusName(ledgerBaseInfoDTO.getBusBarName());
                }
                if (assMap.containsKey(eventDetailVO.getLineid())) {
                    List<String> temList = assMap.get(eventDetailVO.getLineid()).stream().map(PqUserLineAssPO::getUserIndex).collect(Collectors.toList());
                    String str = temList.stream().map(its -> userMap.containsKey(its) ? userMap.get(its).getCustomerName() + "; " : "/").collect(Collectors.joining());
                    eventDetailVO.setObjName(str);
                }
                result.add(eventDetailVO);
            }
        }
        result = result.stream().sorted(Comparator.comparing(EventDetailVO::getTimeid)).collect(Collectors.toList());
        return result;
    }
    public Set<String> getAllParentDeptIds(Set<String> deptIds) {
        // 首次获取直接父级
        List<PqsDepts> allDeptList = pqsDeptsService.lambdaQuery().list();
        // 递归获取所有父级
        Set<String> result = recursivelyGetParentIds(deptIds, allDeptList);
        return result;
    }
    private Set<String> recursivelyGetParentIds(Set<String> currentParentIds, List<PqsDepts> allDeptList) {
        Set<String> result = new HashSet<>(currentParentIds);
        Set<String> nextLevelParentIds = new HashSet<>();
        List<PqsDepts> parentDeptList = allDeptList.stream().filter(it -> currentParentIds.contains(it.getDeptsIndex())).collect(Collectors.toList());
        for (PqsDepts pqsDepts : parentDeptList) {
            if (!pqsDepts.getParentnodeid().equals("0")) {
                nextLevelParentIds.add(pqsDepts.getParentnodeid());
            }
        }
        // 如果有更高层级的父级，继续递归
        if (!nextLevelParentIds.isEmpty()) {
            Set<String> deeperParentIds = recursivelyGetParentIds(nextLevelParentIds, allDeptList);
            result.addAll(deeperParentIds);
        }
        return result;
    }
    @Override
    public List<MessageEventVO> noDealEventListMessage(LargeScreenCountParam largeScreenCountParam) {
        List<MessageEventVO> result = new ArrayList<>();
        DateTime startTime = DateUtil.beginOfDay(DateUtil.parse(largeScreenCountParam.getSearchBeginTime()));
        DateTime endTime = DateUtil.endOfDay(DateUtil.parse(largeScreenCountParam.getSearchEndTime()));
        Set<String> resultIds = getAllParentDeptIds(Collections.singleton(largeScreenCountParam.getDeptId()));

        List<PqsUserSet> list = pqsUsersetService.lambdaQuery().in(PqsUserSet::getDeptsIndex, resultIds).list();
        if(CollectionUtils.isEmpty(list)){
            return result;
        }
        List<String> userIds = list.stream().map(PqsUserSet::getUserIndex).collect(Collectors.toList());

        List<MsgEventInfo> msgEventInfos = msgEventInfoService.lambdaQuery().in(MsgEventInfo::getUserId, userIds).between(MsgEventInfo::getSendTime, startTime, endTime).ne(MsgEventInfo::getIsHandle,1).list();
        Map<String, List<MsgEventInfo>> collect = msgEventInfos.stream().collect(Collectors.groupingBy(MsgEventInfo::getMsgContent));
        collect.forEach((k,v)->{
            MessageEventVO mesageEventVO = new MessageEventVO();
            List<String> eventIds = v.stream().map(MsgEventInfo::getEventIndex).distinct().collect(Collectors.toList());
            List<String> messageIds = v.stream().map(MsgEventInfo::getMsgIndex).distinct().collect(Collectors.toList());

            mesageEventVO.setMessageIds(messageIds);
            mesageEventVO.setEventIds(eventIds);
            mesageEventVO.setMessageContent(k);
            result.add(mesageEventVO);
        });

//        result = result.stream().sorted(Comparator.comparing(EventDetailVO::getTimeid)).collect(Collectors.toList());
        return result;
    }



    @Override
    public boolean lookEvent(List<String> ids) {
        if (ids.size() > 1000) {
            List<List<String>> eventIds = CollUtil.split(ids, 1000);
            for (List<String> needIds : eventIds) {
                LambdaUpdateWrapper<PqsEventdetail> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.in(PqsEventdetail::getEventdetailIndex, needIds).set(PqsEventdetail::getLookFlag, DataStateEnum.ENABLE.getCode());
                pqsEventdetailService.update(updateWrapper);
            }
        } else {
            LambdaUpdateWrapper<PqsEventdetail> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.in(PqsEventdetail::getEventdetailIndex, ids).set(PqsEventdetail::getLookFlag, DataStateEnum.ENABLE.getCode());
            pqsEventdetailService.update(updateWrapper);
        }
        return true;
    }
    @Override
    public boolean lookMessage(List<String> ids) {
        if (ids.size() > 1000) {
            List<List<String>> eventIds = CollUtil.split(ids, 1000);
            for (List<String> needIds : eventIds) {
                LambdaUpdateWrapper<MsgEventInfo> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.in(MsgEventInfo::getMsgIndex, needIds).set(MsgEventInfo::getIsHandle, DataStateEnum.ENABLE.getCode());
                msgEventInfoService.update(updateWrapper);
            }
        } else {
            LambdaUpdateWrapper<MsgEventInfo> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.in(MsgEventInfo::getMsgIndex, ids).set(MsgEventInfo::getIsHandle, DataStateEnum.ENABLE.getCode());
            msgEventInfoService.update(updateWrapper);
        }
        return true;
    }

    @Override
    public List<MapCountVO> mapCount(LargeScreenCountParam largeScreenCountParam) {
        List<MapCountVO> result = new ArrayList<>();
        //起始时间
        LocalDateTime startTime;
        //结束时间
        LocalDateTime endTime;
        if (largeScreenCountParam.getType() == 3) {
            //起始时间
            startTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.beginOfMonth(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER);
            //结束时间
            endTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.endOfMonth(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER);
        } else if (largeScreenCountParam.getType() == 4) {
            //起始时间
            startTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.beginOfWeek(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER);
            //结束时间
            endTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.endOfWeek(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER);
        } else {
            throw new BusinessException("统计类型有误类型");
        }
        //根据用户获取当前部门及子部门id
        List<String> deptAndChildren = pqsDeptsService.findDeptAndChildren(largeScreenCountParam.getDeptId());
        deptAndChildren.remove(largeScreenCountParam.getDeptId());
        //获取对应监测点id
        List<PqsDeptsline> deptslines = pqsDeptslineService.lambdaQuery().in(PqsDeptsline::getDeptsIndex, deptAndChildren).eq(PqsDeptsline::getSystype, sysTypeZt).list();
        if (CollectionUtils.isEmpty(deptslines)) {
            throw new BusinessException("部门下暂无监测点");
        }


        List<PqsDepts> list = pqsDeptsService.lambdaQuery().eq(PqsDepts::getState, 1).list();
        Map<String, PqsDepts> stringPqsDeptsMap = list.stream().collect(Collectors.toMap(PqsDepts::getDeptsIndex, Function.identity(), (key1, key2) -> key2));
        Map<String, List<PqsDeptsline>> collect = deptslines.stream().collect(Collectors.groupingBy(PqsDeptsline::getDeptsIndex));

        List<Integer> ids = deptslines.stream().map(PqsDeptsline::getLineIndex).collect(Collectors.toList());
        List<LedgerBaseInfoDTO> ledgerBaseInfoDTOS = pqLineService.getBaseLineInfo(ids);

        collect.forEach((k, v) -> {
            List<Integer> temList = v.stream().map(PqsDeptsline::getLineIndex).collect(Collectors.toList());
            MapCountVO mapCountVO = new MapCountVO();
            mapCountVO.setDeptsIndex(k);
            mapCountVO.setDeptsName(stringPqsDeptsMap.get(k).getDeptsname());

            List<LedgerBaseInfoDTO> temLedger = ledgerBaseInfoDTOS.stream().filter(it -> temList.contains(it.getLineId())).collect(Collectors.toList());
            mapCountVO.setLineList(temLedger);
            mapCountVO.setLineCount(temLedger.size());
            List<Integer> deptslineIds = v.stream().map(PqsDeptsline::getLineIndex).collect(Collectors.toList());
            List<PqsEventdetail> eventdetails = pqsEventdetailService.lambdaQuery()
                    .between(PqsEventdetail::getTimeid, startTime, endTime)
                    .in(PqsEventdetail::getWavetype, msgEventConfigService.getEventType())
                    .gt(PqsEventdetail::getPersisttime, msgEventConfigService.getEventDuration())
                    .le(PqsEventdetail::getEventvalue, msgEventConfigService.getEventValue())
                    .in(PqsEventdetail::getLineid, deptslineIds).list();
            mapCountVO.setEventCount(eventdetails.size());

            List<String> eveIdndex = eventdetails.stream().map(PqsEventdetail::getEventdetailIndex).collect(Collectors.toList());
            List<MsgEventInfo> temp = new ArrayList<>();
            if (!CollectionUtils.isEmpty(eveIdndex)) {
                temp = msgEventInfoService.getMsgByIds(eveIdndex);
            }
            List<EventDetailVO> change = change(eventdetails, temp);

            mapCountVO.setEventList(change);
            mapCountVO.setNoticeCount(temp.size());
            mapCountVO.setNoticeList(temp);
            result.add(mapCountVO);
        });
        return result;
    }

    @Override
    public EventMsgDetailVO eventMsgDetail(String eventId) {
        EventMsgDetailVO eventMsgDetailVO = new EventMsgDetailVO();
        LambdaQueryWrapper<MessageEventFeedback> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(MessageEventFeedback::getEventIndex, eventId);
        MessageEventFeedback messageEventFeedback = messageEventFeedbackService.getOne(lambdaQueryWrapper);
        if (Objects.nonNull(messageEventFeedback)) {
            BeanUtil.copyProperties(messageEventFeedback, eventMsgDetailVO);
            if (messageEventFeedback.getIsSensitive() == 1) {
                PqsEventdetail pqsEventdetail = pqsEventdetailService.lambdaQuery().eq(PqsEventdetail::getEventdetailIndex, eventId).one();
                PqLinedetail pqLinedetail = pqLinedetailMapper.selectById(pqsEventdetail.getLineid());
                eventMsgDetailVO.setObjName(pqLinedetail.getObjname());
            }
        }
        LambdaQueryWrapper<MsgEventInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MsgEventInfo::getEventIndex, eventId);
        List<MsgEventInfo> msgEventInfoList = msgEventInfoService.list(queryWrapper);
        eventMsgDetailVO.setMsgList(msgEventInfoList);

        return eventMsgDetailVO;
    }

    @Override
    public List<MsgEventInfo> msgSendList(LargeScreenCountParam largeScreenCountParam) {
        List<MsgEventInfo> result = new ArrayList<>();
        // List<Integer> ids = commGeneralService.getLineIdsByDept(largeScreenCountParam);
        if (CollUtil.isEmpty(lineIds)) {
            return result;
        }
        List<PqsEventdetail> allEventList = new ArrayList<>();
        if (lineIds.size() > 1000) {
            List<List<Integer>> listIds = CollUtil.split(lineIds, 1000);
            for (List<Integer> itemIds : listIds) {
                List<PqsEventdetail> pqsEventdetailList = pqsEventdetailService.lambdaQuery().in(PqsEventdetail::getLineid, itemIds).select(PqsEventdetail::getEventdetailIndex).list();
                allEventList.addAll(pqsEventdetailList);
            }
        } else {
            List<PqsEventdetail> pqsEventdetailList = pqsEventdetailService.lambdaQuery().in(PqsEventdetail::getLineid, lineIds).select(PqsEventdetail::getEventdetailIndex).list();
            allEventList.addAll(pqsEventdetailList);
        }
        if (CollUtil.isEmpty(allEventList)) {
            return result;
        }

        List<String> eventIds = allEventList.stream().map(PqsEventdetail::getEventdetailIndex).collect(Collectors.toList());
        result = msgEventInfoService.getMsgByIds(eventIds);
        result = result.stream().sorted(Comparator.comparing(MsgEventInfo::getSendTime, Comparator.reverseOrder())).collect(Collectors.toList());
        if (result.size() > 200) {
            result = result.subList(0, 200);
        }
        return result;
    }

    @Override
    public Page<MsgEventInfo> hasSendMsgPage(LargeScreenCountParam largeScreenCountParam) {
        DateTime start = DateUtil.beginOfDay(DateUtil.parse(largeScreenCountParam.getSearchBeginTime()));
        DateTime end = DateUtil.endOfDay(DateUtil.parse(largeScreenCountParam.getSearchEndTime()));

        QueryWrapper<MsgEventInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("DISTINCT msg_index,user_id, user_name,send_time,msg_content,phone,send_result,is_handle ");
        queryWrapper.lambda().eq(!StringUtils.isEmpty(largeScreenCountParam.getSendResult()), MsgEventInfo::getSendResult, largeScreenCountParam.getSendResult());
        queryWrapper.lambda().orderByDesc(MsgEventInfo::getSendTime).between(MsgEventInfo::getSendTime, start, end);
        if(StrUtil.isNotBlank(largeScreenCountParam.getSearchValue())){
            queryWrapper.lambda().and(w->w.like(MsgEventInfo::getUserName,largeScreenCountParam.getSearchValue()).or().like(MsgEventInfo::getPhone,largeScreenCountParam.getSearchValue()));
        }
        return msgEventInfoService.page(new Page<>(PageFactory.getPageNum(largeScreenCountParam), PageFactory.getPageSize(largeScreenCountParam)), queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean msgHandle(MessageEventFeedbackParam messageEventFeedbackParam) {

        PqsEventdetail pqsEventdetail = pqsEventdetailService.lambdaQuery().eq(PqsEventdetail::getEventdetailIndex, messageEventFeedbackParam.getEventIndex()).one();
        if (Objects.isNull(pqsEventdetail.getLookFlag()) || pqsEventdetail.getLookFlag() == 0) {
            throw new BusinessException(CommonResponseEnum.FAIL, "当前事件暂未处理，请先处理!");
        }

        MessageEventFeedback messageEventFeedback = messageEventFeedbackService.lambdaQuery().eq(MessageEventFeedback::getEventIndex, messageEventFeedbackParam.getEventIndex()).one();
        if (Objects.nonNull(messageEventFeedback)) {
            throw new BusinessException(CommonResponseEnum.FAIL, "请勿重复处理!");
        }
        MessageEventFeedback po = new MessageEventFeedback();
        BeanUtil.copyProperties(messageEventFeedbackParam, po);
        po.setId(IdUtil.simpleUUID());
        messageEventFeedbackService.save(po);
        pqsEventdetailService.lambdaUpdate().set(PqsEventdetail::getNoticeFlag, DataStateEnum.ENABLE.getCode()).eq(PqsEventdetail::getEventdetailIndex, messageEventFeedbackParam.getEventIndex()).update();
        msgEventInfoService.lambdaUpdate().set(MsgEventInfo::getIsHandle, DataStateEnum.ENABLE.getCode()).eq(MsgEventInfo::getEventIndex, messageEventFeedbackParam.getEventIndex()).update();
        return true;
    }

    @Override
    public AlarmAnalysisVO alarmAnalysisDetail(LargeScreenCountParam largeScreenCountParam) {
        AlarmAnalysisVO alarmAnalysisVO = new AlarmAnalysisVO();
        //起始时间
        LocalDateTime startTime;
        //结束时间
        LocalDateTime endTime;
        if (largeScreenCountParam.getType() == 3) {
            //起始时间
            startTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.beginOfMonth(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER);
            //结束时间
            endTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.endOfMonth(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER);
        } else if (largeScreenCountParam.getType() == 4) {
            //起始时间
            startTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.beginOfWeek(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER);
            //结束时间
            endTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.endOfWeek(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER);
        } else {
            throw new BusinessException("统计类型有误类型");
        }

        //根据用户获取当前部门及子部门id
        //List<String> deptAndChildren = pqsDeptsService.findDeptAndChildren(largeScreenCountParam.getDeptId());
        //获取对应监测点id
        //List<PqsDeptsline> deptslines = pqsDeptslineService.lambdaQuery().in(PqsDeptsline::getDeptsIndex, deptAndChildren).eq(PqsDeptsline::getSystype, sysTypeZt).list();
        //List<Integer> deptslineIds = deptslines.stream().map(PqsDeptsline::getLineIndex).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(lineIds)) {
            throw new BusinessException("部门下暂无监测点");

        }
        List<PqsEventdetail> eventdetails = new ArrayList<>();
        if (lineIds.size() > 1000) {
            List<List<Integer>> listIds = CollUtil.split(lineIds, 1000);
            for (List<Integer> itemIds : listIds) {
                List<PqsEventdetail> temp = pqsEventdetailService.lambdaQuery()
                        .between(PqsEventdetail::getTimeid, startTime, endTime)
                        .in(PqsEventdetail::getWavetype, msgEventConfigService.getEventType())
                        .le(PqsEventdetail::getEventvalue, msgEventConfigService.getEventValue())
                        .gt(PqsEventdetail::getPersisttime, msgEventConfigService.getEventDuration())
                        .in(PqsEventdetail::getLineid, listIds)
                        .orderByDesc(PqsEventdetail::getTimeid).list();
                eventdetails.addAll(temp);
            }
        } else {
            List<PqsEventdetail> temp = pqsEventdetailService.lambdaQuery()
                    .between(PqsEventdetail::getTimeid, startTime, endTime)
                    .in(PqsEventdetail::getWavetype, msgEventConfigService.getEventType())
                    .le(PqsEventdetail::getEventvalue, msgEventConfigService.getEventValue())
                    .gt(PqsEventdetail::getPersisttime, msgEventConfigService.getEventDuration())
                    .in(PqsEventdetail::getLineid, lineIds)
                    .orderByDesc(PqsEventdetail::getTimeid).list();
            eventdetails.addAll(temp);
        }

        Integer eventCount = eventdetails.size();
        // 告警
        List<PqsEventdetail> aLarmEvent = eventdetails.stream().filter(temp -> temp.getEventvalue() < 0.5).collect(Collectors.toList());
        // 预警
        List<PqsEventdetail> warnEvent = eventdetails.stream().filter(temp -> temp.getEventvalue() >= 0.5 && temp.getEventvalue() < 0.9).collect(Collectors.toList());
        List<String> eventIds = eventdetails.stream().map(PqsEventdetail::getEventdetailIndex).collect(Collectors.toList());
        //通知
        List<MsgEventInfo> msgEventInfoList = msgEventInfoService.getMsgByIds(eventIds);

        msgEventInfoList = msgEventInfoList.stream().sorted(Comparator.comparing(MsgEventInfo::getSendTime, Comparator.reverseOrder())).collect(Collectors.toList());


        List<PqsEventdetail> lookALarmEvent = aLarmEvent.stream().filter(temp -> Objects.equals(temp.getLookFlag(), 1)).collect(Collectors.toList());
        List<PqsEventdetail> lookWarnEvent = warnEvent.stream().filter(temp -> Objects.equals(temp.getLookFlag(), 1)).collect(Collectors.toList());
        List<MsgEventInfo> handleMsg = msgEventInfoList.stream().filter(temp -> Objects.equals(temp.getIsHandle(), 1)).collect(Collectors.toList());

        Integer aLarmCount = aLarmEvent.size();
        Integer warnCount = warnEvent.size();
        Integer noticeCount = msgEventInfoList.size();
        Integer lookALarmCount = lookALarmEvent.size();
        Integer lookWarnCount = lookWarnEvent.size();
        Integer lookNoticeCount = handleMsg.size();

        alarmAnalysisVO.setEventCount(eventCount);
        alarmAnalysisVO.setALarmCount(aLarmCount);
        alarmAnalysisVO.setWarnCount(warnCount);
        alarmAnalysisVO.setNoticeCount(noticeCount);
        alarmAnalysisVO.setLookALarmCount(lookALarmCount);
        alarmAnalysisVO.setLookWarnCount(lookWarnCount);
        alarmAnalysisVO.setLookNoticeCount(lookNoticeCount);


        alarmAnalysisVO.setEventdetails(change(eventdetails, msgEventInfoList));
        alarmAnalysisVO.setALarmEvent(change(aLarmEvent, msgEventInfoList));
        alarmAnalysisVO.setWarnEvent(change(warnEvent, msgEventInfoList));
        alarmAnalysisVO.setNoticeEvent(msgEventInfoList);
        alarmAnalysisVO.setLookALarmEvent(change(lookALarmEvent, msgEventInfoList));
        alarmAnalysisVO.setLookWarnEvent(change(lookWarnEvent, msgEventInfoList));
        alarmAnalysisVO.setLookNoticeEvent(handleMsg);


        return alarmAnalysisVO;
    }

    @Override
    public Page<EventDetailVO> eventTablePage(LargeScreenCountParam largeScreenCountParam) {
        Page<EventDetailVO> result = new Page<>(PageFactory.getPageNum(largeScreenCountParam), PageFactory.getPageSize(largeScreenCountParam));
        //起始时间
        LocalDateTime startTime;
        //结束时间
        LocalDateTime endTime;
        if (largeScreenCountParam.getType() == 3) {
            //起始时间
            startTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.beginOfMonth(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER);
            //结束时间
            endTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.endOfMonth(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER);
        } else if (largeScreenCountParam.getType() == 4) {
            //起始时间
            startTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.beginOfWeek(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER);
            //结束时间
            endTime = LocalDateTimeUtil.parse(DateUtil.format(DateUtil.endOfWeek(new Date()), DatePattern.NORM_DATETIME_FORMATTER), DatePattern.NORM_DATETIME_FORMATTER);
        } else {
            throw new BusinessException("统计类型有误类型");
        }

        //List<Integer> lineIds = commGeneralService.getLineIdsByDept(largeScreenCountParam);
        if (CollectionUtils.isEmpty(lineIds)) {
            throw new BusinessException("部门下暂无监测点");
        }


        List<String> eventType = msgEventConfigService.getEventType();
        LambdaQueryWrapper<PqsEventdetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper
                .between(PqsEventdetail::getTimeid, startTime, endTime)
                .in(PqsEventdetail::getWavetype, eventType)
                .orderByDesc(PqsEventdetail::getTimeid);
        if (Objects.nonNull(largeScreenCountParam.getEventDeep())) {
            if (largeScreenCountParam.getEventDeep() == 0) {
                lambdaQueryWrapper.ge(PqsEventdetail::getEventvalue, 0.5).lt(PqsEventdetail::getEventvalue, 0.9);
            } else if (largeScreenCountParam.getEventDeep() == 1) {
                lambdaQueryWrapper.lt(PqsEventdetail::getEventvalue, 0.5);
            }
        }
        if (lineIds.size() > 1000) {
            List<List<Integer>> splitList = CollUtil.split(lineIds, 1000);
            lambdaQueryWrapper.and(ew -> {
                for (int i = 0; i < splitList.size(); i++) {
                    List<Integer> batch = splitList.get(i);
                    if (i == 0) {
                        ew.in(PqsEventdetail::getLineid, batch); // 第一个条件不加 or
                    } else {
                        ew.or().in(PqsEventdetail::getLineid, batch); // 后续条件加 or
                    }
                }
            });
        } else {
            lambdaQueryWrapper.in(PqsEventdetail::getLineid, lineIds);
        }
        Page<PqsEventdetail> page = pqsEventdetailService.page(new Page<>(PageFactory.getPageNum(largeScreenCountParam), PageFactory.getPageSize(largeScreenCountParam)), lambdaQueryWrapper);
        result.setTotal(page.getTotal());
        if (CollUtil.isEmpty(page.getRecords())) {
            return result;
        }
        List<Integer> ids = page.getRecords().stream().map(PqsEventdetail::getLineid).distinct().collect(Collectors.toList());
        List<LedgerBaseInfoDTO> pqLineList = pqLineService.getBaseLineInfo(ids);
        Map<Integer, LedgerBaseInfoDTO> ledgerBaseInfoDTOMap = pqLineList.stream().collect(Collectors.toMap(LedgerBaseInfoDTO::getLineId, Function.identity()));

        List<EventDetailVO> resultList = new ArrayList<>();
        for (PqsEventdetail pqsEventdetail : page.getRecords()) {
            EventDetailVO eventDetailVO = new EventDetailVO();
            BeanUtil.copyProperties(pqsEventdetail, eventDetailVO);
            if (ledgerBaseInfoDTOMap.containsKey(pqsEventdetail.getLineid())) {
                LedgerBaseInfoDTO ledgerBaseInfoDTO = ledgerBaseInfoDTOMap.get(pqsEventdetail.getLineid());
                eventDetailVO.setLineid(ledgerBaseInfoDTO.getLineId());
                eventDetailVO.setPointname(ledgerBaseInfoDTO.getLineName());
                eventDetailVO.setBdname(ledgerBaseInfoDTO.getStationName());
                eventDetailVO.setGdName(ledgerBaseInfoDTO.getGdName());
                eventDetailVO.setBusName(ledgerBaseInfoDTO.getBusBarName());
                eventDetailVO.setObjName(ledgerBaseInfoDTO.getObjName());
            }
            resultList.add(eventDetailVO);
        }
        result.setRecords(resultList);
        return result;
    }

    @Override
    public DeviceCountVO devFlagCount(LargeScreenCountParam largeScreenCountParam) {
        DeviceCountVO deviceCountVO = new DeviceCountVO();
        List<PqLine> pqLineList = (List<PqLine>) redisUtil.getObjectByKey(NAME_KEY + StrUtil.DASHED + "pqLineList");
        List<Integer> deptslineIds = (List<Integer>) redisUtil.getObjectByKey(NAME_KEY + StrUtil.DASHED + largeScreenCountParam.getDeptId());
        pqLineList = pqLineList.stream().filter(temp -> deptslineIds.contains(temp.getLineIndex())).collect(Collectors.toList());
        List<Integer> devIndexs = pqLineList.stream().map(PqLine::getDevIndex).collect(Collectors.toList());

        //在运总数
        List<PqDevice> list = pqDeviceService.lambdaQuery().in(PqDevice::getDevIndex, devIndexs).eq(PqDevice::getDevflag, 0).list();

        long onLine = list.stream().filter(temp -> Objects.equals(temp.getStatus(), 1)).count();
        long Offline = list.stream().filter(temp -> Objects.equals(temp.getStatus(), 0)).count();
        deviceCountVO.setAllCount(list.size());
        // deviceCountVO.setOnLine((int) onLine);
        // deviceCountVO.setOffLine((int) Offline);

        //临时调整
        deviceCountVO.setOnLine(list.size());
        deviceCountVO.setOffLine(0);

        return deviceCountVO;
    }

    @Override
    public List<DeviceDTO> devDetail(LargeScreenCountParam largeScreenCountParam) {
        DeviceCountVO deviceCountVO = new DeviceCountVO();
        List<PqLine> pqLineList = (List<PqLine>) redisUtil.getObjectByKey(NAME_KEY + StrUtil.DASHED + "pqLineList");
        List<Integer> deptslineIds = (List<Integer>) redisUtil.getObjectByKey(NAME_KEY + StrUtil.DASHED + largeScreenCountParam.getDeptId());

//        List<String> deptAndChildren = pqsDeptsService.findDeptAndChildren(largeScreenCountParam.getDeptId());
//        List<PqsDeptsline> deptslines = pqsDeptslineService.lambdaQuery().in(PqsDeptsline::getDeptsIndex, deptAndChildren).eq(PqsDeptsline::getSystype, sysTypeZt).list();
//        List<Integer> deptslineIds = deptslines.stream().map(PqsDeptsline::getLineIndex).collect(Collectors.toList());
        pqLineList = pqLineList.stream().filter(temp -> deptslineIds.contains(temp.getLineIndex())).collect(Collectors.toList());
        List<Integer> devIndexs = pqLineList.stream().map(PqLine::getDevIndex).collect(Collectors.toList());


        List<DeviceDTO> deviceDTOList = pqDeviceService.queryListByIds(devIndexs);
        deviceDTOList = deviceDTOList.stream().filter(temp -> Objects.equals(temp.getDevFlag(), 0)).collect(Collectors.toList());
        return deviceDTOList;
    }

    @Override
    public List<RegionDevCountVO> regionDevCount(LargeScreenCountParam largeScreenCountParam) {
        List<RegionDevCountVO> result = new ArrayList<>();
        List<PqLine> pqLineList = (List<PqLine>) redisUtil.getObjectByKey(NAME_KEY + StrUtil.DASHED + "pqLineList");
        List<String> deptAndChildren = pqsDeptsService.findDeptAndChildren(largeScreenCountParam.getDeptId());
        if (deptAndChildren.size() > 1) {
            deptAndChildren.remove(largeScreenCountParam.getDeptId());
        }
        List<PqDevice> pqDeviceList = pqDeviceService.lambdaQuery().eq(PqDevice::getDevflag, 0).list();

//        List<PqsDeptsline> deptslines = pqsDeptslineService.lambdaQuery().in(PqsDeptsline::getDeptsIndex, deptAndChildren).eq(PqsDeptsline::getSystype, sysTypeZt).list();
        List<PqsDeptDTO> list = pqsDeptsService.getDeptList(deptAndChildren);
        list.forEach(temp -> {
            RegionDevCountVO regionDevCountVO = new RegionDevCountVO();
            regionDevCountVO.setDeptsIndex(temp.getDeptsIndex());
            regionDevCountVO.setDeptsname(temp.getDeptsname());
            regionDevCountVO.setAreaName(temp.getAreaName());
            List<Integer> deptslineIds = (List<Integer>) redisUtil.getObjectByKey(NAME_KEY + StrUtil.DASHED + temp.getDeptsIndex());
            List<PqLine> collect = pqLineList.stream().filter(pqLine -> deptslineIds.contains(pqLine.getLineIndex())).collect(Collectors.toList());
            List<Integer> devIndexs = collect.stream().map(PqLine::getDevIndex).collect(Collectors.toList());
            List<PqDevice> tempDeviceList = pqDeviceList.stream().filter(pqDevice -> devIndexs.contains(pqDevice.getDevIndex())).collect(Collectors.toList());
            //在运总数
            //TODO 零时调整
            //long onLine = tempDeviceList.stream().filter(pqDevice -> Objects.equals(pqDevice.getStatus(), 1)).count();
            //long Offline = tempDeviceList.stream().filter(pqDevice ->Objects.equals(pqDevice.getStatus(), 0)).count();
            regionDevCountVO.setAllCount(tempDeviceList.size());

            regionDevCountVO.setOnLine((int) tempDeviceList.size());
            regionDevCountVO.setOffLine((int) 0);
            result.add(regionDevCountVO);
        });
        return result;
    }

    private List<PqUserLineAssPO> getUserLineAssociations(List<Integer> lineIds) {
        LambdaQueryWrapper<PqUserLineAssPO> assQuery = new LambdaQueryWrapper<>();
        assQuery.in(PqUserLineAssPO::getLineIndex, lineIds);

        if (lineIds.size() > 1000) {
            List<List<Integer>> lineList = CollUtil.split(lineIds, 1000);
            assQuery.and(w -> {
                for (List<Integer> ids : lineList) {
                    w.or(wIn -> wIn.in(PqUserLineAssPO::getLineIndex, ids));
                }
            });
        } else {
            assQuery.in(PqUserLineAssPO::getLineIndex, lineIds);
        }

        return pqUserLineAssMapper.selectList(assQuery);
    }

    private List<PqUserLedgerPO> getUserLedgers(List<String> assUserIds) {
        LambdaQueryWrapper<PqUserLedgerPO> userWrapper = new LambdaQueryWrapper<>();
        if (assUserIds.size() > 1000) {
            List<List<String>> assUserIdsList = CollUtil.split(assUserIds, 1000);
            userWrapper.and(w -> {
                for (List<String> ids : assUserIdsList) {
                    w.or(wIn -> wIn.in(PqUserLedgerPO::getId, ids));
                }
            });
        } else {
            userWrapper.in(PqUserLedgerPO::getId, assUserIds);
        }
        return pqUserLedgerMapper.selectList(userWrapper);
    }

    @Override
    public List<SubStationCountVO> substationCount(LargeScreenCountParam largeScreenCountParam) {
        LocalDateTime startTime = largeScreenCountParam.getStartTime().atStartOfDay();
        LocalDateTime endTime = LocalDateTimeUtil.endOfDay(largeScreenCountParam.getEndTime().atStartOfDay());

        List<Integer> deptslineIds = commGeneralService.getLineIdsByRedis(largeScreenCountParam.getDeptId());
        if (CollUtil.isEmpty(deptslineIds)) {
            return new ArrayList<>();
        }
        //查询暂态事件
        List<PqsEventdetail> eventdetails = new ArrayList<>();
        if (deptslineIds.size() > 1000) {
            List<List<Integer>> listIds = CollUtil.split(deptslineIds, 1000);
            for (List<Integer> itemIds : listIds) {
                List<PqsEventdetail> temp = pqsEventdetailService.lambdaQuery()
                        .between(PqsEventdetail::getTimeid, startTime, endTime)
                        .in(PqsEventdetail::getWavetype, msgEventConfigService.getEventType())
                        .le(PqsEventdetail::getEventvalue, msgEventConfigService.getEventValue())
                        .gt(PqsEventdetail::getPersisttime, msgEventConfigService.getEventDuration())
                        .in(PqsEventdetail::getLineid, itemIds)
                        .orderByDesc(PqsEventdetail::getTimeid).list();
                eventdetails.addAll(temp);
            }
        } else {
            List<PqsEventdetail> temp = pqsEventdetailService.lambdaQuery()
                    .between(PqsEventdetail::getTimeid, startTime, endTime)
                    .in(PqsEventdetail::getWavetype, msgEventConfigService.getEventType())
                    .le(PqsEventdetail::getEventvalue, msgEventConfigService.getEventValue())
                    .gt(PqsEventdetail::getPersisttime, msgEventConfigService.getEventDuration())
                    .in(PqsEventdetail::getLineid, deptslineIds)
                    .orderByDesc(PqsEventdetail::getTimeid).list();
            eventdetails.addAll(temp);
        }

        if (CollUtil.isEmpty(eventdetails)) {
            return new ArrayList<>();
        }

        List<Integer> lineIds = eventdetails.stream().map(PqsEventdetail::getLineid).distinct().collect(Collectors.toList());
        //List<PqLine> pqLineList = (List<PqLine>) redisUtil.getObjectByKey( NAME_KEY+ StrUtil.DASHED+"pqLineList");
        //pqLineList = pqLineList.stream().filter(temp->lineIds.contains(temp.getLineIndex())).collect(Collectors.toList());

        List<PqUserLineAssPO> assPOList = getUserLineAssociations(lineIds);
        List<String> userIds = assPOList.stream().map(PqUserLineAssPO::getUserIndex).distinct().collect(Collectors.toList());

        Map<Integer, List<String>> lineAssMap = assPOList.stream().collect(Collectors.groupingBy(PqUserLineAssPO::getLineIndex, Collectors.mapping(PqUserLineAssPO::getUserIndex, Collectors.toList())));

        List<PqUserLedgerPO> pqUserLedgerPOList = getUserLedgers(userIds);

        List<SubStationCountVO> subStationCountVOS = new ArrayList<>();
        List<LedgerBaseInfoDTO> ledgerBaseInfoDTOS = pqLineService.getBaseLedger(lineIds, null);
        //Map<Integer,LedgerBaseInfoDTO> ledgerBaseInfoDTOMap = ledgerBaseInfoDTOS.stream().collect(Collectors.toMap(LedgerBaseInfoDTO::getLineId, Function.identity()));

        List<Integer> subIndexs = ledgerBaseInfoDTOS.stream().map(LedgerBaseInfoDTO::getStationId).collect(Collectors.toList());
        List<PqsStationMap> pqsStationMapList = pqsStationMapMapper.selectList(new LambdaQueryWrapper<PqsStationMap>().in(PqsStationMap::getSubIndex, subIndexs).eq(PqsStationMap::getState, 1));
        Map<Long, PqsStationMap> stationMapMap = pqsStationMapList.stream().collect(Collectors.toMap(PqsStationMap::getSubIndex, dept -> dept));

        Map<Integer, List<LedgerBaseInfoDTO>> substationDTOMap = ledgerBaseInfoDTOS.stream().collect(Collectors.groupingBy(LedgerBaseInfoDTO::getStationId));

        Map<Integer, List<PqsEventdetail>> collect = eventdetails.stream().collect(Collectors.groupingBy(PqsEventdetail::getLineid));

        substationDTOMap.forEach((k, v) -> {
            LedgerBaseInfoDTO ledgerBaseInfoDTO = v.get(0);
            SubStationCountVO subStationCountVO = new SubStationCountVO();
            subStationCountVO.setStationId(k);
            subStationCountVO.setStationName(ledgerBaseInfoDTO.getStationName());
            subStationCountVO.setGdName(ledgerBaseInfoDTO.getGdName());

            if (stationMapMap.containsKey(k.longValue())) {
                PqsStationMap pqsStationMap = stationMapMap.get(k.longValue());
                if (Objects.nonNull(pqsStationMap.getLongItude())) {
                    subStationCountVO.setLongitude(pqsStationMap.getLongItude());
                } else {
                    subStationCountVO.setLongitude(0);
                }

                if (Objects.nonNull(pqsStationMap.getLatItude())) {
                    subStationCountVO.setLatitude(pqsStationMap.getLatItude());
                } else {
                    subStationCountVO.setLatitude(0);
                }
            } else {
                subStationCountVO.setLongitude(0);
                subStationCountVO.setLatitude(0);
            }
            List<Integer> tempLineIds = v.stream().map(LedgerBaseInfoDTO::getLineId).collect(Collectors.toList());
            subStationCountVO.setLineCount(tempLineIds.size());
            List<PqsEventdetail> tempEventList = eventdetails.stream().filter(temp -> tempLineIds.contains(temp.getLineid())).collect(Collectors.toList());
            subStationCountVO.setEventCount(tempEventList.size());
            v.forEach(item -> {
                String obj = "";
                if (lineAssMap.containsKey(item.getLineId())) {
                    List<String> userIndex = lineAssMap.get(item.getLineId());
                    obj = pqUserLedgerPOList.stream().filter(it -> userIndex.contains(it.getId())).map(PqUserLedgerPO::getCustomerName).collect(Collectors.joining(";"));
                }
                item.setObjName(StrUtil.isNotBlank(obj) ? obj : "/");
                item.setEventCount(collect.get(item.getLineId()).size());
            });
            subStationCountVO.setLineEventDetails(v);
            subStationCountVOS.add(subStationCountVO);
        });
        return subStationCountVOS;
    }

    @Override
    public Page<EventDetailVO> eventPage(LargeScreenCountParam largeScreenCountParam) {
        Page<PqsEventdetail> pqsEventdetailPage = new Page<>(largeScreenCountParam.getPageNum(), largeScreenCountParam.getPageSize());
//        LocalDateTime startTime = largeScreenCountParam.getStartTime().atStartOfDay();
//        LocalDateTime endTime = LocalDateTimeUtil.endOfDay(largeScreenCountParam.getEndTime().atStartOfDay());
        //页面查询只显示敏感客户
        largeScreenCountParam.setFiterSensitiveUser("1");
        List<Integer> deptslineIds = commGeneralService.getLineIdsByRedis(largeScreenCountParam.getDeptId());

        List<LedgerBaseInfoDTO> ledgerList = new ArrayList<>();
        List<PqUserLedgerPO> pqUserLedgerPOList = new ArrayList<>();
        List<PqUserLineAssPO> assList = new ArrayList<>();
        LambdaQueryWrapper<PqsEventdetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
//                .between(PqsEventdetail::getTimeid, startTime, endTime)
                .gt(PqsEventdetail::getPersisttime, msgEventConfigService.getEventDuration())
                .le(PqsEventdetail::getEventvalue, msgEventConfigService.getEventValue())
                .orderByDesc(PqsEventdetail::getTimeid);
        if(Objects.equals("1",largeScreenCountParam.getFiterSensitiveUser())){
            //查询重要敏感客户
            List<PqUserLedgerPO> poList = pqUserLedgerMapper.selectList(new LambdaQueryWrapper<PqUserLedgerPO>().select(PqUserLedgerPO::getId, PqUserLedgerPO::getCustomerName,PqUserLedgerPO::getIsShow).eq(PqUserLedgerPO::getIsShow, 1));
            List<String> userIds = poList.stream().map(PqUserLedgerPO::getId).collect(Collectors.toList());
            List<PqUserLineAssPO> pqUserLineAssPOS = pqUserLineAssMapper.selectList(new LambdaQueryWrapper<PqUserLineAssPO>().in(PqUserLineAssPO::getUserIndex, userIds));
            List<Integer> lineIds = pqUserLineAssPOS.stream().map(PqUserLineAssPO::getLineIndex).distinct().collect(Collectors.toList());
            deptslineIds.retainAll(lineIds);
        }

        if (Objects.nonNull(largeScreenCountParam.getEventtype())) {
            queryWrapper.eq(PqsEventdetail::getWavetype, largeScreenCountParam.getEventtype());
        } else {
            queryWrapper.in(PqsEventdetail::getWavetype, msgEventConfigService.getEventType());
        }
        if(Objects.nonNull(largeScreenCountParam.getStartTime())&&Objects.nonNull(largeScreenCountParam.getEndTime())){
                    LocalDateTime startTime = largeScreenCountParam.getStartTime().atStartOfDay();
        LocalDateTime endTime = LocalDateTimeUtil.endOfDay(largeScreenCountParam.getEndTime().atStartOfDay());
            queryWrapper
                .between(PqsEventdetail::getTimeid, startTime, endTime);
        }
        if (Objects.nonNull(largeScreenCountParam.getStartDateTime())&&Objects.nonNull(largeScreenCountParam.getEndTDateime())) {
            queryWrapper.between(PqsEventdetail::getTimeid, largeScreenCountParam.getStartDateTime(),largeScreenCountParam.getEndTDateime());
        }

        if (Objects.nonNull(largeScreenCountParam.getEventDurationMin()) || Objects.nonNull(largeScreenCountParam.getEventDurationMax())) {
            queryWrapper.gt(Objects.nonNull(largeScreenCountParam.getEventDurationMin()), PqsEventdetail::getPersisttime, largeScreenCountParam.getEventDurationMin());
            queryWrapper.lt(Objects.nonNull(largeScreenCountParam.getEventDurationMax()), PqsEventdetail::getPersisttime, largeScreenCountParam.getEventDurationMax());
        }

        if (Objects.nonNull(largeScreenCountParam.getEventValueMin()) || Objects.nonNull(largeScreenCountParam.getEventValueMax())) {
            queryWrapper.gt(Objects.nonNull(largeScreenCountParam.getEventValueMin()), PqsEventdetail::getEventvalue, largeScreenCountParam.getEventValueMin());
            queryWrapper.lt(Objects.nonNull(largeScreenCountParam.getEventValueMax()), PqsEventdetail::getEventvalue, largeScreenCountParam.getEventValueMax());
        }

        if (StrUtil.isNotBlank(largeScreenCountParam.getSearchValue())) {
            LambdaQueryWrapper<PqUserLedgerPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.select(PqUserLedgerPO::getId, PqUserLedgerPO::getCustomerName);
            lambdaQueryWrapper.like(PqUserLedgerPO::getCustomerName, largeScreenCountParam.getSearchValue());
            List<Integer> lineTemUserIds = new ArrayList<>();
            pqUserLedgerPOList = pqUserLedgerMapper.selectList(lambdaQueryWrapper);
            if (CollUtil.isNotEmpty(pqUserLedgerPOList)) {
                List<String> userIds = pqUserLedgerPOList.stream().map(PqUserLedgerPO::getId).collect(Collectors.toList());
                assList = pqUserLineAssMapper.selectList(new LambdaQueryWrapper<PqUserLineAssPO>().in(PqUserLineAssPO::getUserIndex, userIds));
                List<Integer> assIds = assList.stream().map(PqUserLineAssPO::getLineIndex).distinct().collect(Collectors.toList());
                lineTemUserIds = deptslineIds.stream().filter(assIds::contains).collect(Collectors.toList());
            }

            ledgerList = pqLineService.getBaseLedger(deptslineIds, largeScreenCountParam.getSearchValue());
            lineTemUserIds.addAll(ledgerList.stream().map(LedgerBaseInfoDTO::getLineId).collect(Collectors.toList()));
            if (CollUtil.isEmpty(lineTemUserIds)) {
                return new Page<>();
            }
            if (lineTemUserIds.size() > 1000) {
                List<List<Integer>> idPartitions = CollUtil.split(lineTemUserIds, 1000);
                queryWrapper.and(ew -> {
                    for (List<Integer> pList : idPartitions) {
                        ew.or(w -> w.in(PqsEventdetail::getLineid, pList));
                    }
                });
            } else {
                queryWrapper.in(PqsEventdetail::getLineid, lineTemUserIds);
            }

        } else {
            if (deptslineIds.size() > 1000) {
                List<List<Integer>> idPartitions = CollUtil.split(deptslineIds, 1000);
                queryWrapper.and(ew -> {
                    for (List<Integer> pList : idPartitions) {
                        ew.or(w -> w.in(PqsEventdetail::getLineid, pList));
                    }
                });
            } else {
                queryWrapper.in(PqsEventdetail::getLineid, deptslineIds);
            }
        }

        IPage<PqsEventdetail> list = pqsEventdetailService.getBaseMapper().selectPage(pqsEventdetailPage, queryWrapper);
        if (CollUtil.isEmpty(list.getRecords())) {
            return new Page<>();
        }
        List<Integer> pageLineIds = list.getRecords().stream().map(PqsEventdetail::getLineid).distinct().collect(Collectors.toList());
        List<LedgerBaseInfoDTO> pageLedger = pqLineService.getBaseLedger(pageLineIds, null);
        Map<Integer, LedgerBaseInfoDTO> ledgerBaseInfoDTOMap = pageLedger.stream().collect(Collectors.toMap(LedgerBaseInfoDTO::getLineId, Function.identity()));

        List<PqUserLineAssPO> assLastList = pqUserLedgerMapper.getUserByParam(pageLineIds, null);
        Map<Integer, List<String>> mapObj = assLastList.stream().collect(Collectors.groupingBy(PqUserLineAssPO::getLineIndex, Collectors.mapping(PqUserLineAssPO::getUserName, Collectors.toList())));

        List<EventDetailVO> collect = list.getRecords().stream().map(temp -> {
            EventDetailVO eventDetailVO = new EventDetailVO();
            eventDetailVO.setEventdetail_index(temp.getEventdetailIndex());
            eventDetailVO.setTimeid(temp.getTimeid());
            eventDetailVO.setMs(temp.getMs());
            eventDetailVO.setWavetype(temp.getWavetype().toString());
            eventDetailVO.setPersisttime(BigDecimal.valueOf(temp.getPersisttime() / 1000).setScale(3, RoundingMode.HALF_UP).toString());
            eventDetailVO.setEventvalue(temp.getEventvalue());
            eventDetailVO.setLookFlag(temp.getLookFlag());
            eventDetailVO.setNoticeFlag(temp.getNoticeFlag());
            if (ledgerBaseInfoDTOMap.containsKey(temp.getLineid())) {
                LedgerBaseInfoDTO ledgerBaseInfoDTO = ledgerBaseInfoDTOMap.get(temp.getLineid());
                eventDetailVO.setLineid(ledgerBaseInfoDTO.getLineId());
                eventDetailVO.setPointname(ledgerBaseInfoDTO.getLineName());
                eventDetailVO.setBdname(ledgerBaseInfoDTO.getStationName());
                eventDetailVO.setGdName(ledgerBaseInfoDTO.getGdName());
                eventDetailVO.setBusName(ledgerBaseInfoDTO.getBusBarName());
                eventDetailVO.setObjName(ledgerBaseInfoDTO.getObjName());
            }
            String objName = "/";
            if (mapObj.containsKey(eventDetailVO.getLineid())) {
                objName = String.join(";", mapObj.get(eventDetailVO.getLineid()));
            }
            eventDetailVO.setObjName(objName);
            return eventDetailVO;
        }).collect(Collectors.toList());
        Page<EventDetailVO> returnpage = new Page<>(largeScreenCountParam.getPageNum(), largeScreenCountParam.getPageSize());
        returnpage.setRecords(collect);
        returnpage.setTotal(list.getTotal());
        return returnpage;
    }


    @Override
    public List<EventDetailVO> eventPageExport(LargeScreenCountParam largeScreenCountParam) {
        List<EventDetailVO> pqsEventdetailPage = new ArrayList<>();
        LocalDateTime startTime = LocalDateTime.parse(largeScreenCountParam.getSearchBeginTime(), DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN));
        LocalDateTime endTime = LocalDateTime.parse(largeScreenCountParam.getSearchEndTime(), DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN));

        List<Integer> deptslineIds = commGeneralService.getLineIdsByRedis(largeScreenCountParam.getDeptId());

        List<LedgerBaseInfoDTO> ledgerList = new ArrayList<>();
        List<PqUserLedgerPO> pqUserLedgerPOList = new ArrayList<>();
        List<PqUserLineAssPO> assList = new ArrayList<>();
        LambdaQueryWrapper<PqsEventdetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .between(PqsEventdetail::getTimeid, startTime, endTime)
                .gt(PqsEventdetail::getPersisttime, msgEventConfigService.getEventDuration())
                .le(PqsEventdetail::getEventvalue, msgEventConfigService.getEventValue())
                .orderByDesc(PqsEventdetail::getTimeid);

        if (Objects.nonNull(largeScreenCountParam.getEventtype())) {
            queryWrapper.eq(PqsEventdetail::getWavetype, largeScreenCountParam.getEventtype());
        } else {
            queryWrapper.in(PqsEventdetail::getWavetype, msgEventConfigService.getEventType());
        }

        if (Objects.nonNull(largeScreenCountParam.getEventDurationMin()) || Objects.nonNull(largeScreenCountParam.getEventDurationMax())) {
            queryWrapper.gt(Objects.nonNull(largeScreenCountParam.getEventDurationMin()), PqsEventdetail::getPersisttime, largeScreenCountParam.getEventDurationMin());
            queryWrapper.lt(Objects.nonNull(largeScreenCountParam.getEventDurationMax()), PqsEventdetail::getPersisttime, largeScreenCountParam.getEventDurationMax());
        }

        if (Objects.nonNull(largeScreenCountParam.getEventValueMin()) || Objects.nonNull(largeScreenCountParam.getEventValueMax())) {
            queryWrapper.gt(Objects.nonNull(largeScreenCountParam.getEventValueMin()), PqsEventdetail::getEventvalue, largeScreenCountParam.getEventValueMin());
            queryWrapper.lt(Objects.nonNull(largeScreenCountParam.getEventValueMax()), PqsEventdetail::getEventvalue, largeScreenCountParam.getEventValueMax());
        }

        if (StrUtil.isNotBlank(largeScreenCountParam.getSearchValue())) {
            LambdaQueryWrapper<PqUserLedgerPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.select(PqUserLedgerPO::getId, PqUserLedgerPO::getCustomerName);
            lambdaQueryWrapper.like(PqUserLedgerPO::getCustomerName, largeScreenCountParam.getSearchValue());
            List<Integer> lineTemUserIds = new ArrayList<>();
            pqUserLedgerPOList = pqUserLedgerMapper.selectList(lambdaQueryWrapper);
            if (CollUtil.isNotEmpty(pqUserLedgerPOList)) {
                List<String> userIds = pqUserLedgerPOList.stream().map(PqUserLedgerPO::getId).collect(Collectors.toList());
                assList = pqUserLineAssMapper.selectList(new LambdaQueryWrapper<PqUserLineAssPO>().in(PqUserLineAssPO::getUserIndex, userIds));
                List<Integer> assIds = assList.stream().map(PqUserLineAssPO::getLineIndex).distinct().collect(Collectors.toList());
                lineTemUserIds = deptslineIds.stream().filter(assIds::contains).collect(Collectors.toList());
            }

            ledgerList = pqLineService.getBaseLedger(deptslineIds, largeScreenCountParam.getSearchValue());
            lineTemUserIds.addAll(ledgerList.stream().map(LedgerBaseInfoDTO::getLineId).collect(Collectors.toList()));
            if (CollUtil.isEmpty(lineTemUserIds)) {
                return pqsEventdetailPage;
            }
            if (lineTemUserIds.size() > 1000) {
                List<List<Integer>> idPartitions = CollUtil.split(lineTemUserIds, 1000);
                queryWrapper.and(ew -> {
                    for (List<Integer> pList : idPartitions) {
                        ew.or(w -> w.in(PqsEventdetail::getLineid, pList));
                    }
                });
            } else {
                queryWrapper.in(PqsEventdetail::getLineid, lineTemUserIds);
            }

        } else {
            if (deptslineIds.size() > 1000) {
                List<List<Integer>> idPartitions = CollUtil.split(deptslineIds, 1000);
                queryWrapper.and(ew -> {
                    for (List<Integer> pList : idPartitions) {
                        ew.or(w -> w.in(PqsEventdetail::getLineid, pList));
                    }
                });
            } else {
                queryWrapper.in(PqsEventdetail::getLineid, deptslineIds);
            }
        }

        List<PqsEventdetail> list = pqsEventdetailService.getBaseMapper().selectList(queryWrapper);
        if (CollUtil.isEmpty(list)) {
            return pqsEventdetailPage;
        }
        List<Integer> pageLineIds = list.stream().map(PqsEventdetail::getLineid).distinct().collect(Collectors.toList());
        List<LedgerBaseInfoDTO> pageLedger = pqLineService.getBaseLedger(pageLineIds, null);
        Map<Integer, LedgerBaseInfoDTO> ledgerBaseInfoDTOMap = pageLedger.stream().collect(Collectors.toMap(LedgerBaseInfoDTO::getLineId, Function.identity()));

        List<PqUserLineAssPO> assLastList = pqUserLedgerMapper.getUserByParam(pageLineIds, null);
        Map<Integer, List<String>> mapObj = assLastList.stream().collect(Collectors.groupingBy(PqUserLineAssPO::getLineIndex, Collectors.mapping(PqUserLineAssPO::getUserName, Collectors.toList())));

        //字典信息
        PqsDicType pqsDicType = pqsDicTypeMapper.selectOne(new LambdaQueryWrapper<PqsDicType>().eq(PqsDicType::getDicTypeName, DicTypeEnum.VOLTAGE.getDicName()));
        List<PqsDicData> pqsDicDataList = pqsDicDataMapper.selectList(new LambdaQueryWrapper<PqsDicData>().eq(PqsDicData::getDicType, pqsDicType.getDicTypeIndex()));
        Map<String, PqsDicData> pqsDicDataMap = pqsDicDataList.stream().collect(Collectors.toMap(PqsDicData::getDicIndex, dic -> dic));


        pqsEventdetailPage = list.stream().map(temp -> {
            EventDetailVO eventDetailVO = new EventDetailVO();
            eventDetailVO.setEventdetail_index(temp.getEventdetailIndex());
            eventDetailVO.setTimeid(temp.getTimeid());
            eventDetailVO.setMs(temp.getMs());
            eventDetailVO.setWavetype(temp.getWavetype().toString());
            eventDetailVO.setPersisttime(BigDecimal.valueOf(temp.getPersisttime() / 1000).setScale(3, RoundingMode.HALF_UP).toString());
            eventDetailVO.setEventvalue(temp.getEventvalue());
            eventDetailVO.setLookFlag(temp.getLookFlag());
            eventDetailVO.setNoticeFlag(temp.getNoticeFlag());
            if (ledgerBaseInfoDTOMap.containsKey(temp.getLineid())) {
                LedgerBaseInfoDTO ledgerBaseInfoDTO = ledgerBaseInfoDTOMap.get(temp.getLineid());
                eventDetailVO.setLineid(ledgerBaseInfoDTO.getLineId());
                eventDetailVO.setPointname(ledgerBaseInfoDTO.getLineName());
                eventDetailVO.setBdname(ledgerBaseInfoDTO.getStationName());
                eventDetailVO.setGdName(ledgerBaseInfoDTO.getGdName());
                eventDetailVO.setBusName(ledgerBaseInfoDTO.getBusBarName());
                eventDetailVO.setObjName(ledgerBaseInfoDTO.getObjName());
                eventDetailVO.setBusVoltageLevel(pqsDicDataMap.get(ledgerBaseInfoDTO.getScale()).getDicName());

            }
            String objName = "/";
            if (mapObj.containsKey(eventDetailVO.getLineid())) {
                objName = String.join(";", mapObj.get(eventDetailVO.getLineid()));
            }
            eventDetailVO.setObjName(objName);
            return eventDetailVO;
        }).collect(Collectors.toList());

        return pqsEventdetailPage;
    }


    @Override
    public Page<DeviceDTO> devicePage(LargeScreenCountParam largeScreenCountParam) {
        TimeInterval timeInterval = new TimeInterval();
        log.info("开始查询：" + timeInterval.intervalMs() + "ms; " + timeInterval.intervalSecond() + "s");
        LocalDateTime startTime = largeScreenCountParam.getStartTime().atStartOfDay();
        LocalDateTime endTime = LocalDateTimeUtil.endOfDay(largeScreenCountParam.getEndTime().atStartOfDay());
        Page<DeviceDTO> pqsEventdetailPage = new Page<>(largeScreenCountParam.getPageNum(), largeScreenCountParam.getPageSize());
        List<PqLine> pqLineList = (List<PqLine>) redisUtil.getObjectByKey(NAME_KEY + StrUtil.DASHED + "pqLineList");


        List<Integer> deptslineIds = commGeneralService.getLineIdsByRedis(largeScreenCountParam.getDeptId());


        if (Objects.isNull(largeScreenCountParam.getGdIndex())) {
            pqLineList = pqLineList.stream().filter(temp -> deptslineIds.contains(temp.getLineIndex())).collect(Collectors.toList());
        } else {
            pqLineList = pqLineList.stream().filter(temp -> deptslineIds.contains(temp.getLineIndex()) && Objects.equals(temp.getGdIndex(), largeScreenCountParam.getGdIndex())).collect(Collectors.toList());
        }
        if (CollUtil.isEmpty(pqLineList)) {
            return new Page<>();
        }

        List<Integer> devIndexs = pqLineList.stream().map(PqLine::getDevIndex).distinct().collect(Collectors.toList());
        log.info("完成从redis获取信息：" + timeInterval.intervalMs() + "ms; " + timeInterval.intervalSecond() + "s");
        //在运总数

        LambdaQueryWrapper<PqDevice> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(largeScreenCountParam.getState())) {

            if (largeScreenCountParam.getState().equals("0")) {
                return new Page<>();
            }
        }
        if (StrUtil.isNotBlank(largeScreenCountParam.getDevName())) {
            lambdaQueryWrapper.like(StrUtil.isNotEmpty(largeScreenCountParam.getDevName()), PqDevice::getName, largeScreenCountParam.getDevName());
        }
        lambdaQueryWrapper.in(PqDevice::getDevIndex, devIndexs);

        List<PqDevice> pqDeviceList = pqDeviceService.list(lambdaQueryWrapper);

        log.info("完成设备查询sql：" + timeInterval.intervalMs() + "ms; " + timeInterval.intervalSecond() + "s");
        List<Integer> runDevList = pqDeviceList.stream().map(PqDevice::getDevIndex).collect(Collectors.toList());
        if (CollUtil.isEmpty(runDevList)) {
            return new Page<>();
        }

        List<PqsDicData> pqsDicDataList = pqsDicDataMapper.selectList(new LambdaQueryWrapper<PqsDicData>().eq(PqsDicData::getDicType, "cbb2de8a-87da-4ae9-a35c-aaab999c7bc7"));
        Map<String, PqsDicData> pqsDicDataMap = pqsDicDataList.stream().collect(Collectors.toMap(PqsDicData::getDicIndex, Function.identity()));

        List<Integer> bdList = new ArrayList<>();
        if (StrUtil.isNotBlank(largeScreenCountParam.getSearchValue())) {
            List<PqSubstation> substationList = pqSubstationMapper.selectList(new LambdaQueryWrapper<PqSubstation>().like(PqSubstation::getName, largeScreenCountParam.getSearchValue()));
            bdList = substationList.stream().map(PqSubstation::getSubIndex).collect(Collectors.toList());
        }

        Page<PqDevice> page = pqDeviceService.lambdaQuery().in(CollUtil.isNotEmpty(bdList), PqDevice::getSubIndex, bdList)
                .in(PqDevice::getDevIndex, runDevList).page(new Page<>(PageFactory.getPageNum(largeScreenCountParam), PageFactory.getPageSize(largeScreenCountParam)));
        log.info("完成设备部门查询：" + timeInterval.intervalMs() + "ms; " + timeInterval.intervalSecond() + "s");
        // pqsEventdetailPage =  pqDeviceService.selectDeviceDTOPage(pqsEventdetailPage,largeScreenCountParam.getSearchValue(),runDevList);
        log.info("完成设备分页查询sql：" + timeInterval.intervalMs() + "ms; " + timeInterval.intervalSecond() + "s");

        List<PqDevice> deviceDTOList = page.getRecords();
        if (!CollectionUtils.isEmpty(deviceDTOList)) {

            //临时处理
            deviceDTOList.forEach(it -> it.setStatus(1));

            List<Integer> devIds = deviceDTOList.stream().map(PqDevice::getDevIndex).collect(Collectors.toList());
            log.info("在线率查询sql开始：" + timeInterval.intervalMs() + "ms; " + timeInterval.intervalSecond() + "s");
            List<PqsOnlinerate> onlineList = pqsOnlinerateService.lambdaQuery().in(PqsOnlinerate::getDevIndex, devIds).between(PqsOnlinerate::getTimeid, startTime, endTime).list();
            log.info("在线率查询sql结束：" + timeInterval.intervalMs() + "ms; " + timeInterval.intervalSecond() + "s");

            List<PqLine> inteList = pqLineList.stream().filter(it -> devIds.contains(it.getDevIndex())).collect(Collectors.toList());
            Map<Integer, List<Integer>> lineMap = inteList.stream().collect(Collectors.groupingBy(PqLine::getDevIndex, Collectors.mapping(PqLine::getLineIndex, Collectors.toList())));
            List<Integer> inteIds = inteList.stream().map(PqLine::getLineIndex).collect(Collectors.toList());

            Map<Integer, Double> inteDevMap = new HashMap<>();
            log.info("完整性查询sql开始：" + timeInterval.intervalMs() + "ms; " + timeInterval.intervalSecond() + "s");
            List<PqsIntegrity> pqsIntegrityList = pqsIntegrityMapper.selectList(new LambdaQueryWrapper<PqsIntegrity>().in(PqsIntegrity::getLineIndex, inteIds).between(PqsIntegrity::getTimeID, startTime, endTime));
            log.info("完整性查询sql结束：" + timeInterval.intervalMs() + "ms; " + timeInterval.intervalSecond() + "s");
            lineMap.forEach((dev, lineList) -> {
                double rate = pqsIntegrityList.stream().filter(it -> lineList.contains(it.getLineIndex())).mapToDouble(it -> it.getReal() * 1.0 / (it.getDue())).average().orElse(0.0);
                inteDevMap.put(dev, rate);
            });

            List<PqDeviceDetail> deviceDetailList = pqDeviceDetailMapper.selectList(new LambdaQueryWrapper<PqDeviceDetail>().in(PqDeviceDetail::getDevIndex, devIds));
            Map<Long, PqDeviceDetail> devMap = deviceDetailList.stream().collect(Collectors.toMap(PqDeviceDetail::getDevIndex, Function.identity()));

            List<Integer> gdIds = deviceDTOList.stream().map(PqDevice::getGdIndex).collect(Collectors.toList());
            List<PqGdCompany> pqGdCompanyList = pqGdCompanyMapper.selectList(new LambdaQueryWrapper<PqGdCompany>().in(PqGdCompany::getGdIndex, gdIds));
            Map<Long, PqGdCompany> gdMap = pqGdCompanyList.stream().collect(Collectors.toMap(PqGdCompany::getGdIndex, Function.identity()));

            List<Integer> bdIds = deviceDTOList.stream().map(PqDevice::getSubIndex).collect(Collectors.toList());
            List<PqSubstation> substationList = pqSubstationMapper.selectList(new LambdaQueryWrapper<PqSubstation>().in(PqSubstation::getSubIndex, bdIds));
            Map<Integer, PqSubstation> bdMap = substationList.stream().collect(Collectors.toMap(PqSubstation::getSubIndex, Function.identity()));

            List<PqLine> lineList = pqLineList.stream().filter(it -> devIds.contains(it.getDevIndex())).collect(Collectors.toList());
            List<PqsDeptsline> deptslineList = pqsDeptslineService.lambdaQuery().in(PqsDeptsline::getLineIndex, lineList.stream().map(PqLine::getLineIndex).collect(Collectors.toList())).eq(PqsDeptsline::getSystype, sysTypeZt).list();

            Map<String, PqsDepts> pqsDeptsMap = pqsDeptsService.lambdaQuery().eq(PqsDepts::getState, 1).list().stream().collect(Collectors.toMap(PqsDepts::getDeptsIndex, Function.identity()));

            Map<Integer, List<PqsDeptsline>> map = deptslineList.stream().collect(Collectors.groupingBy(PqsDeptsline::getLineIndex));
            Map<Integer, String> temMap = new HashMap<>();
            map.forEach((lineId, deptline) -> {
                String deptName = deptline.stream().map(PqsDeptsline::getDeptsIndex).map(pqsDeptsMap::get).map(PqsDepts::getDeptsname).collect(Collectors.joining(";"));
                temMap.put(lineId, deptName);
            });

            lineList.forEach(it -> it.setDeptName(temMap.get(it.getLineIndex())));
            Map<Integer, List<PqLine>> pqLineMap = lineList.stream().collect(Collectors.groupingBy(PqLine::getDevIndex));

            List<DeviceDTO> result = new ArrayList<>();
            for (PqDevice pqDevice : deviceDTOList) {
                DeviceDTO dto = new DeviceDTO();
                dto.setDevId(pqDevice.getDevIndex());
                dto.setDevName(pqDevice.getName());
                dto.setIp(pqDevice.getIp());
                List<PqsOnlinerate> tempList = onlineList.stream().filter(temp -> Objects.equals(temp.getDevIndex(), pqDevice.getDevIndex())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(tempList)) {
                    double asDouble = tempList.stream().mapToDouble(temp -> (double) (temp.getOnlinemin() * 100) / (temp.getOfflinemin() + temp.getOnlinemin())).average().getAsDouble();
                    dto.setOnLineRate(new BigDecimal(asDouble).setScale(2, RoundingMode.UP).doubleValue());
                }
                dto.setIntegrityRate(inteDevMap.containsKey(pqDevice.getDevIndex()) ? BigDecimal.valueOf(inteDevMap.get(pqDevice.getDevIndex()) * 100).setScale(2, RoundingMode.UP).doubleValue() : 0);

                PqDeviceDetail pqDeviceDetail = devMap.get(pqDevice.getDevIndex().longValue());
                dto.setManufacturerName(pqDeviceDetail.getManufacturer());
                dto.setStatus(pqDevice.getStatus());
                dto.setRunFlag(pqDevice.getStatus());
                dto.setThisTimeCheck(pqDeviceDetail.getThisTimeCheck());
                dto.setNextTimeCheck(pqDeviceDetail.getNextTimeCheck());
                dto.setUpdateTime(pqDevice.getUpdatetime());
                dto.setGdName(gdMap.get(pqDevice.getGdIndex().longValue()).getName());
                dto.setStationName(bdMap.get(pqDevice.getSubIndex()).getName());
                dto.setLogonTime(pqDevice.getLogontime());
                dto.setDeptName(pqLineMap.get(pqDevice.getDevIndex()).get(0).getDeptName());

                if (pqsDicDataMap.containsKey(pqDeviceDetail.getManufacturer())) {
                    dto.setManufacturerName(pqsDicDataMap.get(pqDeviceDetail.getManufacturer()).getDicName());
                }
                result.add(dto);

            }
            pqsEventdetailPage.setRecords(result);
            pqsEventdetailPage.setTotal(page.getTotal());
        }
        log.info("所有程序结束：" + timeInterval.intervalMs() + "ms; " + timeInterval.intervalSecond() + "s");

        return pqsEventdetailPage;
    }
   /* @Override
    public Page<DeviceDTO> devicePage(LargeScreenCountParam largeScreenCountParam) {
        LocalDateTime startTime = largeScreenCountParam.getStartTime().atStartOfDay();
        LocalDateTime endTime = LocalDateTimeUtil.endOfDay(largeScreenCountParam.getEndTime().atStartOfDay());
        Page<DeviceDTO> pqsEventdetailPage = new Page<>(largeScreenCountParam.getPageNum(), largeScreenCountParam.getPageSize());
        List<PqLine> pqLineList = (List<PqLine>) redisUtil.getObjectByKey( NAME_KEY+ StrUtil.DASHED+"pqLineList");
        List<Integer> deptslineIds = (List<Integer>) redisUtil.getObjectByKey( NAME_KEY+ StrUtil.DASHED+largeScreenCountParam.getDeptId());


        if(Objects.isNull(largeScreenCountParam.getGdIndex())){
            pqLineList = pqLineList.stream().filter(temp->deptslineIds.contains(temp.getLineIndex())).collect(Collectors.toList());
        }else {
            pqLineList = pqLineList.stream().filter(temp->deptslineIds.contains(temp.getLineIndex()) && Objects.equals(temp.getGdIndex(),largeScreenCountParam.getGdIndex())).collect(Collectors.toList());
        }
        if(CollUtil.isEmpty(pqLineList)){
            return new Page<>();
        }

        List<Integer> devIndexs = pqLineList.stream().map(PqLine::getDevIndex).distinct().collect(Collectors.toList());
        //在运总数
        List<PqDevice> pqDeviceList = pqDeviceService.lambdaQuery().in(PqDevice::getDevIndex, devIndexs).eq(PqDevice::getDevflag, 0).list();
        List<Integer> runDevList = pqDeviceList.stream().map(PqDevice::getDevIndex).collect(Collectors.toList());

        pqsEventdetailPage =  pqDeviceService.selectDeviceDTOPage(pqsEventdetailPage,largeScreenCountParam.getSearchValue(),runDevList,largeScreenCountParam.getState());
        List<DeviceDTO> deviceDTOList = pqsEventdetailPage.getRecords();
        if(!CollectionUtils.isEmpty(deviceDTOList)){
            List<Integer> devIds = deviceDTOList.stream().map(DeviceDTO::getDevId).collect(Collectors.toList());
            List<PqsOnlinerate> list = pqsOnlinerateService.lambdaQuery().in(PqsOnlinerate::getDevIndex,devIds).between(PqsOnlinerate::getTimeid, startTime, endTime).list();

            List<PqLine> inteList = pqLineList.stream().filter(it->devIds.contains(it.getDevIndex())).collect(Collectors.toList());
            Map<Integer,List<Integer>> lineMap = inteList.stream().collect(Collectors.groupingBy(PqLine::getDevIndex,Collectors.mapping(PqLine::getLineIndex,Collectors.toList())));
            List<Integer> inteIds = inteList.stream().map(PqLine::getLineIndex).collect(Collectors.toList());

           Map<Integer,Double> inteDevMap = new HashMap<>();
            List<PqsIntegrity> pqsIntegrityList = pqsIntegrityMapper.selectList(new LambdaQueryWrapper<PqsIntegrity>().in(PqsIntegrity::getLineIndex,inteIds));
            lineMap.forEach((dev,lineList)->{
                double rate  = pqsIntegrityList.stream().filter(it->lineList.contains(it.getLineIndex())).mapToDouble(it->it.getReal()*1.0/(it.getDue()+it.getReal())).average().orElse(0.0);
                inteDevMap.put(dev,rate);
            });


            for (DeviceDTO record : pqsEventdetailPage.getRecords()) {
                List<PqsOnlinerate> tempList = list.stream().filter(temp -> Objects.equals(temp.getDevIndex(), record.getDevId())).collect(Collectors.toList());
                if(!CollectionUtils.isEmpty(tempList)){
                    double asDouble = tempList.stream().mapToDouble(temp -> {
                        return Double.valueOf(temp.getOnlinemin()*100) / (temp.getOfflinemin() + temp.getOnlinemin());
                    }).average().getAsDouble();
                    record.setOnLineRate(new BigDecimal(asDouble).setScale(2, RoundingMode.UP).doubleValue());
                    record.setIntegrityRate(inteDevMap.containsKey(record.getDevId())? new BigDecimal(inteDevMap.get(record.getDevId())*100).setScale(2,RoundingMode.UP).doubleValue():0);
                }

            }
        }


        return pqsEventdetailPage;
    }*/

    @Override
    public Page<EventDetailVO> userEventList(LargeScreenCountParam largeScreenCountParam) {
        Page<PqsEventdetail> pqsEventdetailPage = new Page<>(largeScreenCountParam.getPageNum(), largeScreenCountParam.getPageSize());

        List<String> eventIds = largeScreenCountParam.getEventIds();
        if (CollectionUtils.isEmpty(eventIds)) {
            return new Page<>();
        }


        QueryWrapper<PqsEventdetail> queryWrapper = new QueryWrapper<>();
        if (eventIds.size() > 1000) {
            List<List<String>> idPartitions = CollUtil.split(eventIds, 1000);

            queryWrapper.lambda()
                    .and(ew -> {
                        for (List<String> pList : idPartitions) {
                            ew.or(w -> w.in(PqsEventdetail::getEventdetailIndex, pList));
                        }
                    }).orderByDesc(PqsEventdetail::getTimeid);


        } else {
            queryWrapper.lambda()
                    .in(PqsEventdetail::getEventdetailIndex, eventIds)
                    .orderByDesc(PqsEventdetail::getTimeid);
        }
        IPage<PqsEventdetail> list = pqsEventdetailService.getBaseMapper().selectPage(pqsEventdetailPage, queryWrapper);
        List<Integer> indexIds = list.getRecords().stream().map(PqsEventdetail::getLineid).collect(Collectors.toList());
        List<LedgerBaseInfoDTO> pqLineList = pqLineService.getBaseLineInfo(indexIds);
        Map<Integer, LedgerBaseInfoDTO> ledgerBaseInfoDTOMap = pqLineList.stream().collect(Collectors.toMap(LedgerBaseInfoDTO::getLineId, Function.identity()));

        List<EventDetailVO> collect = list.getRecords().stream().map(temp -> {
            EventDetailVO eventDetailVO = new EventDetailVO();
            eventDetailVO.setEventdetail_index(temp.getEventdetailIndex());
            eventDetailVO.setTimeid(temp.getTimeid());
            eventDetailVO.setMs(temp.getMs());
            eventDetailVO.setWavetype(temp.getWavetype().toString());
            eventDetailVO.setPersisttime(BigDecimal.valueOf(temp.getPersisttime() / 1000).setScale(3, RoundingMode.HALF_UP).toString());
            eventDetailVO.setEventvalue(temp.getEventvalue());
            eventDetailVO.setLookFlag(temp.getLookFlag());
            eventDetailVO.setNoticeFlag(temp.getNoticeFlag());
            if (ledgerBaseInfoDTOMap.containsKey(temp.getLineid())) {
                LedgerBaseInfoDTO ledgerBaseInfoDTO = ledgerBaseInfoDTOMap.get(temp.getLineid());
                eventDetailVO.setLineid(ledgerBaseInfoDTO.getLineId());
                eventDetailVO.setPointname(ledgerBaseInfoDTO.getLineName());
                eventDetailVO.setBdname(ledgerBaseInfoDTO.getStationName());
                eventDetailVO.setGdName(ledgerBaseInfoDTO.getGdName());
                eventDetailVO.setBusName(ledgerBaseInfoDTO.getBusBarName());
                eventDetailVO.setObjName(ledgerBaseInfoDTO.getObjName());
            }
            return eventDetailVO;
        }).collect(Collectors.toList());
        Page<EventDetailVO> returnpage = new Page<>(largeScreenCountParam.getPageNum(), largeScreenCountParam.getPageSize());
        returnpage.setRecords(collect);
        returnpage.setTotal(list.getTotal());
        return returnpage;
    }

    private List<EventDetailVO> change(List<PqsEventdetail> list, List<MsgEventInfo> handleMsg) {
        List<EventDetailVO> result = new ArrayList<>();
        if (CollectionUtils.isEmpty(list)) {
            return result;
        }
        List<Integer> lineidList = list.stream().map(PqsEventdetail::getLineid).distinct().collect(Collectors.toList());


        List<LedgerBaseInfoDTO> pqLineList = pqLineService.getBaseLineInfo(lineidList);
        Map<Integer, LedgerBaseInfoDTO> ledgerBaseInfoDTOMap = pqLineList.stream().collect(Collectors.toMap(LedgerBaseInfoDTO::getLineId, Function.identity()));

        result = list.stream().map(temp -> {
            EventDetailVO eventDetailVO = new EventDetailVO();
            eventDetailVO.setEventdetail_index(temp.getEventdetailIndex());
            eventDetailVO.setTimeid(temp.getTimeid());
            eventDetailVO.setMs(temp.getMs());
            eventDetailVO.setWavetype(temp.getWavetype().toString());
            eventDetailVO.setPersisttime(BigDecimal.valueOf(temp.getPersisttime() / 1000).setScale(3, RoundingMode.HALF_UP).toString());
            eventDetailVO.setEventvalue(temp.getEventvalue());
            eventDetailVO.setLookFlag(temp.getLookFlag());
            eventDetailVO.setNoticeFlag(temp.getNoticeFlag());
            if (temp.getEventvalue() < 0.5) {
                eventDetailVO.setEventSeverity(1);
            } else {
                eventDetailVO.setEventSeverity(2);
            }
            eventDetailVO.setMsgEventInfoSize(handleMsg.stream().filter(msg -> Objects.equals(msg.getEventIndex(), temp.getEventdetailIndex())).count());
            if (ledgerBaseInfoDTOMap.containsKey(temp.getLineid())) {
                LedgerBaseInfoDTO ledgerBaseInfoDTO = ledgerBaseInfoDTOMap.get(temp.getLineid());
                eventDetailVO.setLineid(ledgerBaseInfoDTO.getLineId());
                eventDetailVO.setPointname(ledgerBaseInfoDTO.getLineName());
                eventDetailVO.setBdname(ledgerBaseInfoDTO.getStationName());
                eventDetailVO.setGdName(ledgerBaseInfoDTO.getGdName());
                eventDetailVO.setBusName(ledgerBaseInfoDTO.getBusBarName());
                eventDetailVO.setObjName(ledgerBaseInfoDTO.getObjName());
            }
            return eventDetailVO;
        }).collect(Collectors.toList());

        return result;
    }

    @Override
    public void exportLineData() {
        List<LedgerExcelDTO> ledgerExcelDTOList;
        List<LedgerBaseInfoDTO> ledgerBaseInfoDTOS = (List<LedgerBaseInfoDTO>)redisUtil.getObjectByKey(NAME_KEY + StrUtil.DASHED+"LedgerBaseInfoDTO");
        ledgerExcelDTOList = ledgerBaseInfoDTOS.stream().map(temp->{
            LedgerExcelDTO ledgerExcelDTO = new LedgerExcelDTO();
            BeanUtils.copyProperties(temp,ledgerExcelDTO);
            return ledgerExcelDTO;
        }).collect(Collectors.toList());

        if (CollectionUtil.isEmpty(ledgerExcelDTOList)) {
            ExcelUtil.exportExcel("台账数据.xls", "台账数据", LedgerExcelDTO.class, new ArrayList<>());
        } else {
            ExcelUtil.exportExcel("台账数据.xls", "台账数据", LedgerExcelDTO.class, ledgerExcelDTOList);
        }
    }




}
