package com.njcn.product.event.transientes.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.product.event.devcie.mapper.PqGdCompanyMapper;
import com.njcn.product.event.devcie.mapper.PqSubstationMapper;
import com.njcn.product.event.devcie.pojo.dto.LedgerBaseInfoDTO;
import com.njcn.product.event.devcie.pojo.po.*;
import com.njcn.product.event.devcie.service.PqLineService;
import com.njcn.product.event.devcie.service.PqsDeptslineService;
import com.njcn.product.event.transientes.mapper.PqUserLedgerMapper;
import com.njcn.product.event.transientes.mapper.PqUserLineAssMapper;
import com.njcn.product.event.transientes.mapper.PqsDicTreeMapper;
import com.njcn.product.event.transientes.pojo.DicTreeEnum;
import com.njcn.product.event.transientes.pojo.param.LargeScreenCountParam;
import com.njcn.product.event.transientes.pojo.po.*;
import com.njcn.product.event.transientes.pojo.vo.EventDetailVO;
import com.njcn.product.event.transientes.pojo.vo.UserLedgerStatisticVO;
import com.njcn.product.event.transientes.service.*;
import com.njcn.web.factory.PageFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author: cdf
 * @CreateTime: 2025-06-30
 * @Description:
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class EventRightServiceImpl implements EventRightService {


    private final PqUserLineAssMapper pqUserLineAssMapper;

    private final PqUserLedgerMapper pqUserLedgerMapper;

    private final PqsDicTreeMapper pqsDicTreeMapper;

    private final PqsEventdetailService pqsEventdetailService;

    private final MsgEventConfigService msgEventConfigService;

    private final PqLineService pqLineService;

    private final PqSubstationMapper pqSubstationMapper;
    private final CommGeneralService commGeneralService;

    private final PqGdCompanyMapper pqGdCompanyMapper;

    private final PqsDeptslineService pqsDeptslineService;

    private final PqsDeptsService pqsDeptsService;
    @Value("${SYS_TYPE_ZT}")
    private String sysTypeZt;



    @Override
    public UserLedgerStatisticVO userLedgerStatistic(LargeScreenCountParam param) {
        UserLedgerStatisticVO result = new UserLedgerStatisticVO();

        // 1. 获取字典树数据
        List<PqsDicTreePO> dicTreeList = getAllDicTrees();
        Map<String, PqsDicTreePO> treeMap = getDicTreeMap(dicTreeList);
        setResultIds(result, treeMap);

        // 2. 获取线路ID列表
        List<Integer> lineIds = commGeneralService.getLineIdsByDept(param);
        if (CollUtil.isEmpty(lineIds)) {
            return result;
        }

        // 3. 获取用户线路关联数据
        List<PqUserLineAssPO> assList = getUserLineAssociations(lineIds);
        if (CollUtil.isEmpty(assList)) {
            return result;
        }

        // 4. 获取用户台账信息
        Set<String> assUserIds = assList.stream()
                .map(PqUserLineAssPO::getUserIndex)
                .collect(Collectors.toSet());
        List<PqUserLedgerPO> userLedgers = getUserLedgers(new ArrayList<>(assUserIds),param,false);
        if (CollUtil.isEmpty(userLedgers)) {
            return result;
        }

        // 5. 获取事件和线路数据
        List<PqsEventdetail> events = getEventsInTimeRange(param, lineIds);
        List<PqLine> lines = getLines(lineIds);

        // 6. 按用户类型分组处理
        Map<String, List<PqUserLedgerPO>> userMap = userLedgers.stream()
                .collect(Collectors.groupingBy(PqUserLedgerPO::getBigObjType));

        // 7. 构建结果
        buildResult(result, treeMap, userMap, assList, events, lines,dicTreeList);

        return result;
    }


    private List<PqsDicTreePO> getAllDicTrees(){
        return pqsDicTreeMapper.selectList(new LambdaQueryWrapper<>());
    }

    private Map<String, PqsDicTreePO> getDicTreeMap(List<PqsDicTreePO> dicTreeList) {
        List<PqsDicTreePO> touList = dicTreeList.stream().filter(it -> Objects.equals(it.getCode(), DicTreeEnum.BJ_USER.getCode())||Objects.equals(it.getCode(), DicTreeEnum.OI_USER.getCode())||Objects.equals(it.getCode(), DicTreeEnum.OT_USER.getCode())).collect(Collectors.toList());
        Map<String, PqsDicTreePO> treeMap = touList.stream().collect(Collectors.toMap(PqsDicTreePO::getCode, Function.identity()));
        return treeMap;
    }

    private void setResultIds (UserLedgerStatisticVO result,Map<String, PqsDicTreePO> treeMap){
        treeMap.forEach((tree, obj) -> {
            if (tree.equals(DicTreeEnum.BJ_USER.getCode())) {
                result.setImportId(obj.getId());
            } else if (tree.equals(DicTreeEnum.OI_USER.getCode())) {
                result.setOtherImportId(obj.getId());
            } else if (tree.equals(DicTreeEnum.OT_USER.getCode())) {
                result.setOtherId(obj.getId());
            }
        });
    }


    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<PqsEventdetail> getEventsInTimeRange(LargeScreenCountParam param,List<Integer> lineIds){
        //查询时间段的暂降事件
        LambdaQueryWrapper<PqsEventdetail> eventQuery = new LambdaQueryWrapper<>();
        eventQuery.between(PqsEventdetail::getTimeid, DateUtil.parse(param.getSearchBeginTime()), DateUtil.endOfDay(DateUtil.parse(param.getSearchEndTime())))
                .in(PqsEventdetail::getWavetype, msgEventConfigService.getEventType())
                .le(PqsEventdetail::getEventvalue,msgEventConfigService.getEventValue())
                .gt(PqsEventdetail::getPersisttime,msgEventConfigService.getEventDuration());
        if (lineIds.size() > 1000) {
            List<List<Integer>> listLineIds = CollUtil.split(lineIds, 1000);
            eventQuery.and(w -> {
                for (List<Integer> ids : listLineIds) {
                    w.or(wIn -> wIn.in(PqsEventdetail::getLineid, ids));
                }
            });
        } else {
            eventQuery.in(PqsEventdetail::getLineid, lineIds);
        }
        List<PqsEventdetail>  eventdetailList = pqsEventdetailService.list(eventQuery);
        if(CollUtil.isNotEmpty(eventdetailList)){
            eventdetailList.forEach(it->it.setPersisttime(BigDecimal.valueOf(it.getPersisttime() / 1000).setScale(3,RoundingMode.HALF_UP).doubleValue()));
        }
        return eventdetailList;
    }

    private List<PqUserLedgerPO>  getUserLedgers(List<String> assUserIds,LargeScreenCountParam param,boolean queryFlag){
        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);
        }
        if(Objects.equals("1",param.getFiterSensitiveUser())){
            userWrapper.eq(PqUserLedgerPO::getIsShow,1);
        }
        if(queryFlag){
            if(StrUtil.isNotBlank(param.getBigObjType())){
                //对象大类不为空
                userWrapper.eq(PqUserLedgerPO::getBigObjType,param.getBigObjType());
            }
            if(StrUtil.isNotBlank(param.getSmallObjType())){
                //对象大类不为空
                userWrapper.eq(PqUserLedgerPO::getSmallObjType,param.getSmallObjType());
            }
            if(Objects.nonNull(param.getGdIndex())){
                userWrapper.eq(PqUserLedgerPO::getPowerSupplyArea,param.getGdIndex());
            }
            if(StrUtil.isNotBlank(param.getSearchValue())){
                userWrapper.like(PqUserLedgerPO::getCustomerName,param.getSearchValue());
            }
        }
        return pqUserLedgerMapper.selectList(userWrapper);
    }
    private List<PqLine> getLines(List<Integer> lineIds){
        LambdaQueryWrapper<PqLine> lineQuery = new LambdaQueryWrapper<>();
        if (lineIds.size() > 1000) {
            List<List<Integer>> listLineIds = CollUtil.split(lineIds, 1000);

            lineQuery.and(w -> {
                for (List<Integer> ids : listLineIds) {
                    w.or(wIn -> wIn.in(PqLine::getLineIndex, ids));
                }
            });
        } else {
            lineQuery.in(PqLine::getLineIndex, lineIds);
        }
        return pqLineService.list(lineQuery);
    }


    private void buildResult(UserLedgerStatisticVO result,Map<String, PqsDicTreePO> treeMap,Map<String, List<PqUserLedgerPO>> userMap,List<PqUserLineAssPO> assList,List<PqsEventdetail> eventdetailList, List<PqLine> lineList,List<PqsDicTreePO> dicTreePOList){
        List<UserLedgerStatisticVO.Inner> innerList = new ArrayList<>();
        Map<String,PqsDicTreePO> allTreeMap = dicTreePOList.stream().collect(Collectors.toMap(PqsDicTreePO::getId,dept->dept));

        treeMap.forEach((tree, obj) -> {
            //获取对象大类的用户
            List<PqUserLedgerPO> oneList = userMap.get(obj.getId());

            if (tree.equals(DicTreeEnum.BJ_USER.getCode())) {
                Integer[] count = getEventCount(oneList, assList, eventdetailList,true);
                result.setImportNum(count[0]);
                result.setImportDevNum(count[1]);
            } else if (tree.equals(DicTreeEnum.OI_USER.getCode())) {
                Integer[] count = getEventCount(oneList, assList, eventdetailList,true);
                result.setOtherImportNum(count[0]);
                result.setOtherImportDevNum(count[1]);
            } else if (tree.equals(DicTreeEnum.OT_USER.getCode())) {
                Integer[] count = getEventCount(oneList, assList, eventdetailList,true);
                result.setOtherNum(count[0]);
                result.setOtherDevNum(count[1]);
            }

            UserLedgerStatisticVO.Inner inner = new UserLedgerStatisticVO.Inner();
            inner.setName(obj.getName());

            inner.setCount(0);

            List<UserLedgerStatisticVO.Inner> childrenList = new ArrayList<>();
            if(CollUtil.isNotEmpty(oneList)) {
                Map<String, List<PqUserLedgerPO>> smallMap = oneList.stream().collect(Collectors.groupingBy(PqUserLedgerPO::getSmallObjType));
                smallMap.forEach((key, userList) -> {
                    UserLedgerStatisticVO.Inner item = new UserLedgerStatisticVO.Inner();
                    Integer[] count = getEventCount(userList, assList, eventdetailList, false);
                    item.setCount(count[0]);
                    item.setTreeId(key);
                    item.setParentId(obj.getId());
                    item.setName(allTreeMap.containsKey(key) ? allTreeMap.get(key).getName() : "/");
                    childrenList.add(item);
                });
                inner.setChildren(childrenList);
                innerList.add(inner);
            }
        });

        result.setInnerList(innerList);
    }


    private void buildResultClone(UserLedgerStatisticVO result,Map<String, PqsDicTreePO> treeMap,Map<String, List<PqUserLedgerPO>> userMap,List<PqUserLineAssPO> assList,List<PqsEventdetail> eventdetailList, List<PqLine> lineList,List<PqsDicTreePO> dicTreePOList){
        List<UserLedgerStatisticVO.Inner> innerList = new ArrayList<>();
        Map<String,PqsDicTreePO> allTreeMap = dicTreePOList.stream().collect(Collectors.toMap(PqsDicTreePO::getId,dept->dept));

        treeMap.forEach((tree, obj) -> {
            //获取对象大类的用户
            List<PqUserLedgerPO> oneList = userMap.get(obj.getId());
            if(CollUtil.isEmpty(oneList)){
                oneList = new ArrayList<>();
            }

            if (tree.equals(DicTreeEnum.BJ_USER.getCode())) {
                Integer[] count = getEventCount(oneList, assList, eventdetailList,true);
                result.setImportNum(oneList.size());
                result.setImportDevNum(count[1]);
            } else if (tree.equals(DicTreeEnum.OI_USER.getCode())) {
                Integer[] count = getEventCount(oneList, assList, eventdetailList,true);
                result.setOtherImportNum(oneList.size());
                result.setOtherImportDevNum(count[1]);
            } else if (tree.equals(DicTreeEnum.OT_USER.getCode())) {
                Integer[] count = getEventCount(oneList, assList, eventdetailList,true);
                result.setOtherNum(oneList.size());
                result.setOtherDevNum(count[1]);
            }

            UserLedgerStatisticVO.Inner inner = new UserLedgerStatisticVO.Inner();
            inner.setName(obj.getName());

            inner.setCount(0);

            List<UserLedgerStatisticVO.Inner> childrenList = new ArrayList<>();
            if(CollUtil.isNotEmpty(oneList)) {
                Map<String, List<PqUserLedgerPO>> smallMap = oneList.stream().collect(Collectors.groupingBy(PqUserLedgerPO::getSmallObjType));
                smallMap.forEach((key, userList) -> {
                    UserLedgerStatisticVO.Inner item = new UserLedgerStatisticVO.Inner();
                    Integer[] count = getEventCount(userList, assList, eventdetailList, false);
                    item.setCount(count[0]);
                    item.setTreeId(key);
                    item.setParentId(obj.getId());
                    item.setName(allTreeMap.containsKey(key) ? allTreeMap.get(key).getName() : "/");
                    childrenList.add(item);
                });
                inner.setChildren(childrenList);
                innerList.add(inner);
            }
        });

        result.setInnerList(innerList);
    }


/*    @Override
    public Page<EventDetailVO> rightEventOpen(LargeScreenCountParam param) {
        Page<EventDetailVO> result = new Page<>(PageFactory.getPageNum(param), PageFactory.getPageSize(param));

        // 1. 获取线路ID
        List<Integer> lineIds = commGeneralService.getLineIdsByRedis(param.getDeptId());
        if (CollUtil.isEmpty(lineIds)) {
            return result;
        }

        // 2. 获取用户线路关联
        List<PqUserLineAssPO> assList = getUserLineAssociations(lineIds);
        if (CollUtil.isEmpty(assList)) {
            return result;
        }

        // 3. 获取用户台账
        List<PqUserLedgerPO> userLedgers = getFilteredUserLedgers(assList, param);
        if (CollUtil.isEmpty(userLedgers)) {
            return result;
        }

        // 4. 获取事件数据
        List<Integer> lineUseList = assList.stream()
                .map(PqUserLineAssPO::getLineIndex)
                .distinct()
                .collect(Collectors.toList());

        Page<PqsEventdetail> eventPage = getEventsPage(param, lineUseList);
        if (CollUtil.isEmpty(eventPage.getRecords())) {
            return result;
        }

        // 5. 构建结果
        buildEventDetailResult(result, eventPage, assList, userLedgers);

        return result;
    }*/




    @Override
    public Page<EventDetailVO> rightEventOpen(LargeScreenCountParam param) {
        Page<EventDetailVO> result = new Page<>(PageFactory.getPageNum(param),PageFactory.getPageSize(param));
        List<Integer> deptLineIds = commGeneralService.getLineIdsByRedis(param.getDeptId());
        if(CollUtil.isEmpty(deptLineIds)){
            return result;
        }
        //页面查询只显示敏感客户
        param.setFiterSensitiveUser("1");

        LambdaQueryWrapper<PqLine> queryWrapper = new LambdaQueryWrapper<>();
        PqSubstation pqSubstation = null;
        if(Objects.nonNull(param.getBdId())){
            pqSubstation =  pqSubstationMapper.selectOne(new LambdaQueryWrapper<PqSubstation>().eq(PqSubstation::getSubIndex,param.getBdId()));
            if(Objects.isNull(pqSubstation)){
                return result;
            }
            queryWrapper.in(PqLine::getSubIndex, pqSubstation.getSubIndex());

        }
        PqGdCompany pqGdCompany = null;
        if(Objects.nonNull(param.getGdIndex())){
            pqGdCompany =  pqGdCompanyMapper.selectOne(new LambdaQueryWrapper<PqGdCompany>().eq(PqGdCompany::getGdIndex,param.getGdIndex()));
            if(Objects.isNull(pqGdCompany)){
                return result;
            }
            queryWrapper.in(PqLine::getGdIndex, pqGdCompany.getGdIndex());
        }

        if(Objects.nonNull(param.getBdId()) || Objects.nonNull(param.getGdIndex())) {

            if(deptLineIds.size()>1000){
                List<List<Integer>> assUserIdsList = CollUtil.split(deptLineIds, 1000);
                queryWrapper.and(w -> {
                    for (List<Integer> ids : assUserIdsList) {
                        w.or(wIn -> wIn.in(PqLine::getLineIndex, ids));
                    }
                });
            }else {
                queryWrapper.in(PqLine::getLineIndex, deptLineIds);
            }

            List<PqLine> pqLineList = pqLineService.list(queryWrapper);
            deptLineIds = pqLineList.stream().map(PqLine::getLineIndex).distinct().collect(Collectors.toList());
        }

        if(CollUtil.isEmpty(deptLineIds)){
            return result;
        }



        //获取用户监测点关系符合部门监测点的
        List<PqUserLineAssPO> assList = getUserLineAssociations(deptLineIds);
        if(CollUtil.isEmpty(assList)){
            return result;
        }
        List<String> userIds = assList.stream().map(PqUserLineAssPO::getUserIndex).distinct().collect(Collectors.toList());
        if(CollUtil.isEmpty(userIds)){
            return result;
        }
        //获取符合条件的用户
        List<PqUserLedgerPO> pqUserLedgerPOList =getUserLedgers(userIds,param,true);

        if(CollUtil.isEmpty(pqUserLedgerPOList)){
            return result;
        }
        Map<String,PqUserLedgerPO> pqMap = pqUserLedgerPOList.stream().collect(Collectors.toMap(PqUserLedgerPO::getId,Function.identity()));
        List<String> pUserIds = pqUserLedgerPOList.stream().map(PqUserLedgerPO::getId).collect(Collectors.toList());
        List<PqUserLineAssPO> assListLast  = assList.stream().filter(it->pUserIds.contains(it.getUserIndex())).collect(Collectors.toList());
        List<Integer> lineUseList = assListLast.stream().map(PqUserLineAssPO::getLineIndex).distinct().collect(Collectors.toList());

        //查询时间段的暂降事件
        LambdaQueryWrapper<PqsEventdetail> eventQuery = new LambdaQueryWrapper<>();
        eventQuery.between(PqsEventdetail::getTimeid, DateUtil.parse(param.getSearchBeginTime()), DateUtil.endOfDay(DateUtil.parse(param.getSearchEndTime())))
                .in(PqsEventdetail::getWavetype, msgEventConfigService.getEventType()).orderByDesc(PqsEventdetail::getTimeid)
                .le(PqsEventdetail::getEventvalue,msgEventConfigService.getEventValue())
                .gt(PqsEventdetail::getPersisttime,msgEventConfigService.getEventDuration());

        if (lineUseList.size() > 1000) {
            List<List<Integer>> listLineIds = CollUtil.split(lineUseList, 1000);
            eventQuery.and(w -> {
                for (List<Integer> ids : listLineIds) {
                    w.or(wIn -> wIn.in(PqsEventdetail::getLineid, ids));
                }
            });
        } else {
            eventQuery.in(PqsEventdetail::getLineid, lineUseList);
        }
        Page<PqsEventdetail> page = pqsEventdetailService.page(new Page<>(PageFactory.getPageNum(param),PageFactory.getPageSize(param)),eventQuery);
        List<PqsEventdetail> temResultList = page.getRecords();
        if(CollUtil.isEmpty(temResultList)){
            return result;
        }

        List<Integer> ids = temResultList.stream().map(PqsEventdetail::getLineid).distinct().collect(Collectors.toList());
        List<LedgerBaseInfoDTO> dtoList = pqLineService.getBaseLineInfo(ids);
        Map<Integer,LedgerBaseInfoDTO> lineMap = dtoList.stream().collect(Collectors.toMap(LedgerBaseInfoDTO::getLineId,Function.identity()));
        Map<Integer,List<String>> temMap = assListLast.stream().filter(it->ids.contains(it.getLineIndex())).collect(Collectors.groupingBy(PqUserLineAssPO::getLineIndex,Collectors.mapping(PqUserLineAssPO::getUserIndex,Collectors.toList())));

        List<EventDetailVO> resultList = new ArrayList<>();
        for(PqsEventdetail pqsEventdetail : temResultList){
            EventDetailVO eventDetailVO = new EventDetailVO();
            BeanUtil.copyProperties(pqsEventdetail,eventDetailVO);
            List<String> userTemIds = temMap.get(pqsEventdetail.getLineid());
            String objName = userTemIds.stream().map(it->pqMap.get(it).getCustomerName()).collect(Collectors.joining("; "));
            eventDetailVO.setObjName(objName);
            LedgerBaseInfoDTO dto = lineMap.get(pqsEventdetail.getLineid());
            eventDetailVO.setBdname(dto.getStationName());
            eventDetailVO.setGdName(dto.getGdName());
            eventDetailVO.setBusName(dto.getBusBarName());
            eventDetailVO.setLineid(dto.getLineId());
            eventDetailVO.setPointname(dto.getLineName());
            eventDetailVO.setEventdetail_index(pqsEventdetail.getEventdetailIndex());
            eventDetailVO.setDevName(dto.getDevName());
            eventDetailVO.setPersisttime(BigDecimal.valueOf(pqsEventdetail.getPersisttime() / 1000).setScale(3,RoundingMode.HALF_UP).toString());
            resultList.add(eventDetailVO);
        }
        result.setTotal(page.getTotal());
        result.setRecords(resultList);
        return result;
    }


    @Override
    public Page<EventDetailVO> rightEventOpenForDetail(LargeScreenCountParam param) {

        Page<EventDetailVO> result = new Page<>(PageFactory.getPageNum(param),PageFactory.getPageSize(param));

        //查询时间段的暂降事件
        LambdaQueryWrapper<PqsEventdetail> eventQuery = new LambdaQueryWrapper<>();
        eventQuery.between(PqsEventdetail::getTimeid, DateUtil.parse(param.getSearchBeginTime()), DateUtil.endOfDay(DateUtil.parse(param.getSearchEndTime())))
                .in(PqsEventdetail::getWavetype, msgEventConfigService.getEventType()).orderByDesc(PqsEventdetail::getTimeid)
                .le(PqsEventdetail::getEventvalue,msgEventConfigService.getEventValue())
                .gt(PqsEventdetail::getPersisttime,msgEventConfigService.getEventDuration())
                .in(PqsEventdetail::getEventdetailIndex,param.getEventIds());

        Page<PqsEventdetail> page = pqsEventdetailService.page(new Page<>(PageFactory.getPageNum(param),PageFactory.getPageSize(param)),eventQuery);
        List<PqsEventdetail> temResultList = page.getRecords();
        if(CollUtil.isEmpty(temResultList)){
            return result;
        }

        List<Integer> ids = temResultList.stream().map(PqsEventdetail::getLineid).distinct().collect(Collectors.toList());
        List<LedgerBaseInfoDTO> dtoList = pqLineService.getBaseLineInfo(ids);
        Map<Integer,LedgerBaseInfoDTO> lineMap = dtoList.stream().collect(Collectors.toMap(LedgerBaseInfoDTO::getLineId,Function.identity()));

        //获取用户监测点关系符合部门监测点的
        List<PqUserLineAssPO> assList = getUserLineAssociations(ids);
        if(CollUtil.isEmpty(assList)){
            return result;
        }
        List<String> userIds = assList.stream().map(PqUserLineAssPO::getUserIndex).distinct().collect(Collectors.toList());
        if(CollUtil.isEmpty(userIds)){
            return result;
        }
        Map<Integer,List<String>> temMap = assList.stream().collect(Collectors.groupingBy(PqUserLineAssPO::getLineIndex,Collectors.mapping(PqUserLineAssPO::getUserIndex,Collectors.toList())));

        //获取符合条件的用户
        List<PqUserLedgerPO> pqUserLedgerPOList =getUserLedgers(userIds,param,true);

        if(CollUtil.isEmpty(pqUserLedgerPOList)){
            return result;
        }
        Map<String,PqUserLedgerPO> pqMap = pqUserLedgerPOList.stream().collect(Collectors.toMap(PqUserLedgerPO::getId,Function.identity()));

        List<EventDetailVO> resultList = new ArrayList<>();
        for(PqsEventdetail pqsEventdetail : temResultList){
            EventDetailVO eventDetailVO = new EventDetailVO();
            BeanUtil.copyProperties(pqsEventdetail,eventDetailVO);
            List<String> userTemIds = temMap.get(pqsEventdetail.getLineid());
            String objName = userTemIds.stream().map(it->pqMap.get(it).getCustomerName()).collect(Collectors.joining("; "));
            eventDetailVO.setObjName(objName);
            LedgerBaseInfoDTO dto = lineMap.get(pqsEventdetail.getLineid());
            eventDetailVO.setBdname(dto.getStationName());
            eventDetailVO.setGdName(dto.getGdName());
            eventDetailVO.setBusName(dto.getBusBarName());
            eventDetailVO.setLineid(dto.getLineId());
            eventDetailVO.setPointname(dto.getLineName());
            eventDetailVO.setEventdetail_index(pqsEventdetail.getEventdetailIndex());
            eventDetailVO.setDevName(dto.getDevName());
            eventDetailVO.setPersisttime(BigDecimal.valueOf(pqsEventdetail.getPersisttime() / 1000).setScale(3,RoundingMode.HALF_UP).toString());
            resultList.add(eventDetailVO);
        }
        result.setTotal(page.getTotal());
        result.setRecords(resultList);
        return result;
    }

    @Override
    public Page<PqUserLedgerPO> rightEventDevOpen(LargeScreenCountParam param) {
        Page<PqUserLedgerPO> result = new Page<>(PageFactory.getPageNum(param),PageFactory.getPageSize(param));
        //页面查询只显示敏感客户
        param.setFiterSensitiveUser("1");
        List<Integer> lineIds = commGeneralService.getLineIdsByRedis(param.getDeptId());
        if(CollUtil.isEmpty(lineIds)){
            return result;
        }

        LambdaQueryWrapper<PqLine> queryWrapper = new LambdaQueryWrapper<>();
        PqSubstation pqSubstation = null;
        if(Objects.nonNull(param.getBdId())){
            pqSubstation =  pqSubstationMapper.selectOne(new LambdaQueryWrapper<PqSubstation>().eq(PqSubstation::getSubIndex,param.getBdId()));
            if(Objects.isNull(pqSubstation)){
                return result;
            }
            queryWrapper.in(PqLine::getSubIndex, pqSubstation.getSubIndex());

        }
        PqGdCompany pqGdCompany = null;
        if(Objects.nonNull(param.getGdIndex())){
            pqGdCompany =  pqGdCompanyMapper.selectOne(new LambdaQueryWrapper<PqGdCompany>().eq(PqGdCompany::getGdIndex,param.getGdIndex()));
            if(Objects.isNull(pqGdCompany)){
                return result;
            }
            queryWrapper.in(PqLine::getGdIndex, pqGdCompany.getGdIndex());
        }

        if(Objects.nonNull(param.getBdId()) || Objects.nonNull(param.getGdIndex())) {

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

            List<PqLine> pqLineList = pqLineService.list(queryWrapper);
            lineIds = pqLineList.stream().map(PqLine::getLineIndex).distinct().collect(Collectors.toList());
        }

        if(CollUtil.isEmpty(lineIds)){
            return result;
        }

        List<PqUserLineAssPO> assPOList =getUserLineAssociations(lineIds);
        if(CollUtil.isEmpty(assPOList)){
            return result;
        }

        List<String> userIds = assPOList.stream().map(PqUserLineAssPO::getUserIndex).distinct().collect(Collectors.toList());
        LambdaQueryWrapper<PqUserLedgerPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        if(userIds.size() > 1000){
           List<List<String>> userIdList = CollUtil.split(userIds,1000);
            lambdaQueryWrapper.and(ad->{
                for(List<String> ids : userIdList){
                    ad.or(o->o.in(PqUserLedgerPO::getId,ids));
                }
            });
        }else {
            lambdaQueryWrapper.in(PqUserLedgerPO::getId,userIds);
        }
        if(Objects.equals("1",param.getFiterSensitiveUser())){
            lambdaQueryWrapper.eq(PqUserLedgerPO::getIsShow,1);
        }
        if(StrUtil.isNotBlank(param.getBigObjType())){
            //对象大类不为空
            lambdaQueryWrapper.eq(PqUserLedgerPO::getBigObjType,param.getBigObjType());
        }
        if(StrUtil.isNotBlank(param.getSmallObjType())){
            //对象大类不为空
            lambdaQueryWrapper.eq(PqUserLedgerPO::getSmallObjType,param.getSmallObjType());
        }

        if(Objects.nonNull(param.getGdIndex())){
            lambdaQueryWrapper.eq(PqUserLedgerPO::getPowerSupplyArea,param.getGdIndex());
        }

        if(StrUtil.isNotBlank(param.getSearchValue())){
            lambdaQueryWrapper.eq(PqUserLedgerPO::getCustomerName,param.getSearchValue());
        }

        List<PqUserLedgerPO> userList = pqUserLedgerMapper.selectList(lambdaQueryWrapper);
        if(CollUtil.isEmpty(userList)){
            return result;
        }
        List<String> userTemIds = userList.stream().map(PqUserLedgerPO::getId).collect(Collectors.toList());

        List<PqUserLineAssPO> aassList = assPOList.stream().filter(it->userTemIds.contains(it.getUserIndex())).collect(Collectors.toList());
        List<Integer> ids = aassList.stream().map(PqUserLineAssPO::getLineIndex).distinct().collect(Collectors.toList());
        List<PqsEventdetail> eventdetailList = getEventsInTimeRange(param,ids);
        if(CollUtil.isEmpty(eventdetailList)){
            return result;
        }
        List<Integer> temLineIds = eventdetailList.stream().map(PqsEventdetail::getLineid).distinct().collect(Collectors.toList());
        List<String> lastUserList = aassList.stream().filter(it->temLineIds.contains(it.getLineIndex())).map(PqUserLineAssPO::getUserIndex).distinct().collect(Collectors.toList());

        Page<PqUserLedgerPO> page = pqUserLedgerMapper.selectPage(new Page<>(PageFactory.getPageNum(param),PageFactory.getPageSize(param)),new LambdaQueryWrapper<PqUserLedgerPO>().in(PqUserLedgerPO::getId,lastUserList).orderByAsc(PqUserLedgerPO::getSmallObjType,PqUserLedgerPO::getUpdateTime));
        if(CollUtil.isEmpty(page.getRecords())){
            return page;
        }

        List<String> lastIds = page.getRecords().stream().map(PqUserLedgerPO::getId).collect(Collectors.toList());
        List<PqUserLineAssPO> lastAssList = aassList.stream().filter(it->lastIds.contains(it.getUserIndex())).collect(Collectors.toList());

        List<Integer> monitorIds = lastAssList.stream().map(PqUserLineAssPO::getLineIndex).distinct().collect(Collectors.toList());
        List<PqLine> pqLineList = pqLineService.list(new LambdaQueryWrapper<PqLine>().in(PqLine::getLineIndex,monitorIds));

        List<PqSubstation> pqSubstationList  = pqSubstationMapper.selectList(new LambdaQueryWrapper<PqSubstation>().in(PqSubstation::getSubIndex,pqLineList.stream().map(PqLine::getSubIndex).collect(Collectors.toList())));
        Map<Integer,PqSubstation> subMap = pqSubstationList.stream().collect(Collectors.toMap(PqSubstation::getSubIndex,sub->sub));
        pqLineList.forEach(it->it.setSubName(subMap.get(it.getSubIndex()).getName()));

        Map<String,List<Integer>> objMap = lastAssList.stream().collect(Collectors.groupingBy(PqUserLineAssPO::getUserIndex,Collectors.mapping(PqUserLineAssPO::getLineIndex,Collectors.toList())));
        Map<String,List<PqLine>> lastMap = new HashMap<>();
        objMap.forEach((k,vList)->{
            lastMap.put(k,pqLineList.stream().filter(it->vList.contains(it.getLineIndex())).collect(Collectors.toList()));
        });
        page.getRecords().forEach(item-> {
            if(objMap.containsKey(item.getId())){
                List<PqsEventdetail> countObj = eventdetailList.stream().filter(it->objMap.get(item.getId()).contains(it.getLineid())).collect(Collectors.toList());
                item.setEventCount(countObj.size());
                item.setEventIds(countObj.stream().map(PqsEventdetail::getEventdetailIndex).collect(Collectors.toList()));

                if(param.getExportFlag()){
                    item.setEventList(countObj);
                    if(lastMap.containsKey(item.getId())){
                        List<PqLine> abList = lastMap.get(item.getId());
                       Map<Integer,PqLine> lineMap= abList.stream().collect(Collectors.toMap(PqLine::getLineIndex,Function.identity()));
                       for(PqsEventdetail pqsEventdetail:countObj){
                           if(lineMap.containsKey(pqsEventdetail.getLineid())){
                               PqLine pqLine = lineMap.get(pqsEventdetail.getLineid());
                               pqsEventdetail.setBusBarName(pqLine.getSubvName());
                               pqsEventdetail.setStationName(pqLine.getSubName());
                           }

                       }
                    }
                }

            }
            if(lastMap.containsKey(item.getId())){
                List<PqLine> abList = lastMap.get(item.getId());
                item.setSubstationName(abList.stream().map(PqLine::getSubName).distinct().collect(Collectors.joining(StrUtil.COMMA)));
                item.setInfo(abList.stream().map(items->items.getSubName()+"_"+items.getSubvName()).distinct().collect(Collectors.joining("; ")));
            }
        });
        return page;
    }



    @Override
    public List<UserLedgerStatisticVO.Inner> rightImportUser(LargeScreenCountParam param) {
        List<UserLedgerStatisticVO.Inner> result = new ArrayList<>();
        List<Integer> deptLineIds = commGeneralService.getLineIdsByRedis(param.getDeptId());
        if(CollUtil.isEmpty(deptLineIds)){
            return result;
        }

        List<PqUserLineAssPO> assPOList = getUserLineAssociations(deptLineIds);
        if(CollUtil.isEmpty(assPOList)){
            return result;
        }
        List<String> userIds = assPOList.stream().map(PqUserLineAssPO::getUserIndex).distinct().collect(Collectors.toList());

        LambdaQueryWrapper<PqUserLedgerPO> userQuery = new LambdaQueryWrapper<>();
        if(userIds.size() > 1000){
            List<List<String>> userIdList = CollUtil.split(userIds,1000);
            userQuery.and(ad->{
                for(List<String> ids : userIdList){
                    ad.or(o->o.in(PqUserLedgerPO::getId,ids));
                }
            });
        }else {
            userQuery.in(PqUserLedgerPO::getId,userIds);
        }
        userQuery.eq(PqUserLedgerPO::getIsShow,1);
        List<PqUserLedgerPO> poList = pqUserLedgerMapper.selectList(userQuery);
        if(CollUtil.isEmpty(poList)){
            return result;
        }

        List<String> ids = poList.stream().map(PqUserLedgerPO::getId).collect(Collectors.toList());
        List<PqUserLineAssPO> assTemList = assPOList.stream().filter(it->ids.contains(it.getUserIndex())).collect(Collectors.toList());

        //获取监测id,用于查询暂降表
        List<Integer> lineIds = assTemList.stream().map(PqUserLineAssPO::getLineIndex).distinct().collect(Collectors.toList());

        List<PqsEventdetail> eventList = pqsEventdetailService.lambdaQuery().
                in(PqsEventdetail::getLineid,lineIds)
                .in(PqsEventdetail::getWavetype,msgEventConfigService.getEventType())
                .gt(PqsEventdetail::getPersisttime,msgEventConfigService.getEventDuration())
                .le(PqsEventdetail::getEventvalue,msgEventConfigService.getEventValue())
                .between(PqsEventdetail::getTimeid,DateUtil.beginOfDay(DateUtil.parse(param.getSearchBeginTime())),DateUtil.endOfDay(DateUtil.parse(param.getSearchEndTime()))).list();
        if(CollUtil.isEmpty(eventList)){
            poList.forEach(item->{
                UserLedgerStatisticVO.Inner inner = new UserLedgerStatisticVO.Inner();
                inner.setCustomId(item.getId());
                inner.setName(item.getCustomerName());
                inner.setCount(0);
                result.add(inner);
            });
            return result;
        }

        Map<String,List<Integer>> assMap = assTemList.stream().collect(Collectors.groupingBy(PqUserLineAssPO::getUserIndex,Collectors.mapping(PqUserLineAssPO::getLineIndex,Collectors.toList())));
        poList.forEach(item->{
            UserLedgerStatisticVO.Inner inner = new UserLedgerStatisticVO.Inner();
            inner.setCustomId(item.getId());
            inner.setName(item.getCustomerName());
            List<Integer> LIds = assMap.get(item.getId());
            List<String> eventIds = eventList.stream().filter(it -> LIds.contains(it.getLineid())).map(PqsEventdetail::getEventdetailIndex).collect(Collectors.toList());
            inner.setEventList(eventIds);
            inner.setCount(eventIds.size());
            result.add(inner);
        });
        return result;
    }

    @Override
    public PqUserLedgerPO rightImportOpenDetail(LargeScreenCountParam param) {
        List<Integer> deptLineIds = commGeneralService.getLineIdsByRedis(param.getDeptId());
        if(CollUtil.isEmpty(deptLineIds)){
            return null;
        }

       PqUserLedgerPO po = pqUserLedgerMapper.selectOne(new LambdaQueryWrapper<PqUserLedgerPO>().eq(PqUserLedgerPO::getId,param.getSearchValue()));

        PqsDicTreePO pqsDicTreePO = pqsDicTreeMapper.selectOne(new LambdaQueryWrapper<PqsDicTreePO>().eq(PqsDicTreePO::getId,po.getSmallObjType()));
        po.setSmallObjType(pqsDicTreePO.getName());
       List<PqUserLineAssPO> pqUserLineAssPOS = pqUserLineAssMapper.selectList(new LambdaQueryWrapper<PqUserLineAssPO>().eq(PqUserLineAssPO::getUserIndex,po.getId()));
       List<PqUserLineAssPO> lastAss =  pqUserLineAssPOS.stream().filter(it->deptLineIds.contains(it.getLineIndex())).collect(Collectors.toList());

       List<Integer> lineIds =  lastAss.stream().map(PqUserLineAssPO::getLineIndex).collect(Collectors.toList());
       List<LedgerBaseInfoDTO> ledgerBaseInfoDTOList =  pqLineService.getBaseLedger(lineIds,null);
        po.setGdName(ledgerBaseInfoDTOList.stream().map(LedgerBaseInfoDTO::getGdName).distinct().collect(Collectors.joining(";")));
        po.setSubstationName(ledgerBaseInfoDTOList.stream().map(LedgerBaseInfoDTO::getStationName).distinct().collect(Collectors.joining(";")));
        po.setBusbarName(ledgerBaseInfoDTOList.stream().map(it->it.getStationName()+"_"+it.getBusBarName()).distinct().collect(Collectors.joining(";")));

        return po;
    }

    @Override
    public List<PqGdCompany> gdSelect() {
        return pqGdCompanyMapper.selectList(null);
    }

    @Override
    public List<PqSubstation> bdSelect() {
        return pqSubstationMapper.selectList(null);
    }

    private Integer[] getEventCount(List<PqUserLedgerPO> oneList, List<PqUserLineAssPO> assList, List<PqsEventdetail> pqsEventdetailList,boolean devFlag) {
        Integer[] count = new Integer[]{0, 0};
        //用户的id
        if(CollUtil.isNotEmpty(oneList)){
        List<String> userIds = oneList.stream().map(PqUserLedgerPO::getId).collect(Collectors.toList());
        //获取用户关联监测点
        List<Integer> lineTemIds = assList.stream().filter(it -> userIds.contains(it.getUserIndex())).map(PqUserLineAssPO::getLineIndex).distinct().collect(Collectors.toList());
        //用户的暂降事件次数
        List<PqsEventdetail> eventdetailList = pqsEventdetailList.stream().filter(it -> lineTemIds.contains(it.getLineid())).collect(Collectors.toList());
        count[0] = eventdetailList.size();
        if(devFlag) {
            List<Integer> lastLineIds = eventdetailList.stream().map(PqsEventdetail::getLineid).distinct().collect(Collectors.toList());
            List<String> userLastIds = assList.stream().filter(it->lastLineIds.contains(it.getLineIndex())).map(PqUserLineAssPO::getUserIndex).distinct().collect(Collectors.toList());
            long devCount = oneList.stream().filter(it->userLastIds.contains(it.getId())).count();
            count[1] = (int) devCount;
        }
        }else {
            oneList = new ArrayList<>();
        }
        return count;
    }

    @Override
    public UserLedgerStatisticVO userLedgerStatisticClone(LargeScreenCountParam param) {
        UserLedgerStatisticVO result = new UserLedgerStatisticVO();
        //页面查询只显示敏感客户
        param.setFiterSensitiveUser("1");
        // 1. 获取字典树数据
        List<PqsDicTreePO> dicTreeList = getAllDicTrees();
        Map<String, PqsDicTreePO> treeMap = getDicTreeMap(dicTreeList);
        setResultIds(result, treeMap);

        // 2. 获取线路ID列表
        List<Integer> lineIds = commGeneralService.getLineIdsByDept(param);
        if (CollUtil.isEmpty(lineIds)) {
            return result;
        }
        if(Objects.equals("1",param.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> templineIds = pqUserLineAssPOS.stream().map(PqUserLineAssPO::getLineIndex).distinct().collect(Collectors.toList());
            lineIds.retainAll(templineIds);
        }

        // 3. 获取用户线路关联数据
        List<PqUserLineAssPO> assList = getUserLineAssociations(lineIds);
        if (CollUtil.isEmpty(assList)) {
            return result;
        }

        // 4. 获取用户台账信息
        Set<String> assUserIds = assList.stream()
                .map(PqUserLineAssPO::getUserIndex)
                .collect(Collectors.toSet());
        List<PqUserLedgerPO> userLedgers = getUserLedgers(new ArrayList<>(assUserIds),param,false);
        if (CollUtil.isEmpty(userLedgers)) {
            return result;
        }

        // 5. 获取事件和线路数据
        List<PqsEventdetail> events = getEventsInTimeRange(param, lineIds);
        List<PqLine> lines = getLines(lineIds);

        // 6. 按用户类型分组处理
        Map<String, List<PqUserLedgerPO>> userMap = userLedgers.stream()
                .collect(Collectors.groupingBy(PqUserLedgerPO::getBigObjType));

        // 7. 构建结果
        buildResultClone(result, treeMap, userMap, assList, events, lines,dicTreeList);

        return result;
    }

    @Override
    public Page<PqUserLedgerPO> rightEventOpenClone(LargeScreenCountParam param) {
        Page<PqUserLedgerPO> result = new Page<>();

        // 2. 获取线路ID列表
        List<Integer> lineIds = commGeneralService.getLineIdsByDept(param);
        if (CollUtil.isEmpty(lineIds)) {
            return result;
        }
        //页面查询只显示敏感客户
        param.setFiterSensitiveUser("1");
        LambdaQueryWrapper<PqLine> queryWrapper = new LambdaQueryWrapper<>();
        PqSubstation pqSubstation = null;
        if(Objects.nonNull(param.getBdId())){
            pqSubstation =  pqSubstationMapper.selectOne(new LambdaQueryWrapper<PqSubstation>().eq(PqSubstation::getSubIndex,param.getBdId()));
            if(Objects.isNull(pqSubstation)){
                return result;
            }
            queryWrapper.in(PqLine::getSubIndex, pqSubstation.getSubIndex());

        }
        PqGdCompany pqGdCompany = null;
        if(Objects.nonNull(param.getGdIndex())){
            pqGdCompany =  pqGdCompanyMapper.selectOne(new LambdaQueryWrapper<PqGdCompany>().eq(PqGdCompany::getGdIndex,param.getGdIndex()));
            if(Objects.isNull(pqGdCompany)){
                return result;
            }
            queryWrapper.in(PqLine::getGdIndex, pqGdCompany.getGdIndex());
        }

        if(Objects.nonNull(param.getBdId()) || Objects.nonNull(param.getGdIndex())) {
            List<PqLine> pqLineList = pqLineService.list(queryWrapper);
            lineIds = pqLineList.stream().map(PqLine::getLineIndex).distinct().collect(Collectors.toList());
        }

        if(CollUtil.isEmpty(lineIds)){
            return result;
        }

        // 3. 获取用户线路关联数据
        List<PqUserLineAssPO> assList = getUserLineAssociations(lineIds);
        if (CollUtil.isEmpty(assList)) {
            return result;
        }

        LambdaQueryWrapper<PqUserLedgerPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByAsc(PqUserLedgerPO::getSmallObjType,PqUserLedgerPO::getUpdateTime);
        if(Objects.equals("1",param.getFiterSensitiveUser())){
            lambdaQueryWrapper.eq(PqUserLedgerPO::getIsShow,1);
        }
        if(StrUtil.isNotBlank(param.getBigObjType())){
            //对象大类不为空
            lambdaQueryWrapper.eq(PqUserLedgerPO::getBigObjType,param.getBigObjType());
        }
        if(StrUtil.isNotBlank(param.getSmallObjType())){
            //对象大类不为空
            lambdaQueryWrapper.eq(PqUserLedgerPO::getSmallObjType,param.getSmallObjType());
        }
        if(Objects.nonNull(param.getGdIndex())){
            lambdaQueryWrapper.eq(PqUserLedgerPO::getPowerSupplyArea,param.getGdIndex());
        }
        if(StrUtil.isNotBlank(param.getSearchValue())){
            lambdaQueryWrapper.like(PqUserLedgerPO::getCustomerName,param.getSearchValue());
        }
        List<String> assIds = assList.stream().map(PqUserLineAssPO::getUserIndex).distinct().collect(Collectors.toList());
        if(assIds.size()>1000){
            List<List<String>> userIds = CollUtil.split(assIds, 1000);
            lambdaQueryWrapper.and(w -> {
                for (List<String> ids : userIds) {
                    w.or(wIn -> wIn.in(PqUserLedgerPO::getId, ids));
                }
            });
        }else {
            lambdaQueryWrapper.in(PqUserLedgerPO::getId, assIds);
        }

        Page<PqUserLedgerPO> page = pqUserLedgerMapper.selectPage(new Page<>(PageFactory.getPageNum(param),PageFactory.getPageSize(param)),lambdaQueryWrapper);
        if(CollUtil.isEmpty(page.getRecords())){
            return result;
        }
        List<String> userIds = page.getRecords().stream().map(PqUserLedgerPO::getId).collect(Collectors.toList());
        List<PqUserLineAssPO> assPOList = assList.stream().filter(it->userIds.contains(it.getUserIndex())).collect(Collectors.toList());
        List<Integer> lineTemIds = assPOList.stream().map(PqUserLineAssPO::getLineIndex).distinct().collect(Collectors.toList());

        List<LedgerBaseInfoDTO> ledgerList = pqLineService.getBaseLedger(lineTemIds,null);

        List<PqsDeptsline> pqsDeptslineList = pqsDeptslineService.lambdaQuery().in(PqsDeptsline::getLineIndex,lineTemIds).eq(PqsDeptsline::getSystype,sysTypeZt).list();
//        Map<Integer,PqsDeptsline> deptLineMap = pqsDeptslineList.stream().collect(Collectors.toMap(PqsDeptsline::getLineIndex,dept->dept));
        Map<Integer,List<PqsDeptsline>> deptLineMap = pqsDeptslineList.stream().collect(Collectors.groupingBy(PqsDeptsline::getLineIndex));

        Map<Integer,List<String>> deptTemMap = new HashMap<>();
        List<PqsDepts> pqsDeptsList = pqsDeptsService.lambdaQuery().eq(PqsDepts::getState,1).list();
        Map<String,PqsDepts> deptMap = pqsDeptsList.stream().collect(Collectors.toMap(PqsDepts::getDeptsIndex,dept->dept));
        deptLineMap.forEach((k,v)->{
            deptTemMap.put(k,v.stream().map(PqsDeptsline::getDeptsIndex).map(deptMap::get).map(PqsDepts::getDeptsname).collect(Collectors.toList()));
        });

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

        for(PqUserLedgerPO po :page.getRecords()){
            if(assMap.containsKey(po.getId())){
                List<Integer> temIds = assMap.get(po.getId());
                List<LedgerBaseInfoDTO> temList = ledgerList.stream().filter(it->temIds.contains(it.getLineId())).collect(Collectors.toList());
                po.setGdName(temList.stream().map(LedgerBaseInfoDTO::getGdName).distinct().collect(Collectors.joining(";")));
                po.setStation(temList.stream().map(LedgerBaseInfoDTO::getStationName).distinct().collect(Collectors.joining(";")));
                po.setInfo(temList.stream().map(it->it.getStationName()+"_"+it.getBusBarName()).distinct().collect(Collectors.joining(";")));
//                po.setDeptName(temList.stream().map(LedgerBaseInfoDTO::getLineId).distinct().map(deptTemMap::get).distinct().collect(Collectors.joining(";")));
                po.setDeptName(temList.stream().map(LedgerBaseInfoDTO::getLineId).distinct().map(deptTemMap::get).flatMap(Collection::stream).distinct().collect(Collectors.joining(";")));

            }

        }

        return page;
    }

}
