package com.njcn.product.diagram.LedgerScale.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.oss.utils.FileStorageUtil;
import com.njcn.product.advance.eventSource.mapper.RmpEventDetailAssMapper;
import com.njcn.product.advance.eventSource.pojo.po.RmpEventDetailAssPO;
import com.njcn.product.advance.harmonicUp.mapper.UpHarmonicDetailMapper;
import com.njcn.product.advance.harmonicUp.pojo.po.UpHarmonicDetail;
import com.njcn.product.advance.responsility.mapper.RespDataResultMapper;
import com.njcn.product.advance.responsility.pojo.dto.CustomerResponsibility;
import com.njcn.product.advance.responsility.pojo.po.RespDataResult;
import com.njcn.product.cnzutai.zutai.pojo.po.CsConfigurationPO;
import com.njcn.product.cnzutai.zutai.pojo.po.CsSubConfigurationAss;
import com.njcn.product.cnzutai.zutai.service.CsConfigurationService;
import com.njcn.product.cnzutai.zutai.service.CsSubConfigurationAssService;
import com.njcn.product.diagram.LedgerScale.pojo.dto.EventSourceDTO;
import com.njcn.product.diagram.LedgerScale.pojo.dto.LedgerScaleDTO;
import com.njcn.product.diagram.LedgerScale.pojo.vo.EventDetailVO;
import com.njcn.product.diagram.LedgerScale.pojo.vo.EventLedgerVO;
import com.njcn.product.terminal.mysqlTerminal.mapper.*;
import com.njcn.product.terminal.mysqlTerminal.pojo.enums.LineBaseEnum;
import com.njcn.product.terminal.mysqlTerminal.pojo.po.Line;
import com.njcn.product.terminal.mysqlTerminal.pojo.po.PqStation;
import com.njcn.product.terminal.mysqlTerminal.pojo.vo.TerminalShowVO;
import com.njcn.product.diagram.LedgerScale.service.LedgerScaleService;
import com.njcn.product.system.dict.mapper.DictDataMapper;
import com.njcn.product.system.dict.pojo.enums.DicDataTypeEnum;
import com.njcn.product.system.dict.pojo.po.DictData;
import com.njcn.product.terminal.mysqlTerminal.pojo.dto.LedgerBaseInfo;
import com.njcn.product.terminal.mysqlTerminal.pojo.enums.RunFlagEnum;
import com.njcn.product.terminal.mysqlTerminal.pojo.param.LargeScreenCountParam;
import com.njcn.product.terminal.mysqlTerminal.pojo.po.RmpEventDetailPO;
import com.njcn.product.terminal.mysqlTerminal.service.CommGeneralService;
import com.njcn.web.factory.PageFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

/**
 * @Author: cdf
 * @CreateTime: 2025-09-01
 * @Description: 台账规模
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class LedgerScaleServiceImpl implements LedgerScaleService {

    private final CommGeneralService commGeneralService;

    private final LedgerScaleMapper ledgerScaleMapper;

    private final RmpEventDetailMapper rmpEventDetailMapper;

    private final RmpEventDetailAssMapper rmpEventDetailAssMapper;
    private final DictDataMapper dictDataMapper;
    private final LineMapper lineMapper;

    private final RespDataResultMapper respDataResultMapper;

    private final FileStorageUtil fileStorageUtil;
    private final UpHarmonicDetailMapper upHarmonicDetailMapper;
    private final PqStationMapper pqStationMapper;
    private final CsSubConfigurationAssService csSubConfigurationAssService;
    private final CsConfigurationService csConfigurationService;

    @Override
    public LedgerScaleDTO ledgerScaleStatistic(LargeScreenCountParam param) {
        LedgerScaleDTO ledgerScaleDTO = new LedgerScaleDTO();

        List<String> deptIds = commGeneralService.getAllLineIdsByDept(param.getDeptId());
        if (CollUtil.isEmpty(deptIds)) {
            throw new BusinessException(CommonResponseEnum.FAIL, "用户部门没有绑定监测点");
        }

        List<LedgerBaseInfo> ledgerBaseInfoList = ledgerScaleMapper.getLedgerBaseInfo(deptIds);

        List<LedgerBaseInfo> runList = ledgerBaseInfoList.stream().filter(it -> Objects.equals(it.getRunFlag(), RunFlagEnum.RUNNING.getStatus())).collect(Collectors.toList());


        List<LedgerBaseInfo> onlineList = runList.stream().filter(it -> it.getComFlag() == 1).collect(Collectors.toList());

        ledgerScaleDTO.setLineAll(runList.size());
        ledgerScaleDTO.setLineRun(onlineList.size());

        long devAll = ledgerBaseInfoList.stream().map(LedgerBaseInfo::getDevId).distinct().count();
        long devRun = runList.stream().map(LedgerBaseInfo::getDevId).distinct().count();
        ledgerScaleDTO.setDevAll((int) devAll);
        ledgerScaleDTO.setDevRun((int) devRun);

        long stationAll = ledgerBaseInfoList.stream().map(LedgerBaseInfo::getStationId).distinct().count();
        long stationRun = runList.stream().map(LedgerBaseInfo::getStationId).distinct().count();
        ledgerScaleDTO.setStationAll((int) stationAll);
        ledgerScaleDTO.setStationRun((int) stationRun);
        return ledgerScaleDTO;
    }

    @Override
    public EventSourceDTO eventSource(LargeScreenCountParam param) {
        EventSourceDTO eventSourceDTO = new EventSourceDTO();
        List<String> deptIds = commGeneralService.getRunLineIdsByDept(param.getDeptId());
        if (CollUtil.isEmpty(deptIds)) {
            return eventSourceDTO;
        }

        DateTime start = DateUtil.beginOfDay(DateUtil.parse(param.getSearchBeginTime()));
        DateTime end = DateUtil.endOfDay(DateUtil.parse(param.getSearchEndTime()));


        LambdaQueryWrapper<RmpEventDetailPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.between(RmpEventDetailPO::getStartTime, start, end).in(RmpEventDetailPO::getLineId, deptIds);
        List<RmpEventDetailPO> eventList = rmpEventDetailMapper.selectList(lambdaQueryWrapper);
        if (CollUtil.isEmpty(eventList)) {
            return eventSourceDTO;
        }

        List<String> ids = eventList.stream().map(RmpEventDetailPO::getLineId).distinct().collect(Collectors.toList());
        List<LedgerBaseInfo> ledgerBaseInfoList = ledgerScaleMapper.getBaseInfo(ids);
        Map<String, LedgerBaseInfo> objMap = ledgerBaseInfoList.stream().collect(Collectors.toMap(LedgerBaseInfo::getLineId, Function.identity()));

        Map<String, List<RmpEventDetailPO>> map = eventList.stream().collect(Collectors.groupingBy(RmpEventDetailPO::getLineId));

        List<EventSourceDTO.Inner> innerList = new ArrayList<>();
        map.forEach((k, val) -> {
            EventSourceDTO.Inner inner = new EventSourceDTO.Inner();
            LedgerBaseInfo ledgerBaseInfo = objMap.get(k);
            inner.setName(StrUtil.isNotBlank(ledgerBaseInfo.getObjName()) ? ledgerBaseInfo.getObjName() : ledgerBaseInfo.getLineName());
            inner.setCount(val.size());
            inner.setId(ledgerBaseInfo.getLineId());
            innerList.add(inner);
        });
        eventSourceDTO.setEventCount(eventList.size());
        eventSourceDTO.setInnerList(innerList);

        return eventSourceDTO;
    }

    @Override
    public EventSourceDTO eventAggregation(LargeScreenCountParam param) {
        EventSourceDTO eventSourceDTO = new EventSourceDTO();


        DateTime start = DateUtil.beginOfDay(DateUtil.parse(param.getSearchBeginTime()));
        DateTime end = DateUtil.endOfDay(DateUtil.parse(param.getSearchEndTime()));

        LambdaQueryWrapper<RmpEventDetailAssPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(RmpEventDetailAssPO::getTimeId).between(RmpEventDetailAssPO::getTimeId, start, end);
        List<RmpEventDetailAssPO> assPOList = rmpEventDetailAssMapper.selectList(lambdaQueryWrapper);
        if (CollUtil.isEmpty(assPOList)) {
            return eventSourceDTO;
        }
     /*   Map<String, RmpEventDetailAssPO> assObjMap = assPOList.stream().collect(Collectors.toMap(RmpEventDetailAssPO::getEventAssId, Function.identity()));

        List<String> assIds = assPOList.stream().map(RmpEventDetailAssPO::getEventAssId).collect(Collectors.toList());
        List<RmpEventDetailPO> rmpEventDetailPOList = rmpEventDetailMapper.selectList(new LambdaQueryWrapper<RmpEventDetailPO>().in(RmpEventDetailPO::getEventassIndex, assIds));


        Map<String, LocalDateTime> assMap = assPOList.stream().collect(Collectors.toMap(RmpEventDetailAssPO::getEventAssId, RmpEventDetailAssPO::getTimeId));
        rmpEventDetailPOList = rmpEventDetailPOList.stream().filter(it -> {
            if (!assMap.containsKey(it.getEventassIndex())) {
                return false;
            }
            LocalDateTime localDateTime = assMap.get(it.getEventassIndex());
            if (it.getStartTime().equals(localDateTime)) {
                return true;
            } else {
                return false;
            }
        }).collect(Collectors.toList());*/

        eventSourceDTO.setEventCount(assPOList.size());

        List<EventSourceDTO.Inner> innerList = new ArrayList<>();
        for (RmpEventDetailAssPO it : assPOList) {
            EventSourceDTO.Inner inner = new EventSourceDTO.Inner();
            inner.setId(it.getEventAssId());
            inner.setName(it.getContentDes());
            innerList.add(inner);
        }
        eventSourceDTO.setInnerList(innerList);
        return eventSourceDTO;
    }

    @Override
    public List<EventLedgerVO> hasEventList(LargeScreenCountParam param) {
        List<EventLedgerVO> result = new ArrayList<>();
        LambdaQueryWrapper<RmpEventDetailPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isBlank(param.getEventAssId())) {
            List<String> ids = commGeneralService.getRunLineIdsByDept(param.getDeptId());
            if (CollUtil.isEmpty(ids)) {
                return result;
            }
            DateTime start = DateUtil.beginOfDay(DateUtil.parse(param.getSearchBeginTime()));
            DateTime end = DateUtil.endOfDay(DateUtil.parse(param.getSearchEndTime()));
            lambdaQueryWrapper.in(RmpEventDetailPO::getLineId, ids).between(RmpEventDetailPO::getStartTime, start, end);
        } else {
            lambdaQueryWrapper.eq(RmpEventDetailPO::getEventassIndex, param.getEventAssId());
        }


        List<RmpEventDetailPO> rmpEventDetailPOList = rmpEventDetailMapper.selectList(lambdaQueryWrapper);
        List<String> lineIds = rmpEventDetailPOList.stream().map(RmpEventDetailPO::getLineId).distinct().collect(Collectors.toList());
        if (CollUtil.isEmpty(lineIds)) {
            return result;
        }
        Map<String, LedgerBaseInfo> ledgerBaseInfoMap = ledgerScaleMapper.getLedgerBaseInfo(lineIds).stream().collect(Collectors.toMap(LedgerBaseInfo::getLineId, Function.identity()));
        Map<String, List<RmpEventDetailPO>> map = rmpEventDetailPOList.stream().collect(Collectors.groupingBy(RmpEventDetailPO::getLineId));

        RmpEventDetailPO minPo = rmpEventDetailPOList.stream().min(Comparator.comparingDouble(RmpEventDetailPO::getFeatureAmplitude)).get();
        map.forEach((lineId, list) -> {



            LedgerBaseInfo ledgerBaseInfo = ledgerBaseInfoMap.get(lineId);
            EventLedgerVO eventLedgerVO = new EventLedgerVO();
            BeanUtil.copyProperties(ledgerBaseInfo, eventLedgerVO);
            eventLedgerVO.setEventIds(list.stream().map(RmpEventDetailPO::getEventId).collect(Collectors.toList()));
            if (StrUtil.isBlank(param.getEventAssId())) {
                eventLedgerVO.setIsImport(DataStateEnum.DELETED.getCode());
            }else {
                if(minPo.getLineId().equals(lineId)){
                    eventLedgerVO.setIsImport(DataStateEnum.ENABLE.getCode());
                }else {
                    eventLedgerVO.setIsImport(DataStateEnum.DELETED.getCode());
                }
            }
            result.add(eventLedgerVO);
        });
        return result;
    }

    @Override
    public List<EventLedgerVO> hasUpEventList(LargeScreenCountParam param) {
        List<EventLedgerVO> result = new ArrayList<>();
        List<String> ids = commGeneralService.getRunLineIdsByDept(param.getDeptId());
        if (CollUtil.isEmpty(ids)) {
            return result;
        }

        LambdaQueryWrapper<UpHarmonicDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        DateTime start = DateUtil.beginOfDay(DateUtil.parse(param.getSearchBeginTime()));
        DateTime end = DateUtil.endOfDay(DateUtil.parse(param.getSearchEndTime()));
        lambdaQueryWrapper.in(UpHarmonicDetail::getMonitorId, ids).between(UpHarmonicDetail::getStartTime, start, end);
        List<UpHarmonicDetail> upHarmonicDetailList = upHarmonicDetailMapper.selectList(lambdaQueryWrapper);
        if(CollUtil.isEmpty(upHarmonicDetailList)){
            return result;
        }

        List<String> monitorIds = upHarmonicDetailList.stream().map(UpHarmonicDetail::getMonitorId).distinct().collect(Collectors.toList());
        List<LedgerBaseInfo> ledgerBaseInfoList = ledgerScaleMapper.getLedgerBaseInfo(monitorIds);
        Map<String,LedgerBaseInfo> ledgerBaseInfoMap = ledgerBaseInfoList.stream().collect(Collectors.toMap(LedgerBaseInfo::getLineId,Function.identity()));

        Map<String,List<UpHarmonicDetail>> map = upHarmonicDetailList.stream().collect(Collectors.groupingBy(UpHarmonicDetail::getMonitorId));
        map.forEach((lineId,list)->{
            EventLedgerVO eventLedgerVO = new EventLedgerVO();
            BeanUtil.copyProperties(ledgerBaseInfoMap.get(lineId),eventLedgerVO);
            eventLedgerVO.setEventIds(list.stream().map(UpHarmonicDetail::getId).collect(Collectors.toList()));
            result.add(eventLedgerVO);
        });
        return result;
    }

    @Override
    public EventLedgerVO clickImage(LargeScreenCountParam param) {
        List<LedgerBaseInfo> ledgerBaseInfoList = ledgerScaleMapper.getLedgerBaseInfo(Stream.of(param.getLineId()).collect(Collectors.toList()));
        if (CollUtil.isEmpty(ledgerBaseInfoList)) {
            throw new BusinessException(CommonResponseEnum.FAIL, "当前节点未查询到测点信息");
        }

        EventLedgerVO eventLedgerVO = new EventLedgerVO();
        BeanUtil.copyProperties(ledgerBaseInfoList.get(0), eventLedgerVO);
        DateTime start = DateUtil.beginOfDay(DateUtil.parse(param.getSearchBeginTime()));
        DateTime end = DateUtil.endOfDay(DateUtil.parse(param.getSearchEndTime()));
        LambdaQueryWrapper<RmpEventDetailPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(RmpEventDetailPO::getLineId, param.getLineId()).between(RmpEventDetailPO::getStartTime, start, end).orderByDesc(RmpEventDetailPO::getStartTime);;
        List<RmpEventDetailPO> rmpEventDetailPOList = rmpEventDetailMapper.selectList(lambdaQueryWrapper);

        List<DictData> dictDataList = dictDataMapper.getDicDataByTypeCode(DicDataTypeEnum.EVENT_STATIS.getCode());
        Map<String, DictData> dictDataMap = dictDataList.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));
        rmpEventDetailPOList.forEach(item-> item.setEventType(dictDataMap.get(item.getEventType()).getName()));
        eventLedgerVO.setEventList(rmpEventDetailPOList);
        return eventLedgerVO;
    }



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

        LambdaQueryWrapper<RmpEventDetailPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isBlank(param.getEventAssId())) {
            List<String> ids = commGeneralService.getRunLineIdsByDept(param.getDeptId());
            if (CollUtil.isEmpty(ids)) {
                return result;
            }

            if(StrUtil.isNotBlank(param.getSearchValue())){
                ids =  ledgerScaleMapper.getQueryLedger(ids,param.getSearchValue());
                if (CollUtil.isEmpty(ids)) {
                    return result;
                }
            }

            DateTime start = DateUtil.beginOfDay(DateUtil.parse(param.getSearchBeginTime()));
            DateTime end = DateUtil.endOfDay(DateUtil.parse(param.getSearchEndTime()));
            lambdaQueryWrapper.in(RmpEventDetailPO::getLineId, ids).between(RmpEventDetailPO::getStartTime, start, end).orderByDesc(RmpEventDetailPO::getStartTime);

            if(StrUtil.isNotBlank(param.getEventType())){
                lambdaQueryWrapper.eq(RmpEventDetailPO::getEventType,param.getEventType());
            }

            if(Objects.nonNull(param.getEventDurationMin()) ||Objects.nonNull(param.getEventDurationMax())){
                lambdaQueryWrapper.gt(Objects.nonNull(param.getEventDurationMin()),RmpEventDetailPO::getDuration,param.getEventDurationMin());
                lambdaQueryWrapper.lt(Objects.nonNull(param.getEventDurationMax()),RmpEventDetailPO::getDuration,param.getEventDurationMax());
            }

            if(Objects.nonNull(param.getEventValueMin()) ||Objects.nonNull(param.getEventValueMax())){
                lambdaQueryWrapper.gt(Objects.nonNull(param.getEventValueMin()),RmpEventDetailPO::getFeatureAmplitude,param.getEventValueMin());
                lambdaQueryWrapper.lt(Objects.nonNull(param.getEventValueMax()),RmpEventDetailPO::getFeatureAmplitude,param.getEventValueMax());
            }

        } else {
            lambdaQueryWrapper.eq(RmpEventDetailPO::getEventassIndex, param.getEventAssId());
        }

        Page<RmpEventDetailPO> page = rmpEventDetailMapper.selectPage(new Page<>(PageFactory.getPageNum(param), PageFactory.getPageSize(param)), lambdaQueryWrapper);
        if (CollUtil.isEmpty(page.getRecords())) {
            return result;
        }

        List<String> lineIds = page.getRecords().stream().map(RmpEventDetailPO::getLineId).distinct().collect(Collectors.toList());
        Map<String, LedgerBaseInfo> ledgerBaseInfoMap = ledgerScaleMapper.getLedgerBaseInfo(lineIds).stream().collect(Collectors.toMap(LedgerBaseInfo::getLineId, Function.identity()));

        List<DictData> dictDataList = dictDataMapper.getDicDataByTypeCode(DicDataTypeEnum.EVENT_STATIS.getCode());
        Map<String, DictData> dictDataMap = dictDataList.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));

        List<EventDetailVO> temList = new ArrayList<>();
        page.getRecords().forEach(item -> {
            EventDetailVO eventDetailVO = new EventDetailVO();
            BeanUtil.copyProperties(item, eventDetailVO);

            eventDetailVO.setFeatureAmplitude(BigDecimal.valueOf(item.getFeatureAmplitude()).setScale(5, RoundingMode.HALF_UP).doubleValue());
            eventDetailVO.setEventType(dictDataMap.get(eventDetailVO.getEventType()).getName());

            if (ledgerBaseInfoMap.containsKey(item.getLineId())) {
                LedgerBaseInfo ledgerBaseInfo = ledgerBaseInfoMap.get(item.getLineId());
                BeanUtil.copyProperties(ledgerBaseInfo, eventDetailVO);
            }
            temList.add(eventDetailVO);
        });
        result.setRecords(temList);
        result.setTotal(page.getTotal());
        return result;
    }


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

        LambdaQueryWrapper<RmpEventDetailPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        DateTime start = DateUtil.beginOfDay(DateUtil.parse(param.getSearchBeginTime()));
        DateTime end = DateUtil.endOfDay(DateUtil.parse(param.getSearchEndTime()));
        lambdaQueryWrapper.eq(RmpEventDetailPO::getLineId, param.getLineId()).between(RmpEventDetailPO::getStartTime, start, end).orderByDesc(RmpEventDetailPO::getStartTime);

        Page<RmpEventDetailPO> page = rmpEventDetailMapper.selectPage(new Page<>(PageFactory.getPageNum(param), PageFactory.getPageSize(param)), lambdaQueryWrapper);
        if (CollUtil.isEmpty(page.getRecords())) {
            return result;
        }

        List<LedgerBaseInfo> ledgerBaseInfoList = ledgerScaleMapper.getLedgerBaseInfo(Collections.singletonList(param.getLineId()));
        LedgerBaseInfo ledgerBaseInfo = ledgerBaseInfoList.get(0);

        List<DictData> dictDataList = dictDataMapper.getDicDataByTypeCode(DicDataTypeEnum.EVENT_STATIS.getCode());
        Map<String, DictData> dictDataMap = dictDataList.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));

        List<EventDetailVO> temList = new ArrayList<>();
        page.getRecords().forEach(item -> {
            EventDetailVO eventDetailVO = new EventDetailVO();
            BeanUtil.copyProperties(item, eventDetailVO);

            eventDetailVO.setFeatureAmplitude(BigDecimal.valueOf(item.getFeatureAmplitude()).setScale(5, RoundingMode.HALF_UP).doubleValue());
            eventDetailVO.setEventType(dictDataMap.get(eventDetailVO.getEventType()).getName());
            BeanUtil.copyProperties(ledgerBaseInfo, eventDetailVO);
            temList.add(eventDetailVO);
        });
        result.setRecords(temList);
        result.setTotal(page.getTotal());
        return result;
    }


    @Override
    public Page<TerminalShowVO> stationPage(LargeScreenCountParam param) {
        List<String> lineIds = commGeneralService.getAllLineIdsByDept(param.getDeptId());
        if (CollUtil.isEmpty(lineIds)) {
            return new Page<>();
        }
        Page<TerminalShowVO> page = lineMapper.getStationList(new Page<>(PageFactory.getPageNum(param), PageFactory.getPageSize(param)), lineIds, param.getRunFlag(), param.getSearchValue());
        if (CollUtil.isNotEmpty(page.getRecords())) {
            List<DictData> dictData = dictDataMapper.getDicDataByTypeCode(DicDataTypeEnum.DEV_VOLTAGE_STAND.getCode());
            Map<String, DictData> map = dictData.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));
            page.getRecords().forEach(it -> {
                if (map.containsKey(it.getStationVoltageLevel())) {
                    it.setStationVoltageLevel(map.get(it.getStationVoltageLevel()).getName());
                }
            });
        }

        return page;
    }


    @Override
    public Page<TerminalShowVO> devPage(LargeScreenCountParam param) {
        List<String> lineIds = commGeneralService.getAllLineIdsByDept(param.getDeptId());
        if (CollUtil.isEmpty(lineIds)) {
            return new Page<>();
        }
        Page<TerminalShowVO> page = lineMapper.getDevList(new Page<>(PageFactory.getPageNum(param), PageFactory.getPageSize(param)), lineIds, param.getRunFlag(), param.getSearchValue());
        if (CollUtil.isNotEmpty(page.getRecords())) {
            List<DictData> dictData = dictDataMapper.getDicDataByTypeCode(DicDataTypeEnum.DEV_MANUFACTURER.getCode());
            Map<String, DictData> map = dictData.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));
            page.getRecords().forEach(it -> {
                if (map.containsKey(it.getManufacturer())) {
                    it.setManufacturer(map.get(it.getManufacturer()).getName());
                }
            });
        }
        return page;
    }

    @Override
    public Page<TerminalShowVO> linePage(LargeScreenCountParam param) {
        List<String> lineIds = commGeneralService.getRunLineIdsByDept(param.getDeptId());
        if (CollUtil.isEmpty(lineIds)) {
            return new Page<>();
        }
        Page<TerminalShowVO> page = lineMapper.getLineList(new Page<>(PageFactory.getPageNum(param), PageFactory.getPageSize(param)), lineIds, param.getComFlag(), param.getSearchValue());
        if (CollUtil.isNotEmpty(page.getRecords())) {
            List<DictData> dictData = dictDataMapper.getDicDataByTypeCode(DicDataTypeEnum.DEV_VOLTAGE_STAND.getCode());
            Map<String, DictData> map = dictData.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));
            page.getRecords().forEach(it -> {
                if (map.containsKey(it.getVoltageLevel())) {
                    it.setVoltageLevel(map.get(it.getVoltageLevel()).getName());
                }
            });
        }
        return page;
    }

    @Override
    public List<CustomerResponsibility> harmOneImage(String id, Integer time) {
        LambdaQueryWrapper<RespDataResult> respDataResultLambdaQueryWrapper = new LambdaQueryWrapper<>();
        respDataResultLambdaQueryWrapper.eq(RespDataResult::getResDataId, id)
                .eq(RespDataResult::getTime, time).orderByDesc(RespDataResult::getCreateTime);
        List<RespDataResult> respDataResults = respDataResultMapper.selectList(respDataResultLambdaQueryWrapper);
        if (CollectionUtil.isNotEmpty(respDataResults)) {

            RespDataResult respDataResult = respDataResults.get(0);
            //处理排名前10数据
            InputStream respStream = fileStorageUtil.getFileStream(respDataResult.getUserResponsibility());
            String respStr = IoUtil.readUtf8(respStream);
            List<CustomerResponsibility> respData = JSONArray.parseArray(respStr, CustomerResponsibility.class);
            respData.forEach(it -> {
                String tem = it.getCustomerName().substring(it.getCustomerName().indexOf("(") + 1, it.getCustomerName().indexOf(")"));
                it.setMonitorId(tem);
            });
            return respData;
        }
        return new ArrayList<>();
    }

    @Override
    public List<PqStation> stationMap(LargeScreenCountParam param) {
        List<PqStation> result = new ArrayList<>();
        List<String> runIds = commGeneralService.getRunLineIdsByDept(param.getDeptId());
        if(CollUtil.isEmpty(runIds)){
            return result;
        }
        List<Line> lineList = lineMapper.selectList(new LambdaQueryWrapper<Line>().in(Line::getId,runIds));
        List<String> stationIds = lineList.stream().map(it->it.getPids().split(StrUtil.COMMA)[LineBaseEnum.SUB_LEVEL.getCode()]).distinct().collect(Collectors.toList());
        List<Line> stationResult = lineMapper.selectList(new LambdaQueryWrapper<Line>().in(Line::getId,stationIds));
        List<String> ids = stationResult.stream().map(Line::getId).distinct().collect(Collectors.toList());
        List<PqStation> pqStationList = pqStationMapper.selectList(new LambdaQueryWrapper<PqStation>().in(PqStation::getId,ids));
        Map<String, PqStation> substationMap = pqStationList.stream().collect(Collectors.toMap(PqStation::getId, po->po));
        stationResult.forEach(it->{
            PqStation pqStation = new PqStation();
            if(substationMap.containsKey(it.getId())){
                PqStation tem = substationMap.get(it.getId());
                pqStation.setLng(tem.getLng());
                pqStation.setLat(tem.getLat());
            }
            pqStation.setId(it.getId());
            pqStation.setName(it.getName());
            CsSubConfigurationAss one = csSubConfigurationAssService.lambdaQuery().eq(CsSubConfigurationAss::getSubId, it.getId()).one();
            if(Objects.isNull(one)){
                pqStation.setBindFlag(false);

            }else {
                CsConfigurationPO csConfigurationPO = csConfigurationService.lambdaQuery().eq(CsConfigurationPO::getId, one.getConfigId()).one();
                pqStation.setBindFlag(true);
                pqStation.setConfigId(csConfigurationPO.getId());
                pqStation.setConfigName(csConfigurationPO.getName());
            }
            result.add(pqStation);
        });
        return result;
    }


}
