package com.njcn.csharmonic.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.constant.LogInfo;
import com.njcn.csdevice.api.*;
import com.njcn.csdevice.constant.DataParam;
import com.njcn.csdevice.pojo.dto.CsLineDTO;
import com.njcn.csdevice.pojo.dto.DevDetailDTO;
import com.njcn.csdevice.pojo.po.Node;
import com.njcn.csdevice.pojo.vo.CsLedgerVO;
import com.njcn.csharmonic.api.PqGovernPlanFeignClient;
import com.njcn.csharmonic.mapper.CsEventPOMapper;
import com.njcn.csharmonic.mapper.CsEventUserPOMapper;
import com.njcn.csharmonic.param.CldWarnParam;
import com.njcn.csharmonic.param.CsEventUserQueryPage;
import com.njcn.csharmonic.param.CsEventUserQueryParam;
import com.njcn.csharmonic.pojo.dto.UnReadEventDto;
import com.njcn.csharmonic.pojo.po.CsEventPO;
import com.njcn.csharmonic.pojo.po.CsEventUserPO;
import com.njcn.csharmonic.pojo.po.PqGovernPlan;
import com.njcn.csharmonic.pojo.vo.EventDetailVO;
import com.njcn.csharmonic.pojo.vo.FrontWarnVo;
import com.njcn.csharmonic.pojo.vo.event.EventStatisticVO;
import com.njcn.csharmonic.service.CsEventUserPOService;
import com.njcn.csharmonic.utils.DataChangeUtil;
import com.njcn.influx.pojo.dto.EventDataSetDTO;
import com.njcn.influx.service.EvtDataService;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.api.DictTreeFeignClient;
import com.njcn.system.api.EleEvtFeignClient;
import com.njcn.system.api.EpdFeignClient;
import com.njcn.system.pojo.po.EleEpdPqd;
import com.njcn.system.pojo.po.EleEvtParm;
import com.njcn.system.pojo.po.SysDicTreePO;
import com.njcn.user.enums.AppRoleEnum;
import com.njcn.web.utils.RequestUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

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

/**
 * 
 * Description:
 * Date: 2023/9/4  15:15【需求编号】
 *
 * @author clam
 * @version V1.0.0
 */
@Service
@RequiredArgsConstructor
public class CsEventUserPOServiceImpl extends ServiceImpl<CsEventUserPOMapper, CsEventUserPO> implements CsEventUserPOService{

    private final DicDataFeignClient dicDataFeignClient;
    private final DictTreeFeignClient dictTreeFeignClient;
    private final CsLedgerFeignClient csLedgerFeignClient;
    private final EvtDataService evtDataService;
    private final EpdFeignClient epdFeignClient;
    private final EleEvtFeignClient eleEvtFeignClient;
    private final CsEventPOMapper csEventPOMapper;
    private final NodeFeignClient nodeFeignClient;
    private final CsDeviceUserFeignClient csDeviceUserFeignClient;
    private final CsCommTerminalFeignClient csCommTerminalFeignClient;
    private final CsLineFeignClient csLineFeignClient;
    private final PqGovernPlanFeignClient pqGovernPlanClient;

    @Override
    public Integer queryEventCount(CsEventUserQueryParam csEventUserQueryParam) {
        csEventUserQueryParam.setUserId(RequestUtil.getUserIndex());
        Integer integer = this.getBaseMapper().queryEventCount(csEventUserQueryParam);
        return integer;
    }

    @Override
    public List<UnReadEventDto> queryEngineeringEventCount(String userIndex) {
        return this.getBaseMapper().queryEngineeringEventCount(userIndex);
    }

    @Override
    public List<EventDetailVO> queryUserEventList(CsEventUserQueryParam csEventUserQueryParam) {
        csEventUserQueryParam.setUserId(RequestUtil.getUserIndex());
        String role = RequestUtil.getUserRole();
        Boolean flag =Boolean.TRUE;

        if(Objects.equals(role, LogInfo.UNKNOWN_ROLE)){
            return new ArrayList<>();
        }
        List<String> strings = JSONArray.parseArray(role, String.class);
        if(CollectionUtils.isEmpty(strings)){
            return new ArrayList<>();
        }
        role=strings.get(0);
        if( Objects.equals(role, AppRoleEnum.APP_VIP_USER.getCode())&&Objects.equals(csEventUserQueryParam.getType(),"3")){
            csEventUserQueryParam.setLevel("3");
        }
//        if( Objects.equals(role, AppRoleEnum.OPERATION_MANAGER.getCode())||Objects.equals(role, AppRoleEnum.ROOT.getCode())){
//            csEventUserQueryParam.setUserId(null);
//            flag = Boolean.FALSE;
//
//        }
//        if(CollectionUtil.isEmpty(csEventUserQueryParam.getTarget())&&Objects.equals(csEventUserQueryParam.getType(),"0")){
//            /*获取所有暂态事件类型*/
//            List<DictData> data = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.APP_EVENT.getCode()).getData();
//            List<String> collect = data.stream().map(DictData::getCode).collect(Collectors.toList());
//            csEventUserQueryParam.setTarget(collect);
//        }

        List<String> deviceId = new ArrayList<>();
        List<CsLedgerVO> data = csLedgerFeignClient.getDeviceTree().getData();

        List<String> collect = data.stream().map(CsLedgerVO::getChildren).
                flatMap(Collection::stream).
                map(CsLedgerVO::getChildren).
                flatMap(Collection::stream).
                map(CsLedgerVO::getChildren).
                flatMap(Collection::stream).
                map(CsLedgerVO::getId).
                collect(Collectors.toList());
        if (CollectionUtils.isEmpty(collect)){
            return  new ArrayList<>();
        }
        List<EventDetailVO>  list = this.getBaseMapper().queryUserEventList(csEventUserQueryParam,collect,flag);
           // 主要用于统计不关心详情，详情重分页查询获取
//        list.forEach(temp->{
//            DevDetailDTO devDetail = csLedgerFeignClient.queryDevDetail(temp.getDeviceId()).getData();
//            temp.setEquipmentName(devDetail.getEquipmentName());
//            temp.setProjectId(devDetail.getProjectId());
//            temp.setProjectName(devDetail.getProjectName());
//            temp.setEngineeringid(devDetail.getEngineeringid());
//            temp.setEngineeringName(devDetail.getEngineeringName());
//            EleEpdPqd data = epdFeignClient.findByName(temp.getTag()).getData();
//            temp.setShowName(data.getShowName());
//
//            if(Objects.equals(csEventUserQueryParam.getType(),"0")){
//                List<EleEvtParm> data1 = eleEvtFeignClient.queryByPid(data.getId()).getData();
//                List<EventDataSetDTO> eventDataSetDTOS = new ArrayList<>();
//                for (EleEvtParm eleEvtParm : data1) {
//                    EventDataSetDTO eventDataSetDTO = new EventDataSetDTO();
//                    BeanUtils.copyProperties(eleEvtParm,eventDataSetDTO);
//                    EventDataSetDTO evtData = evtDataService.getEventDataSet("evt_data", temp.getId(), eleEvtParm.getName());
//                    if (evtData == null) {
//                        eventDataSetDTO.setValue("-");
//                    }else {
//                        eventDataSetDTO.setValue(Optional.ofNullable(evtData.getValue()).orElse("-"));
//
//                    }
//
//                    eventDataSetDTOS.add(eventDataSetDTO);
//                }
//                temp.setDataSet(eventDataSetDTOS);
//
//                List<EventDataSetDTO> evtParamVVaDepth = eventDataSetDTOS.stream().
//                        filter(dataSetDTO -> Objects.equals(dataSetDTO.getName(), "Evt_Param_VVaDepth")).
//                        collect(Collectors.toList());
//                if(CollectionUtil.isEmpty(evtParamVVaDepth)){
//                    temp.setEvtParamVVaDepth("-");
//
//                }else {
//                    temp.setEvtParamVVaDepth(evtParamVVaDepth.get(0).getValue()+(Objects.isNull(evtParamVVaDepth.get(0).getUnit())?"":evtParamVVaDepth.get(0).getUnit()));
//
//                }
//
//                List<EventDataSetDTO> evtParamPosition = eventDataSetDTOS.stream().
//                        filter(dataSetDTO -> Objects.equals(dataSetDTO.getName(), "Evt_Param_Position")).
//                        collect(Collectors.toList());
//                if(CollectionUtil.isEmpty(evtParamPosition)){
//                    temp.setEvtParamPosition("-");
//
//                }else {
//                    temp.setEvtParamPosition(evtParamPosition.get(0).getValue()+(Objects.isNull(evtParamPosition.get(0).getUnit())?"":evtParamPosition.get(0).getUnit()));
//
//                }
//
//                List<EventDataSetDTO> evtParamTm = eventDataSetDTOS.stream().
//                        filter(dataSetDTO -> Objects.equals(dataSetDTO.getName(), "Evt_Param_Tm")).
//                        collect(Collectors.toList());
//                if(CollectionUtil.isEmpty(evtParamTm)){
//                    temp.setEvtParamTm("-");
//
//                }else {
//                    temp.setEvtParamTm(evtParamTm.get(0).getValue()+(Objects.isNull(evtParamTm.get(0).getUnit())?"":evtParamTm.get(0).getUnit()));
//
//                }
//
//                List<EventDataSetDTO> evtParamPhase = eventDataSetDTOS.stream().
//                        filter(dataSetDTO -> Objects.equals(dataSetDTO.getName(), "Evt_Param_Phase")).
//                        collect(Collectors.toList());
//                if(CollectionUtil.isEmpty(evtParamPhase)){
//                    temp.setEvtParamPhase("-");
//
//                }else {
//                    temp.setEvtParamPhase(evtParamPhase.get(0).getValue()+(Objects.isNull(evtParamPhase.get(0).getUnit())?"":evtParamPhase.get(0).getUnit()));
//
//                }
//
//            }
//
//        });


        return list;
    }

    @Override
    public void updateStatus(CsEventUserQueryParam csEventUserQueryParam) {
        csEventUserQueryParam.setUserId(RequestUtil.getUserIndex());
        //getEventIds传空一键已读
        if(CollectionUtil.isEmpty(csEventUserQueryParam.getEventIds())){
            //暂态数据和运行事件和之前一样逻辑
            if (Objects.equals(csEventUserQueryParam.getType(), "0") || Objects.equals(csEventUserQueryParam.getType(), "2")) {
                List<EventDetailVO> list = this.queryUserEventList(csEventUserQueryParam);
                if(!CollectionUtils.isEmpty(list)){
                    List<String> collect = list.stream().map(EventDetailVO::getId).collect(Collectors.toList());
                    this.lambdaUpdate().in(CsEventUserPO::getEventId,collect).
                            eq(CsEventUserPO::getUserId,csEventUserQueryParam.getUserId()).
                            set(CsEventUserPO::getStatus,1).update();
                }
            }
            //稳态
            else if (Objects.equals(csEventUserQueryParam.getType(), "1")) {
                List<String> harmonicList = csDeviceUserFeignClient.getIdList("1").getData();
                if (CollectionUtil.isNotEmpty(harmonicList)) {
                    this.lambdaUpdate().in(CsEventUserPO::getEventId,harmonicList).
                            eq(CsEventUserPO::getUserId,RequestUtil.getUserIndex()).
                            set(CsEventUserPO::getStatus,1).update();
                }
            }
            //运行告警
            else if (Objects.equals(csEventUserQueryParam.getType(), "3")) {
                List<String> alarmList = csDeviceUserFeignClient.getIdList("3").getData();
                if (CollectionUtil.isNotEmpty(alarmList)) {
                    this.lambdaUpdate().in(CsEventUserPO::getEventId,alarmList).
                            eq(CsEventUserPO::getUserId,RequestUtil.getUserIndex()).
                            set(CsEventUserPO::getStatus,1).update();
                }
            }
        } else {
            this.lambdaUpdate().in(CsEventUserPO::getEventId,csEventUserQueryParam.getEventIds()).
                    eq(CsEventUserPO::getUserId,csEventUserQueryParam.getUserId()).
                    set(CsEventUserPO::getStatus,1).update();
        }
    }

    @Override
    public Page<EventDetailVO> queryEventpage(CsEventUserQueryPage csEventUserQueryPage) {
        Page<EventDetailVO> returnpage = new Page<> (csEventUserQueryPage.getPageNum ( ), csEventUserQueryPage.getPageSize ( ));

        csEventUserQueryPage.setUserId(RequestUtil.getUserIndex());
        String role = RequestUtil.getUserRole();
        if(Objects.equals(role, LogInfo.UNKNOWN_ROLE)){
            return returnpage;
        }
        List<String> strings = JSONArray.parseArray(role, String.class);
        if(CollectionUtils.isEmpty(strings)){
            return returnpage;
        }
        role=strings.get(0);
        if( Objects.equals(role, AppRoleEnum.APP_VIP_USER.getCode())&&Objects.equals(csEventUserQueryPage.getType(),"3")){
            csEventUserQueryPage.setLevel("3");
        }

        List<CsLedgerVO> data = csLedgerFeignClient.lineTree().getData();
        if (CollectionUtils.isEmpty(data)) {
            return returnpage;
        }

        // 获取第一层节点（根节点），从第二层开始才是真正的工程
        List<CsLedgerVO> firstLevelNodes = new ArrayList<>();
        for (CsLedgerVO rootNode : data) {
            List<CsLedgerVO> children = rootNode.getChildren();
            if (CollectionUtil.isNotEmpty(children)) {
                firstLevelNodes.addAll(children);
            }
        }

        if (CollectionUtils.isEmpty(firstLevelNodes)) {
            return returnpage;
        }

        // 缓存查询条件到局部变量
        String engineeringId = csEventUserQueryPage.getEngineeringid();
        String projectId = csEventUserQueryPage.getProjectId();
        String deviceId = csEventUserQueryPage.getDeviceId();
        String lineId = csEventUserQueryPage.getLineId();

        // 从第二层开始遍历：工程 -> 项目 -> 设备 -> 监测点
        List<String> collect = new ArrayList<>();
        for (CsLedgerVO engineering : firstLevelNodes) {
            // 过滤工程
            if (StringUtil.isNotBlank(engineeringId)
                    && !Objects.equals(engineering.getId(), engineeringId)) {
                continue;
            }

            List<CsLedgerVO> projects = engineering.getChildren();
            if (CollectionUtils.isEmpty(projects)) {
                continue;
            }

            for (CsLedgerVO project : projects) {
                // 过滤项目
                if (StringUtil.isNotBlank(projectId)
                        && !Objects.equals(project.getId(), projectId)) {
                    continue;
                }

                List<CsLedgerVO> devices = project.getChildren();
                if (CollectionUtils.isEmpty(devices)) {
                    continue;
                }

                for (CsLedgerVO device : devices) {
                    // 过滤设备
                    if (StringUtil.isNotBlank(deviceId)
                            && !Objects.equals(device.getId(), deviceId)) {
                        continue;
                    }

                    // 如果传了监测点 ID，需要进一步过滤
                    if (StringUtil.isNotBlank(lineId)) {
                        List<CsLedgerVO> lines = device.getChildren();
                        if (CollectionUtil.isNotEmpty(lines)) {
                            boolean hasLine = lines.stream()
                                    .anyMatch(line -> Objects.equals(line.getId(), lineId));
                            if (hasLine) {
                                collect.add(device.getId());
                            }
                        }
                    } else {
                        // 没有传监测点 ID，直接添加设备 ID
                        collect.add(device.getId());
                    }
                }
            }
        }
        if (CollectionUtils.isEmpty(collect)) {
            return returnpage;
        }
        returnpage = this.getBaseMapper().queryEventpage(returnpage, csEventUserQueryPage, collect);
        if (CollectionUtil.isNotEmpty(returnpage.getRecords())) {
            List<String> ids = returnpage.getRecords().stream().map(EventDetailVO::getId).collect(Collectors.toList());
            List<CsEventUserPO> userEvents = this.queryEventListByUserId(RequestUtil.getUserIndex(),ids);
            returnpage.getRecords().forEach(temp -> {
                if (!Objects.equals(csEventUserQueryPage.getType(),"0")) {
                    temp.setStartTime2(temp.getStartTime());
                }
                //台账信息
                DevDetailDTO devDetail = csLedgerFeignClient.queryDevDetail(temp.getDeviceId()).getData();
                temp.setEquipmentName(devDetail.getEquipmentName());
                temp.setProjectId(devDetail.getProjectId());
                temp.setProjectName(devDetail.getProjectName());
                temp.setEngineeringid(devDetail.getEngineeringid());
                temp.setEngineeringName(devDetail.getEngineeringName());
                //设备类型
                SysDicTreePO po = dictTreeFeignClient.queryById(temp.getDevType()).getData();
                temp.setDevType(Objects.isNull(po)?null:po.getCode());
                //监测位置
                temp.setEvtParamPosition(Objects.equals(temp.getLocation(), "grid") ? "电网侧" : "负载侧");
                //暂态事件类型
                EleEpdPqd ele = epdFeignClient.findByName(temp.getTag()).getData();
                temp.setShowName(Objects.isNull(ele) ? temp.getTag() : ele.getShowName());
                temp.setCode(Objects.isNull(ele) ? null : ele.getDefaultValue());
                //匹配已读/未读状态
                temp.setStatus(userEvents.stream().filter(item1->item1.getEventId().equals(temp.getId())).findFirst().map(CsEventUserPO::getStatus).orElse(1));
            });
        }
        return returnpage;
    }

    @Override
    public Page<EventDetailVO> queryEventPageWeb(CsEventUserQueryPage csEventUserQueryPage) {
        Page<EventDetailVO> returnpage = new Page<> (csEventUserQueryPage.getPageNum ( ), csEventUserQueryPage.getPageSize ( ));
        List<String> devIds = new ArrayList<>();
        List<String> lineIds = new ArrayList<>();
        if (!Objects.isNull(csEventUserQueryPage.getIsDvr()) && csEventUserQueryPage.getIsDvr() == 1) {
            PqGovernPlan plan = pqGovernPlanClient.getById(csEventUserQueryPage.getDeviceId()).getData();
            if (Objects.isNull(plan)) {
                return returnpage;
            }
            String beforeId = plan.getGovernBefore();
            String afterId = plan.getGovernAfter();
            lineIds = Arrays.asList(beforeId, afterId);
            if (CollectionUtil.isEmpty(lineIds)) {
                return returnpage;
            }
        } else {
            List<CsLedgerVO> data = csLedgerFeignClient.getDeviceTree().getData();
            data = data.stream().filter(temp -> StringUtils.isEmpty(csEventUserQueryPage.getDeviceTypeName() )||
                    Objects.equals(temp.getName(), csEventUserQueryPage.getDeviceTypeName())).collect(Collectors.toList());
            //便携式设备和治理设备拆分
            List<CsLedgerVO> portableDevTree = data.stream().filter(temp -> Objects.equals(temp.getName(), DataParam.portableDev)).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(portableDevTree)){
                portableDevTree = portableDevTree.get(0).getChildren();
            }
            List<CsLedgerVO> governmentDevTree = data.stream().filter(temp -> Objects.equals(temp.getName(), DataParam.governmentDev)).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(governmentDevTree)){
                governmentDevTree = governmentDevTree.get(0).getChildren();
            }
            List<CsLedgerVO> cldDevTree = data.stream().filter(temp -> Objects.equals(temp.getName(), DataParam.cldDev)).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(cldDevTree)){
                cldDevTree = cldDevTree.get(0).getChildren();
            }
            if (ObjectUtil.isNull(csEventUserQueryPage.getDeviceId()) || StringUtils.isEmpty(csEventUserQueryPage.getDeviceId())) {
                //便携式就1层下边就是设备 这边给便携式设备添加了假的工程和项目，id是写死的
                List<String> portableDevIds = new ArrayList<>();
                if (Objects.equals(csEventUserQueryPage.getEngineeringid(),"1")
                        || Objects.equals(csEventUserQueryPage.getProjectId(),"2")
                        || (!ObjectUtil.isNull(csEventUserQueryPage.getLineId()) && !StringUtils.isEmpty(csEventUserQueryPage.getLineId()))) {
                    portableDevIds = portableDevTree.stream().map(CsLedgerVO::getId).filter(
                            id -> StringUtils.isEmpty(csEventUserQueryPage.getDeviceId()) ||
                                    Objects.equals(id, csEventUserQueryPage.getDeviceId())
                    ).collect(Collectors.toList());
                }
                List<String> governmentDevIds = governmentDevTree.stream().filter(temp->StringUtils.isEmpty(csEventUserQueryPage.getEngineeringid())||
                                Objects.equals(temp.getId(), csEventUserQueryPage.getEngineeringid()))
                        .map(CsLedgerVO::getChildren).flatMap(Collection::stream).filter(
                                temp->StringUtils.isEmpty(csEventUserQueryPage.getProjectId())||
                                        Objects.equals(temp.getId(), csEventUserQueryPage.getProjectId())
                        ).
                        map(CsLedgerVO::getChildren).flatMap(Collection::stream).filter(
                                temp->StringUtils.isEmpty(csEventUserQueryPage.getDeviceId())||
                                        Objects.equals(temp.getId(), csEventUserQueryPage.getDeviceId())
                        ).
                        map(CsLedgerVO::getId).
                        collect(Collectors.toList());
                List<String> cldDevIds = cldDevTree.stream().filter(temp->StringUtils.isEmpty(csEventUserQueryPage.getEngineeringid())||
                                Objects.equals(temp.getId(), csEventUserQueryPage.getEngineeringid()))
                        .map(CsLedgerVO::getChildren).flatMap(Collection::stream).filter(
                                temp->StringUtils.isEmpty(csEventUserQueryPage.getProjectId())||
                                        Objects.equals(temp.getId(), csEventUserQueryPage.getProjectId())
                        ).
                        map(CsLedgerVO::getChildren).flatMap(Collection::stream).filter(
                                temp->StringUtils.isEmpty(csEventUserQueryPage.getDeviceId())||
                                        Objects.equals(temp.getId(), csEventUserQueryPage.getDeviceId())
                        ).
                        map(CsLedgerVO::getId).
                        collect(Collectors.toList());

                devIds.addAll(portableDevIds);
                devIds.addAll(governmentDevIds);
                devIds.addAll(cldDevIds);
            } else {
                devIds.add(csEventUserQueryPage.getDeviceId());
            }
            if (CollectionUtils.isEmpty(devIds)){
                return returnpage;
            }
            if (!ObjectUtil.isNull(csEventUserQueryPage.getLineId()) && !StringUtils.isEmpty(csEventUserQueryPage.getLineId())) {
                lineIds.add(csEventUserQueryPage.getLineId());
            }
        }
        //获取tag
        if (Objects.equals(csEventUserQueryPage.getType(), "0")) {
            if (CollUtil.isNotEmpty(csEventUserQueryPage.getTarget())) {
                List<String> tag = DataChangeUtil.getTag(csEventUserQueryPage.getTarget());
                csEventUserQueryPage.setTarget(tag);
            }
        }
        //获取告警码
        String searchValue = csEventUserQueryPage.getSearchValue();
        if (StrUtil.isNotBlank(searchValue)) {
            List<EleEpdPqd> epdList = epdFeignClient.findListByCode(searchValue).getData();
            if (CollUtil.isNotEmpty(epdList)) {
                List<String> epdTagList = epdList.stream()
                        .map(EleEpdPqd::getName)
                        .collect(Collectors.toList());
                csEventUserQueryPage.setEpdTagList(epdTagList);
            }
        }
        //获取监测点电压等级
        List<CsLineDTO> list = csLineFeignClient.getAllLineDetail().getData();
        Map<String, CsLineDTO> map = list.stream().collect(Collectors.toMap(CsLineDTO::getLineId, temp -> temp));
        if (!Objects.isNull(csEventUserQueryPage.getIsDvr()) && csEventUserQueryPage.getIsDvr() == 1) {
            returnpage  = this.getBaseMapper().queryEventPageWebDvr(returnpage,csEventUserQueryPage,lineIds);
        } else {
            returnpage  = this.getBaseMapper().queryEventPageWeb(returnpage,csEventUserQueryPage,devIds,lineIds);
        }
        returnpage.getRecords().forEach(temp->{
            CsLineDTO dto = map.get(temp.getLineId());
            DevDetailDTO devDetail = csLedgerFeignClient.queryDevDetail(temp.getDeviceId()).getData();
            temp.setEquipmentName(devDetail.getEquipmentName());
            temp.setProjectId(devDetail.getProjectId());
            temp.setProjectName(devDetail.getProjectName());
            temp.setEngineeringid(devDetail.getEngineeringid());
            temp.setEngineeringName(devDetail.getEngineeringName());
            if (ObjectUtil.isNotNull(temp.getLineId())) {
                if (!Objects.isNull(dto)) {
                    temp.setLineVoltage(dto.getVolGrade());
                    if (!Objects.isNull(dto.getClDid()) && dto.getClDid() == 0) {
                        temp.setModuleNo("模块" + temp.getClDid());
                    }
                }
            }
            EleEpdPqd ele = epdFeignClient.findByName(temp.getTag()).getData();
            if (Objects.isNull(ele)) {
                temp.setShowName(temp.getTag());
                temp.setCode(temp.getCode());
            } else {
                temp.setShowName(ele.getShowName());
                temp.setCode(ele.getDefaultValue());
            }
            if(Objects.equals(csEventUserQueryPage.getType(),"0")){
                List<EleEvtParm> data1 = eleEvtFeignClient.queryByPid(ele.getId()).getData();
                List<EventDataSetDTO> eventDataSetDTOS = new ArrayList<>();
                for (EleEvtParm eleEvtParm : data1) {
                    EventDataSetDTO eventDataSetDTO = new EventDataSetDTO();
                    BeanUtils.copyProperties(eleEvtParm,eventDataSetDTO);
                    if (Objects.equals(eventDataSetDTO.getName(),"Evt_Param_Position")) {
                        continue;
                    }
                    EventDataSetDTO evtData = evtDataService.getEventDataSet("evt_data", temp.getId(), eleEvtParm.getName());
                    if (evtData == null) {
                        eventDataSetDTO.setValue("-");
                    }else {
                        eventDataSetDTO.setValue(Optional.ofNullable(evtData.getValue()).orElse("-"));
                    }
                    eventDataSetDTOS.add(eventDataSetDTO);
                }
                temp.setDataSet(eventDataSetDTOS);
                List<EventDataSetDTO> evtParamVVaDepth = eventDataSetDTOS.stream().
                        filter(dataSetDTO -> Objects.equals(dataSetDTO.getName(), "Evt_Param_VVaDepth")).
                        collect(Collectors.toList());
                if(CollectionUtil.isEmpty(evtParamVVaDepth)){
                    temp.setEvtParamVVaDepth("-");
                }else {
                    temp.setEvtParamVVaDepth(evtParamVVaDepth.get(0).getValue()+(Objects.isNull(evtParamVVaDepth.get(0).getUnit())?"":evtParamVVaDepth.get(0).getUnit()));
                }

                List<EventDataSetDTO> evtParamPosition = eventDataSetDTOS.stream().
                        filter(dataSetDTO -> Objects.equals(dataSetDTO.getName(), "Evt_Param_Position")).
                        collect(Collectors.toList());
                if(CollectionUtil.isEmpty(evtParamPosition)){
                    temp.setEvtParamPosition("-");
                }else {
                    temp.setEvtParamPosition(evtParamPosition.get(0).getValue());
                }
                if (Objects.equals(temp.getEvtParamPosition(),"-")) {
                    if (!Objects.isNull(temp.getLocation())) {
                        temp.setEvtParamPosition(Objects.equals(temp.getLocation(),"grid")?"电网侧":"负载侧");
                    }
                }

                List<EventDataSetDTO> evtParamTm = eventDataSetDTOS.stream().
                        filter(dataSetDTO -> Objects.equals(dataSetDTO.getName(), "Evt_Param_Tm")).
                        collect(Collectors.toList());
                if(CollectionUtil.isEmpty(evtParamTm)){
                    temp.setEvtParamTm("-");
                }else {
                    temp.setEvtParamTm(evtParamTm.get(0).getValue()+(Objects.isNull(evtParamTm.get(0).getUnit())?"":evtParamTm.get(0).getUnit()));
                }

                List<EventDataSetDTO> evtParamPhase = eventDataSetDTOS.stream().
                        filter(dataSetDTO -> Objects.equals(dataSetDTO.getName(), "Evt_Param_Phase")).
                        collect(Collectors.toList());
                if(CollectionUtil.isEmpty(evtParamPhase)){
                    temp.setEvtParamPhase("-");
                }else {
                    temp.setEvtParamPhase(evtParamPhase.get(0).getValue()+(Objects.isNull(evtParamPhase.get(0).getUnit())?"":evtParamPhase.get(0).getUnit()));
                }
            }
        });
        return returnpage;
    }

    @Override
    public Page<FrontWarnVo> getFrontWarnInfo(CldWarnParam baseParam) {
        Page<FrontWarnVo> result = new Page<>(baseParam.getPageNum(), baseParam.getPageSize());

        // 1. 获取全量节点并构建映射（始终保留全量map用于后续VO转换）
        List<Node> nodeList = nodeFeignClient.nodeAllList().getData();
        if (CollectionUtil.isEmpty(nodeList)) {
            return result;
        }
        Map<String, Node> nodeMap = nodeList.stream()
                .collect(Collectors.toMap(Node::getId, Function.identity(), (a, b) -> a));

        // 2. 提取搜索关键词，避免重复调用getter
        String searchValue = baseParam.getSearchValue();
        boolean hasSearchValue = StrUtil.isNotBlank(searchValue);
        // 3. 根据搜索词筛选出"名称/IP匹配"的节点ID（仅作为OR条件的一部分）
        List<String> matchedNodeIds;
        if (hasSearchValue) {
            matchedNodeIds = nodeList.stream()
                    .filter(item -> item.getName().contains(searchValue)

                            || item.getIp().contains(searchValue))
                    .map(Node::getId)
                    .collect(Collectors.toList());
        } else {
            matchedNodeIds = Collections.emptyList();
        }
        // 4. 全量节点ID（用于限定查询总范围，防止code LIKE查到无关设备）
        List<String> allNodeIds = nodeList.stream()
                .map(Node::getId)
                .collect(Collectors.toList());

        // 5. 构建查询条件
        LambdaQueryWrapper<CsEventPO> queryWrapper = new LambdaQueryWrapper<>();
        // 搜索条件下 deviceId 与 code 改为 OR 关系
        if (hasSearchValue) {
            if (CollectionUtil.isNotEmpty(matchedNodeIds)) {
                // 有匹配节点：(deviceId IN 匹配节点 OR code LIKE) AND deviceId IN 全部节点
                queryWrapper.in(CsEventPO::getDeviceId, allNodeIds)
                        .and(w -> w
                                .in(CsEventPO::getDeviceId, matchedNodeIds)
                                .or()
                                .like(CsEventPO::getCode, searchValue)
                        );
            } else {
                // 无匹配节点：仅靠 code LIKE，但仍限定在全部节点范围内
                queryWrapper.in(CsEventPO::getDeviceId, allNodeIds)
                        .and(w -> w.like(CsEventPO::getCode, searchValue));
            }
        } else {
            // 无搜索词：正常按全部节点查询
            queryWrapper.in(CsEventPO::getDeviceId, allNodeIds);
        }
        // 时间范围 & 类型固定条件
        queryWrapper.between(CsEventPO::getStartTime,
                        DateUtil.beginOfDay(DateUtil.parse(baseParam.getSearchBeginTime())).toString(),
                        DateUtil.endOfDay(DateUtil.parse(baseParam.getSearchEndTime())).toString())
                .eq(CsEventPO::getType, 4)
                .orderByDesc(CsEventPO::getStartTime);
        // 等级筛选
        if (StrUtil.isNotBlank(baseParam.getLevel())) {
            List<Integer> levelList = Arrays.stream(baseParam.getLevel().split(","))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(levelList)) {
                queryWrapper.in(CsEventPO::getLevel, levelList);
            }
        }

        // 6. 执行分页查询
        Page<CsEventPO> page = csEventPOMapper.selectPage(
                new Page<>(baseParam.getPageNum(), baseParam.getPageSize()), queryWrapper);
        // 7. 结果转换
        List<CsEventPO> records = page.getRecords();
        if (CollUtil.isEmpty(records)) {
            return result;
        }
        List<FrontWarnVo> frontWarnVos = records.stream().map(item -> {
            FrontWarnVo vo = new FrontWarnVo();
            // 填充节点信息（使用全量nodeMap，而非过滤后的列表）
            Node node = nodeMap.get(item.getDeviceId());
            item.setLineId(node != null ? node.getName() : null);
            item.setWavePath(node != null ? node.getIp() : null);
            // 事件等级映射: 4,5→3(DEBUG/NORMAL) | 6→2(WARN) | 7→1(ERROR)
            Integer level = item.getLevel();
            if (level == 4 || level == 5) {
                item.setLevel(3);
            } else if (level == 6) {
                item.setLevel(2);
            } else if (level == 7) {
                item.setLevel(1);
            }
            BeanUtils.copyProperties(item, vo);
            return vo;
        }).collect(Collectors.toList());

        result.setRecords(frontWarnVos);
        result.setTotal(page.getTotal());
        result.setPages(page.getPages());
        result.setCurrent(page.getCurrent());
        result.setSize(page.getSize());
        return result;
    }

//    @Override
//    public Page<FrontWarnVo> getFrontWarnInfo(CldWarnParam baseParam) {
//        Page<FrontWarnVo> result = new Page<>(baseParam.getPageNum(), baseParam.getPageSize());
//        Page<CsEventPO> page = new Page<>(baseParam.getPageNum(), baseParam.getPageSize());
//        List<Node> nodeList = nodeFeignClient.nodeAllList().getData();
//        Map<String, Node> nodeMap = new HashMap<>();
//
//        if (CollectionUtil.isNotEmpty(nodeList)) {
//            nodeMap = nodeList.stream().collect(Collectors.toMap(Node::getId, Function.identity()));
//            if (ObjectUtil.isNotNull(baseParam.getSearchValue()) || StringUtil.isNotBlank(baseParam.getSearchValue())) {
//                nodeList = nodeList.stream().filter(item-> item.getName().contains(baseParam.getSearchValue()) || item.getIp().contains(baseParam.getSearchValue())).collect(Collectors.toList());
//            }
//            if (CollectionUtil.isNotEmpty(nodeList)) {
//                List<String> nodeIds = nodeList.stream().map(Node::getId).collect(Collectors.toList());
//                LambdaQueryWrapper<CsEventPO> queryWrapper = new LambdaQueryWrapper<>();
//                queryWrapper.in(CsEventPO::getDeviceId, nodeIds)
//                        .between(CsEventPO::getStartTime,
//                                DateUtil.beginOfDay(DateUtil.parse(baseParam.getSearchBeginTime())).toString(),
//                                DateUtil.endOfDay(DateUtil.parse(baseParam.getSearchEndTime())).toString())
//                        .eq(CsEventPO::getType, 4)
//                        .like(StrUtil.isNotBlank(baseParam.getSearchValue()), CsEventPO::getCode, baseParam.getSearchValue())
//                        .orderByDesc(CsEventPO::getStartTime);
//                if (ObjectUtil.isNotNull(baseParam.getLevel()) && StringUtil.isNotBlank(baseParam.getLevel())) {
//                    List<Integer> levelList = Arrays.stream(baseParam.getLevel().split(","))
//                            .map(String::trim)
//                            .filter(s -> !s.isEmpty())
//                            .map(Integer::parseInt)
//                            .collect(Collectors.toList());
//                    queryWrapper.in(CsEventPO::getLevel, levelList);
//                }
//                page = csEventPOMapper.selectPage(page, queryWrapper);
//            }
//        }
//        List<CsEventPO> records = page.getRecords();
//        if (CollUtil.isNotEmpty(records)) {
//            List<FrontWarnVo> frontWarnVos = new ArrayList<>();
//            Map<String, Node> finalNodeMap = nodeMap;
//            page.getRecords().forEach(item->{
//                FrontWarnVo vo = new FrontWarnVo();
//                //这边将前置名称放进lineId字段；将前置IP放进wavePath字段；进程号使用clDid
//                Node node = finalNodeMap.get(item.getDeviceId());
//                item.setLineId(Objects.isNull(node) ? null : node.getName());
//                item.setWavePath(Objects.isNull(node) ? null : node.getIp());
//                //事件等级(1:Ⅰ级||ERROR 2:Ⅱ级||WARN 3:Ⅲ级||(DEBUG&&NORMAL))
//                if (item.getLevel() == 4 || item.getLevel() == 5) {
//                    item.setLevel(3);
//                } else if (item.getLevel() == 6) {
//                    item.setLevel(2);
//                } else if (item.getLevel() == 7) {
//                    item.setLevel(1);
//                }
//                BeanUtils.copyProperties(item, vo);
//                frontWarnVos.add(vo);
//            });
//            result.setRecords(frontWarnVos);
//            result.setTotal(page.getTotal());
//            result.setPages(page.getPages());
//            result.setCurrent(page.getCurrent());
//            result.setSize(page.getSize());
//        }
//        return result;
//    }

    @Override
    public List<CsEventUserPO> queryEventListByUserId(String userIndex, List<String> eventList) {
        LambdaQueryWrapper<CsEventUserPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CsEventUserPO::getUserId, userIndex).in(CsEventUserPO::getEventId, eventList);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public EventStatisticVO queryAppEventCounts(CsEventUserQueryPage csEventUserQueryPage) {
        EventStatisticVO result = new EventStatisticVO();
        csEventUserQueryPage.setUserId(RequestUtil.getUserIndex());
        String role = RequestUtil.getUserRole();
        if(Objects.equals(role, LogInfo.UNKNOWN_ROLE)){
            return result;
        }
        List<String> strings = JSONArray.parseArray(role, String.class);
        if(CollectionUtils.isEmpty(strings)){
            return result;
        }
        role=strings.get(0);
        if( Objects.equals(role, AppRoleEnum.APP_VIP_USER.getCode())&&Objects.equals(csEventUserQueryPage.getType(),"3")){
            csEventUserQueryPage.setLevel("3");
        }
        List<CsLedgerVO> data = csLedgerFeignClient.lineTree().getData();
        if (CollectionUtils.isEmpty(data)) {
            return result;
        }
        // 获取第一层节点（根节点），从第二层开始才是真正的工程
        List<CsLedgerVO> firstLevelNodes = new ArrayList<>();
        for (CsLedgerVO rootNode : data) {
            List<CsLedgerVO> children = rootNode.getChildren();
            if (CollectionUtil.isNotEmpty(children)) {
                firstLevelNodes.addAll(children);
            }
        }
        if (CollectionUtils.isEmpty(firstLevelNodes)) {
            return result;
        }
        // 缓存查询条件到局部变量
        String engineeringId = csEventUserQueryPage.getEngineeringid();
        String projectId = csEventUserQueryPage.getProjectId();
        String deviceId = csEventUserQueryPage.getDeviceId();
        String lineId = csEventUserQueryPage.getLineId();

        // 从第二层开始遍历：工程 -> 项目 -> 设备 -> 监测点
        List<String> collect = new ArrayList<>();
        for (CsLedgerVO engineering : firstLevelNodes) {
            // 过滤工程
            if (StringUtil.isNotBlank(engineeringId)
                    && !Objects.equals(engineering.getId(), engineeringId)) {
                continue;
            }

            List<CsLedgerVO> projects = engineering.getChildren();
            if (CollectionUtils.isEmpty(projects)) {
                continue;
            }

            for (CsLedgerVO project : projects) {
                // 过滤项目
                if (StringUtil.isNotBlank(projectId)
                        && !Objects.equals(project.getId(), projectId)) {
                    continue;
                }

                List<CsLedgerVO> devices = project.getChildren();
                if (CollectionUtils.isEmpty(devices)) {
                    continue;
                }

                for (CsLedgerVO device : devices) {
                    // 过滤设备
                    if (StringUtil.isNotBlank(deviceId)
                            && !Objects.equals(device.getId(), deviceId)) {
                        continue;
                    }

                    // 如果传了监测点 ID，需要进一步过滤
                    if (StringUtil.isNotBlank(lineId)) {
                        List<CsLedgerVO> lines = device.getChildren();
                        if (CollectionUtil.isNotEmpty(lines)) {
                            boolean hasLine = lines.stream()
                                    .anyMatch(line -> Objects.equals(line.getId(), lineId));
                            if (hasLine) {
                                collect.add(device.getId());
                            }
                        }
                    } else {
                        // 没有传监测点 ID，直接添加设备 ID
                        collect.add(device.getId());
                    }
                }
            }
        }
        if (CollectionUtils.isEmpty(collect)) {
            return result;
        } else {
            result = baseMapper.getEventCounts(csEventUserQueryPage.getStartTime(),csEventUserQueryPage.getEndTime(),collect);
        }
        return result;
    }
}
