package com.njcn.device.pms.service.majornetwork.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.dto.SimpleDTO;
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.device.biz.enums.DeviceResponseEnum;

import com.njcn.device.biz.pojo.dto.DeptGetChildrenDTO;
import com.njcn.device.biz.pojo.dto.LineALLInfoDTO;
import com.njcn.device.biz.pojo.dto.LineDTO;
import com.njcn.device.biz.pojo.dto.LineDevGetDTO;
import com.njcn.device.biz.pojo.param.DeptGetLineParam;
import com.njcn.device.biz.pojo.po.DeviceBak;
import com.njcn.device.biz.utils.COverlimit;
import com.njcn.device.biz.utils.COverlimitUtil;
import com.njcn.device.pms.enums.PmsDeviceResponseEnum;
import com.njcn.device.pms.mapper.majornetwork.*;
import com.njcn.device.pms.pojo.dto.PmsMonitorBaseDTO;
import com.njcn.device.pms.pojo.dto.PmsMonitorDTO;
import com.njcn.device.pms.pojo.dto.PmsMonitorInfoDTO;
import com.njcn.device.pms.pojo.excel.PmsLedgerExcel;
import com.njcn.device.pms.pojo.param.*;
import com.njcn.device.pms.pojo.param.gw.TypicalSourceParam;
import com.njcn.device.pms.pojo.po.*;
import com.njcn.device.pms.pojo.vo.MonitorVO;
import com.njcn.device.pms.pojo.vo.PmsMonitorVO;
import com.njcn.device.pms.pojo.vo.gw.TypicalSourceOnLine;
import com.njcn.device.pms.service.majornetwork.*;
import com.njcn.device.pq.pojo.bo.excel.OracleTerminalExcel;
import com.njcn.device.biz.pojo.dto.PollutionLineDTO;
import com.njcn.device.pq.pojo.po.LineBak;
import com.njcn.poi.excel.ExcelUtil;
import com.njcn.poi.util.PoiUtil;
import com.njcn.system.api.DictTreeFeignClient;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.system.enums.DicDataTypeEnum;
import com.njcn.system.enums.DicTreeEnum;
import com.njcn.system.pojo.po.SysDicTreePO;
import com.njcn.system.pojo.vo.DictTreeVO;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.device.biz.pojo.po.Overlimit;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.enums.SystemResponseEnum;
import com.njcn.system.pojo.po.DictData;
import com.njcn.user.pojo.dto.DeptDTO;
import com.njcn.user.pojo.po.Dept;
import com.njcn.web.factory.PageFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author cdf
 * @since 2022-10-14
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MonitorServiceImpl extends ServiceImpl<MonitorMapper, Monitor> implements IMonitorService {

    private final MonitorMapper monitorMapper;

    private final OverlimitMapper overlimitMapper;

    private final DicDataFeignClient dicDataFeignClient;

    private final DeptFeignClient deptFeignClient;

    private final PmsGeneratrixWireMapper generatrixWireMapper;

    private final SpecialMonitorMapper specialMonitorMapper;

    private final IDistributionMonitorService iDistributionMonitorService;

    private final StatationStatMapper statationStatMapper;

    private final TerminalMapper terminalMapper;

    private final LineBakMapper lineBakMapper;

    private final DeviceBakMapper deviceBakMapper;

    private final DictTreeFeignClient dictTreeFeignClient;
    private final ITractionStationService tractionStationService;
    private final PowerClientMapper powerClientMapper;
    private final DistributionMonitorMapper distributionMonitorMapper;

    @Override
    public List<PmsMonitorBaseDTO> getMonitorByCondition(List<String> deptIdList, PmsDeviceInfoParam pmsDeviceInfoParam) {
        return this.baseMapper.getMonitorByCondition(deptIdList, pmsDeviceInfoParam);
    }

    /**
     * 获取指定的监测点信息
     *
     * @param pmsMonitorInfoParam 获取监测点详情数据入参
     * @return 指定的监测点信息
     */
    @Override
    public List<PmsMonitorInfoDTO> getMonitorInfo(PmsMonitorInfoParam pmsMonitorInfoParam) {
        return monitorMapper.getMonitorInfo(pmsMonitorInfoParam);
    }

    /***
     * 根据条件获取监测点列表（包含监测点所有信息）
     * @author jianghaifei
     * @date 2022-10-20 20:29
     * @param pmsMonitorParam
     * @return java.util.List<com.njcn.device.pms.pojo.dto.PmsMonitorDTO>
     */
    @Override
    public List<PmsMonitorDTO> getMonitorInfoListByCond(PmsMonitorParam pmsMonitorParam) {
        LambdaQueryWrapper<Monitor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //组装条件：org_id in (orgIds) and id in (monitorIds) and name like "%monitorName%"
        //            and voltage_Level in (voltageLevels)
        lambdaQueryWrapper.in(CollUtil.isNotEmpty(pmsMonitorParam.getOrgIds()), Monitor::getOrgId, pmsMonitorParam.getOrgIds())
                .in(CollUtil.isNotEmpty(pmsMonitorParam.getMonitorIds()), Monitor::getId, pmsMonitorParam.getMonitorIds())
                .like(StringUtils.isNotBlank(pmsMonitorParam.getMonitorName()), Monitor::getName, pmsMonitorParam.getMonitorName())
                .in(CollUtil.isNotEmpty(pmsMonitorParam.getVoltageLevels()), Monitor::getVoltageLevel, pmsMonitorParam.getVoltageLevels())
                .in(CollUtil.isNotEmpty(pmsMonitorParam.getPowerrIds()), Monitor::getPowerrId, pmsMonitorParam.getPowerrIds())
                .like(StringUtils.isNotBlank(pmsMonitorParam.getPowerrName()), Monitor::getPowerrName, pmsMonitorParam.getPowerrName())
                .eq(Objects.nonNull(pmsMonitorParam.getIsSpecialMonitor()), Monitor::getIsSpecialMonitor, pmsMonitorParam.getIsSpecialMonitor())
                .eq(StringUtils.isNotBlank(pmsMonitorParam.getMonitorType()), Monitor::getMonitorType, pmsMonitorParam.getMonitorType())

                .in(CollUtil.isNotEmpty(pmsMonitorParam.getMonitorTags()), Monitor::getMonitorTag, pmsMonitorParam.getMonitorTags())

                .eq(StringUtils.isNotBlank(pmsMonitorParam.getMonitorState()), Monitor::getMonitorState, pmsMonitorParam.getMonitorState())
                .eq(StringUtils.isNotBlank(pmsMonitorParam.getMonitorTag()), Monitor::getMonitorTag, pmsMonitorParam.getMonitorTag());

        List<Monitor> list = this.list(lambdaQueryWrapper);
        List<PmsMonitorDTO> dtoList = list.stream().map(item -> {
            PmsMonitorDTO dto = new PmsMonitorDTO();
            BeanUtils.copyProperties(item, dto);
            return dto;
        }).collect(Collectors.toList());
        return dtoList;
    }

    /***
     * 获取所有监测点信息
     * @author jianghaifei
     * @date 2022-10-24 20:01
     * @param
     * @return java.util.List<com.njcn.device.pms.pojo.vo.PmsMonitorVO>
     */
    @Override
    public List<PmsMonitorVO> getAllMonitorList() {
        List<Monitor> monitorList = this.list();
        List<PmsMonitorVO> resultList = monitorList.stream().map(item -> {
            PmsMonitorVO pmsMonitorVO = new PmsMonitorVO();
            BeanUtils.copyProperties(item, pmsMonitorVO);
            return pmsMonitorVO;
        }).collect(Collectors.toList());
        return resultList;
    }

    @Override
    public Overlimit getOverLimitData(String id) {
        return overlimitMapper.selectById(id);
    }

    @Override
    public List<Overlimit> getOverLimitDataByIds(List<String> ids) {
        return overlimitMapper.selectBatchIds(ids);
    }

    @Override
    public Page<Monitor> getAllMonitorPageList(TerminalQueryParam baseParam) {
        LambdaQueryWrapper<Monitor> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        List<String> objTypeIds = new ArrayList<>();
        if(StrUtil.isNotBlank(baseParam.getObjType())){
            if(baseParam.getObjType().equals("987654321")){
                //特殊处理
               List<SysDicTreePO> sysDicTreePOList = dictTreeFeignClient.queryAll().getData();

               List<SysDicTreePO>  typicDic =sysDicTreePOList.stream().filter(item->Objects.equals(DicTreeEnum.Power_Station.getCode(),item.getCode())||Objects.equals(DicTreeEnum.Ele_Railways.getCode(),item.getCode())||
                        Objects.equals(DicTreeEnum.Wind_Farms.getCode(),item.getCode())||Objects.equals(DicTreeEnum.Imp_Users.getCode(),item.getCode())).collect(Collectors.toList());

               for(SysDicTreePO sysDicTreePO : typicDic){
                   List<DictTreeVO> temList = dictTreeFeignClient.query(sysDicTreePO.getId()).getData();
                   List<String> ids = temList.stream().map(DictTreeVO::getId).collect(Collectors.toList());
                   objTypeIds.addAll(ids);
                   objTypeIds.add(sysDicTreePO.getId());
               }

                lambdaQueryWrapper.notIn(Monitor::getObjType,objTypeIds);


            }else {
                SysDicTreePO sysDicTreePO = dictTreeFeignClient.queryById(baseParam.getObjType()).getData();
                if(sysDicTreePO.getPid().equals("0")){
                    List<DictTreeVO> temList = dictTreeFeignClient.query(sysDicTreePO.getId()).getData();
                    List<String> ids = temList.stream().map(DictTreeVO::getId).collect(Collectors.toList());
                    objTypeIds.addAll(ids);
                }
                objTypeIds.add(sysDicTreePO.getId());
                lambdaQueryWrapper.in(CollUtil.isNotEmpty(objTypeIds),Monitor::getObjType,objTypeIds);

            }

        }

        lambdaQueryWrapper
                .eq(StrUtil.isNotBlank(baseParam.getMonitorState()), Monitor::getMonitorState, baseParam.getMonitorState())
                .eq(StrUtil.isNotBlank(baseParam.getMonitorTag()), Monitor::getMonitorTag, baseParam.getMonitorTag())
                .eq(Objects.nonNull(baseParam.getIsUpToGrid()), Monitor::getIsUpToGrid, baseParam.getIsUpToGrid())
                .eq(Objects.nonNull(baseParam.getIsUploadHead()), Monitor::getIsUploadHead, baseParam.getIsUploadHead())
                .eq(Objects.nonNull(baseParam.getMonitorUploadStatus()), Monitor::getMonitorUploadStatus, baseParam.getMonitorUploadStatus())

                .and(StrUtil.isNotBlank(baseParam.getSearchValue()), i -> i.like(Monitor::getName, baseParam.getSearchValue())
                        .or()
                        .like(Monitor::getId, baseParam.getSearchValue())
                        .or()
                        .like(Monitor::getPowerrName, baseParam.getSearchValue())
                        .or()
                        .like(Monitor::getOrgName, baseParam.getSearchValue()))
                .eq(Monitor::getStatus, DataStateEnum.ENABLE.getCode())
                .orderByAsc(Monitor::getOrgName,Monitor::getPowerrName);
        Page<Monitor> page = this.page(new Page<>(PageFactory.getPageNum(baseParam), PageFactory.getPageSize(baseParam)), lambdaQueryWrapper);

        List<DictData> dictDataList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.DEV_VOLTAGE.getCode()).getData();
        Map<String, DictData> map = dictDataList.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));

        List<Monitor> temList = page.getRecords();



        if(CollUtil.isNotEmpty(temList)) {
            List<String> terminalIds = temList.stream().map(Monitor::getTerminalId).distinct().collect(Collectors.toList());
            List<PmsTerminal> pmsTerminalList = terminalMapper.selectList(new LambdaQueryWrapper<PmsTerminal>().in(PmsTerminal::getId, terminalIds));
            Map<String, PmsTerminal> mapTerminal = pmsTerminalList.stream().collect(Collectors.toMap(PmsTerminal::getId, Function.identity()));

            List<String> busIds = temList.stream().map(Monitor::getLineId).distinct().collect(Collectors.toList());
            List<GeneratrixWire> generatrixWireList = generatrixWireMapper.selectList(new LambdaQueryWrapper<GeneratrixWire>().in(GeneratrixWire::getId, busIds));
            Map<String, GeneratrixWire> mapBus = generatrixWireList.stream().collect(Collectors.toMap(GeneratrixWire::getId, Function.identity()));

            List<String> powerIds = temList.stream().map(Monitor::getPowerrId).distinct().collect(Collectors.toList());
            List<StatationStat> statationStatList = statationStatMapper.selectList(new LambdaQueryWrapper<StatationStat>().in(StatationStat::getPowerId,powerIds));
            Map<String,StatationStat> statMap = statationStatList.stream().collect(Collectors.toMap(StatationStat::getPowerId,Function.identity()));

            temList = temList.stream().peek(item -> {
                if (mapTerminal.containsKey(item.getTerminalId())) {
                    item.setTerminalCode(mapTerminal.get(item.getTerminalId()).getTerminalCode());
                    item.setDevIp(mapTerminal.get(item.getTerminalId()).getIp());
                }

                if (statMap.containsKey(item.getPowerrId())) {
                    item.setMidStation(statMap.get(item.getPowerrId()).getMidStationId());
                }

                if (mapBus.containsKey(item.getLineId())) {
                    item.setBusId(mapBus.get(item.getLineId()).getMidBusId());
                }

                item.setStandShortCapacity(COverlimit.getStandShortCap(map.get(item.getVoltageLevel()).getValue()));

            }).collect(Collectors.toList());
        }


        page.setRecords(temList);
        return page;
    }


    @Override
    public Page<Monitor> getAllMainUserPageList(TerminalQueryParam baseParam) {


        List<String> objTypeIds = new ArrayList<>();
        if(StrUtil.isNotBlank(baseParam.getObjType())){
            if(baseParam.getObjType().equals("987654321")){
                //特殊处理
                List<SysDicTreePO> sysDicTreePOList = dictTreeFeignClient.queryAll().getData();

                List<SysDicTreePO>  typicDic =sysDicTreePOList.stream().filter(item->Objects.equals(DicTreeEnum.Power_Station.getCode(),item.getCode())||Objects.equals(DicTreeEnum.Ele_Railways.getCode(),item.getCode())||
                        Objects.equals(DicTreeEnum.Wind_Farms.getCode(),item.getCode())||Objects.equals(DicTreeEnum.Imp_Users.getCode(),item.getCode())).collect(Collectors.toList());

                for(SysDicTreePO sysDicTreePO : typicDic){
                    List<DictTreeVO> temList = dictTreeFeignClient.query(sysDicTreePO.getId()).getData();
                    List<String> ids = temList.stream().map(DictTreeVO::getId).collect(Collectors.toList());
                    objTypeIds.addAll(ids);
                    objTypeIds.add(sysDicTreePO.getId());
                }
            }else {
                SysDicTreePO sysDicTreePO = dictTreeFeignClient.queryById(baseParam.getObjType()).getData();
                if(sysDicTreePO.getPid().equals("0")){
                    List<DictTreeVO> temList = dictTreeFeignClient.query(sysDicTreePO.getId()).getData();
                    List<String> ids = temList.stream().map(DictTreeVO::getId).collect(Collectors.toList());
                    objTypeIds.addAll(ids);
                }
                objTypeIds.add(sysDicTreePO.getId());
            }
            baseParam.setObjTypeList(objTypeIds);
        }
        Page<Monitor> page = this.baseMapper.getAllObjUser(new Page<>(baseParam.getPageNum(), baseParam.getPageSize()),baseParam);
        return page;
    }


    @Override
    public List<Monitor> getMonitorList(List<String> monitorIds) {
        List<Monitor> monitorList = new ArrayList<>();
        LambdaQueryWrapper<Monitor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Monitor::getStatus, DataStateEnum.ENABLE.getCode());
        if (CollUtil.isEmpty(monitorIds)) {
            //为空查询所有监测点
            monitorList = this.list(lambdaQueryWrapper);
        } else {
            lambdaQueryWrapper.in(Monitor::getId, monitorIds);
            monitorList = this.list(lambdaQueryWrapper);
        }
        return monitorList;
    }


    @Override
    public List<Monitor> getMonitorListByMid(List<String> midIds) {
        List<Monitor> monitorList;
        LambdaQueryWrapper<Monitor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Monitor::getStatus, DataStateEnum.ENABLE.getCode()).in(Monitor::getMonitorId,midIds);
        monitorList = this.list(lambdaQueryWrapper);
        return monitorList;
    }

    @Override
    public List<LineDevGetDTO> getPmsCalMonitorList(List<String> monitorIds) {
        List<LineDevGetDTO> monitorList = new ArrayList<>();
        LambdaQueryWrapper<Monitor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(Monitor::getId,Monitor::getStatisticalInterval,Monitor::getTerminalId)
                .in(Monitor::getId,monitorIds).eq(Monitor::getStatus, DataStateEnum.ENABLE.getCode());

        List<Monitor> monitors = monitorMapper.selectList(lambdaQueryWrapper);
        for(Monitor monitor : monitors){
            LineDevGetDTO lineDevGetDTO = new LineDevGetDTO();
            lineDevGetDTO.setDevId(monitor.getTerminalId());
            lineDevGetDTO.setPointId(monitor.getId());

            lineDevGetDTO.setInterval(monitor.getStatisticalInterval());
            System.out.println("获取主网测点统计间隔"+lineDevGetDTO.getInterval());
            monitorList.add(lineDevGetDTO);
        }

        DictData dictData = dicDataFeignClient.getDicDataByNameAndTypeName(DicDataTypeEnum.LINE_SORT.getName(), DicDataEnum.THREE_LINE.getName()).getData();
        List<DistributionMonitor> distributionMonitorList = distributionMonitorMapper.selectList(new LambdaQueryWrapper<DistributionMonitor>().in(DistributionMonitor::getMonitorId,monitorIds).eq(DistributionMonitor::getMonitorSort,dictData.getId()).eq(DistributionMonitor::getStatus,DataStateEnum.ENABLE.getCode()));
        for(DistributionMonitor distributionMonitor : distributionMonitorList){
            LineDevGetDTO lineDevGetDTO = new LineDevGetDTO();
            lineDevGetDTO.setDevId(distributionMonitor.getTerminalId());
            lineDevGetDTO.setPointId(distributionMonitor.getMonitorId());
            lineDevGetDTO.setInterval(distributionMonitor.getStatisticalInterval());
            monitorList.add(lineDevGetDTO);
        }
        return monitorList;
    }


    @Override
    public Page<Monitor> getMonitorPage(TerminalQueryParam baseParam) {
        LambdaQueryWrapper<Monitor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Monitor::getStatus, DataStateEnum.ENABLE.getCode());
        lambdaQueryWrapper.in(Monitor::getId, baseParam.getMonitorIds());
        Page<Monitor> page = this.page(new Page<>(PageFactory.getPageNum(baseParam),PageFactory.getPageSize(baseParam)),lambdaQueryWrapper);
        return page;
    }

    @Override
    public List<Monitor> getMonitorListByParam(MonitorParam monitorParam) {
        LambdaQueryWrapper<Monitor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //根据部门
        if (StrUtil.isNotBlank(monitorParam.getOrgId())) {
            List<String> deptIds = deptFeignClient.getDepSonSelfCodetByDeptId(monitorParam.getOrgId()).getData();
            lambdaQueryWrapper.in(Monitor::getOrgId, deptIds).eq(Monitor::getStatus, DataStateEnum.ENABLE.getCode());
        }
        //是否上送国网测点
        if(Objects.nonNull(monitorParam.getIsUpToGrid())){
            lambdaQueryWrapper.eq(Monitor::getIsUpToGrid, DataStateEnum.ENABLE.getCode());
        }
        //运行状态
        if(StrUtil.isNotBlank(monitorParam.getMonitorState())){
            lambdaQueryWrapper.eq(Monitor::getMonitorState,monitorParam.getMonitorState());
        }
        return this.list(lambdaQueryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addMonitor(MonitorParam monitorParam) {
        checkParam(monitorParam, false);
        Monitor monitor = new Monitor();
        BeanUtils.copyProperties(monitorParam, monitor);
        checkOther(monitorParam, monitor, false);
        monitor.setStatus(DataStateEnum.ENABLE.getCode());
        monitor.setIsUploadHead(0);
        monitor.setMonitorUploadStatus(0);
        monitor.setMonitorOverlimitStatus(0);

        //主网测点限值计算
        Overlimit overlimit = overLimitCal(monitorParam, monitor);
        this.save(monitor);

        //新增监测点同时新增pms_special_monitor
        SpecialMonitor specialMonitor = new SpecialMonitor();
        specialMonitor.setId(monitor.getId());
        specialMonitor.setCapacity(100f);
        specialMonitor.setType(1);
        specialMonitorMapper.insert(specialMonitor);

        overlimit.setId(monitor.getId());
        overlimitMapper.deleteById(monitor.getId());
        overlimitMapper.insert(overlimit);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateMonitor(MonitorParam monitorParam) {
        checkParam(monitorParam, true);
        Monitor monitor = new Monitor();
        BeanUtils.copyProperties(monitorParam, monitor);
        checkOther(monitorParam, monitor, true);


        Monitor tem = this.getById(monitorParam.getId());
        if(tem.getIsUploadHead() == 1){
            monitor.setIsUploadHead(3);
        }
        if(tem.getMonitorUploadStatus() == 1){
            monitor.setMonitorUploadStatus(3);
        }
        if(tem.getMonitorOverlimitStatus() == 1){
            monitor.setMonitorOverlimitStatus(3);
        }

        this.updateById(monitor);

        //修改监测点同时修改pms_special_monitor
        SpecialMonitor specialMonitor = new SpecialMonitor();
        specialMonitor.setId(monitor.getId());
        specialMonitor.setCapacity(100f);
        specialMonitor.setType(1);
        specialMonitorMapper.updateById(specialMonitor);

        //修改主网监测点如何配网表中也存在需要同时修改
        DistributionMonitor distributionMonitor = iDistributionMonitorService.getById(monitor.getId());
        if (Objects.nonNull(distributionMonitor)) {
            distributionMonitor.setTerminalId(monitor.getTerminalId());
            distributionMonitor.setTerminalWiringMethod(monitor.getTerminalWiringMethod());
            distributionMonitor.setVoltageLevel(monitor.getVoltageLevel());
            distributionMonitor.setMonitorState(monitor.getMonitorState());
            iDistributionMonitorService.updateById(distributionMonitor);
        }

        Overlimit overlimit = overLimitCal(monitorParam, monitor);
        overlimitMapper.deleteById(monitor.getId());
        overlimit.setId(monitor.getId());
        overlimitMapper.insert(overlimit);
        return true;

    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean delMonitor(List<String> monitorIds) {
        //需要先判断配网表中是否存在此监测点
        iDistributionMonitorService.removeByIds(monitorIds);
        this.removeByIds(monitorIds);
        specialMonitorMapper.deleteBatchIds(monitorIds);
        overlimitMapper.deleteBatchIds(monitorIds);

        lineBakMapper.deleteBatchIds(monitorIds);
        return true;
    }

    @Override
    public boolean retirementMonitor(Integer type, List<String> lineIds) {
        List<DictData> dictDataList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.LINE_STATE.getCode()).getData();
        Map<String, DictData> map = dictDataList.stream().collect(Collectors.toMap(DictData::getCode, Function.identity()));
        DictData dictData = map.get(DicDataEnum.RETIREMENT.getCode());
        if (type == 0) {
            //主网
            LambdaUpdateWrapper<Monitor> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.in(Monitor::getId, lineIds).eq(Monitor::getStatus, DataStateEnum.ENABLE.getCode());
            //退役
            lambdaUpdateWrapper.set(Monitor::getMonitorState, dictData.getId());
            this.update(lambdaUpdateWrapper);
        } else if (type == 1) {
            //配网
            LambdaUpdateWrapper<DistributionMonitor> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.in(DistributionMonitor::getMonitorId, lineIds).eq(DistributionMonitor::getStatus, DataStateEnum.ENABLE.getCode());
            //退役
            lambdaUpdateWrapper.set(DistributionMonitor::getMonitorState, dictData.getId());
            iDistributionMonitorService.update(lambdaUpdateWrapper);
        }
        return true;
    }

    @Override
    public List<SimpleDTO> getPmsPowerrInfoWithInOrg(List<String> orgIdList, PmsDeviceInfoParam pmsDeviceInfoParam) {
        return this.baseMapper.getPmsPowerrInfoWithInOrg(orgIdList, pmsDeviceInfoParam);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStatus(MonitorStatus monitorParam) {
        LambdaUpdateWrapper<Monitor> update = new LambdaUpdateWrapper<>();
        update.set(Monitor::getStatus, monitorParam.getStatus())
                .in(Monitor::getId, monitorParam.getId());
        return this.update(update);
    }

    @Override
    public MonitorVO monitorTerminal(MonitorTerminalParam param) {
        //type 0:主网 1:配网
        MonitorVO monitorTerminal;
        if (param.getType() == 0) {
            monitorTerminal = this.baseMapper.getMonitorTerminal(param.getId());
        } else {
            monitorTerminal = this.baseMapper.getPwMonitorTerminal(param.getId());
        }
        String terminalWiringMethod = monitorTerminal.getTerminalWiringMethod();
        DictData data = dicDataFeignClient.getDicDataById(terminalWiringMethod).getData();
        if (DicDataEnum.STAR.getCode().equals(data.getCode())) {
            monitorTerminal.setTerminalWiringMethod("0");
        }
        if (DicDataEnum.STAR_TRIANGLE.getCode().equals(data.getCode())) {
            monitorTerminal.setTerminalWiringMethod("1");
        }
        if (DicDataEnum.OPEN_DELTA.getCode().equals(data.getCode())) {
            monitorTerminal.setTerminalWiringMethod("2");
        } else {
            monitorTerminal.setTerminalWiringMethod("-1");
        }
        return monitorTerminal;
    }

    @Override
    public List<DeptGetChildrenDTO> deptMonitor(DeptGetLineParam param) {
        if (Objects.isNull(param)) {
            param.setSystemType(2);
        }
        //返回主网和配网监测信息
        List<DeptGetChildrenDTO> deviceInfos = new ArrayList<>();
        List<DeptDTO> deptInfos = deptFeignClient.getDeptDescendantIndexes(param.getDeptId(), Stream.of(0, 1).collect(Collectors.toList())).getData();
        DictData dictData = dicDataFeignClient.getDicDataByNameAndTypeName(DicDataTypeEnum.LINE_STATE.getName(), DicDataEnum.RUN.getName()).getData();
        if (Objects.isNull(dictData)) {
            throw new BusinessException("监测点状态字典为空");
        }
        for (DeptDTO deptInfo : deptInfos) {
            List<DeptDTO> directDeptInfos = deptInfos.stream()
                    .filter(deptDTO -> deptDTO.getPid().equals(deptInfo.getId()))
                    .collect(Collectors.toList());
            if (CollUtil.isEmpty(directDeptInfos)) {
                //没有直接子部门，获取当前部门所有信息
                List<DeptDTO> dept = deptInfos.stream()
                        .filter(deptDTO -> deptDTO.getId().equals(deptInfo.getId()))
                        .collect(Collectors.toList());
                deviceInfos.add(getPmsMonitor(dept.get(0), dictData, Collections.singletonList(dept.get(0).getCode()),param.getSystemType()));
            } else {
                List<String> deptIdList = new ArrayList<>();
                for (DeptDTO deptDTO : directDeptInfos) {
                    //筛选上级部门pids包含该id的所有部门
                    List<DeptDTO> descendantDeptDTO = deptInfos.stream()
                            .filter(d -> d.getPids().contains(deptDTO.getId()))
                            .collect(Collectors.toList());
                    //形成需要查询监测点的部门索引
                    deptIdList.addAll(descendantDeptDTO.stream()
                            .map(DeptDTO::getCode)
                            .distinct()
                            .collect(Collectors.toList()));
                    deptIdList.add(deptDTO.getCode());
                }
                deviceInfos.add(getPmsMonitor(deptInfo, dictData, deptIdList,param.getSystemType()));
            }
        }
        return deviceInfos;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importOracleLedgerToMysql(MultipartFile file, HttpServletResponse response) {
        ImportParams importParams = new ImportParams();
        importParams.setHeadRows(1);
        importParams.setTitleRows(1);
        importParams.setNeedVerify(true);

        try {
            ExcelImportResult<OracleTerminalExcel> terminalExcelExcelImportResult = ExcelImportUtil.importExcelMore(file.getInputStream(), OracleTerminalExcel.class, importParams);

            //如果存在非法数据，将不合格的数据导出
            if (terminalExcelExcelImportResult.isVerifyFail()) {
                PoiUtil.exportFileByWorkbook(terminalExcelExcelImportResult.getFailWorkbook(), "非法台账信息.xlsx", response);
                return null;
            } else {
                //执行台账信息导入（不考虑，存在监测点却不存在限值信息）
                return dealData(terminalExcelExcelImportResult.getList());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(DeviceResponseEnum.IMPORT_ORACLE_EXCEPTION);
        }

    }

    @Override
    public String importUpdateLedger(MultipartFile file, HttpServletResponse response) {
        ImportParams importParams = new ImportParams();
        importParams.setHeadRows(1);
        importParams.setTitleRows(1);
        importParams.setNeedVerify(true);

        try {
            ExcelImportResult<PmsLedgerExcel> terminalExcelExcelImportResult = ExcelImportUtil.importExcelMore(file.getInputStream(), PmsLedgerExcel.class, importParams);

            //如果存在非法数据，将不合格的数据导出
            if (terminalExcelExcelImportResult.isVerifyFail()) {
                PoiUtil.exportFileByWorkbook(terminalExcelExcelImportResult.getFailWorkbook(), "非法台账信息.xlsx", response);
                return null;
            } else {
                //执行台账信息导入（不考虑，存在监测点却不存在限值信息）
                return dealDataBatchUpdate(terminalExcelExcelImportResult.getList());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(DeviceResponseEnum.IMPORT_ORACLE_EXCEPTION);
        }
    }

    @Override
    public List<Overlimit> getAllLineOverLimit() {
        return overlimitMapper.selectList(null);
    }

    @Override
    public Map<String, List<String>> getLineBySubstationRelation(Integer devDataType) {
        //获取主网监测点信息
        if (devDataType == 0) {
            List<Monitor> list = this.list();
            return list.stream()
                    .collect(Collectors.groupingBy(Monitor::getPowerrId, Collectors.mapping(Monitor::getId, Collectors.toList())));
        }
        return null;
    }

    @Override
    public LineDTO getLineDetail(String id) {
        List<DictData> voltage = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.DEV_VOLTAGE.getCode()).getData();
        Map<String, String> voltageMap = voltage.stream().collect(Collectors.toMap(DictData::getId, DictData::getValue));
        List<DictData> connect = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.DEV_CONNECT.getCode()).getData();
        Map<String, String> connectMap = connect.stream().collect(Collectors.toMap(DictData::getId, DictData::getValue));
        LineDTO lineDTO = this.baseMapper.selectLineDetail(id);
        if (voltageMap.containsKey(lineDTO.getVoltageLevel()) && connectMap.containsKey(lineDTO.getPtType())) {
            lineDTO.setVoltageLevel(voltageMap.get(lineDTO.getVoltageLevel()));
            lineDTO.setPtType(connectMap.get(lineDTO.getPtType()));
            return lineDTO;
        }
        return null;
    }

    /**
     * 批量根据监测点id获取监测点信息
     */
    @Override
    public List<LineDTO> getLineDetailBatch(List<String> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            return null;
        }
        List<LineDTO> lineDTOS = this.baseMapper.selectLineDetailBatch(ids);
        //电压等级
        Map<String, List<LineDTO>> lineVoltageMap = lineDTOS.stream().collect(Collectors.groupingBy(LineDTO::getVoltageLevel));
        List<DictData> voltageList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.DEV_VOLTAGE.getCode()).getData();
        Map<String, String> voltageMap = voltageList.stream().collect(Collectors.toMap(DictData::getId, DictData::getValue));
        lineVoltageMap.forEach((key, lineData) -> {
            String voltage = voltageMap.get(key);
            lineData = lineData.stream().peek(line -> line.setVoltageLevel(voltage)).collect(Collectors.toList());
        });
        //接线方式
        Map<String, List<LineDTO>> linePtTypeMap = lineDTOS.stream().collect(Collectors.groupingBy(LineDTO::getPtType));
        List<DictData> connect = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.DEV_CONNECT.getCode()).getData();
        Map<String, String> connectMap = connect.stream().collect(Collectors.toMap(DictData::getId, DictData::getValue));
        linePtTypeMap.forEach((key, lineData) -> {
            String ptType = connectMap.get(key);
            lineData = lineData.stream().peek(line -> line.setPtType(ptType)).collect(Collectors.toList());
        });
        return lineDTOS;
    }

    @Override
    public List<Dept> existMonitorDeptTree() {
        DictData dictData = dicDataFeignClient.getDicDataByNameAndTypeName(DicDataTypeEnum.LINE_STATE.getName(), DicDataEnum.RUN.getName()).getData();
        List<Dept> deptList = deptFeignClient.getAllDept().getData();
        List<String> monitorList = this.lambdaQuery().select(Monitor::getOrgId).eq(Monitor::getMonitorState,dictData.getId()).list().stream().map(Monitor::getOrgId).distinct().collect(Collectors.toList());
        return deptList.stream().filter(it->monitorList.contains(it.getCode())).collect(Collectors.toList());
    }

    @Override
    public LineALLInfoDTO getLineAllDetail(String id) {
        LineALLInfoDTO lineALLInfoDTO = new LineALLInfoDTO();
        Monitor monitor = this.getBaseMapper().selectById(id);

        PmsTerminal pmsTerminal = terminalMapper.selectById(monitor.getTerminalId());
        //处理监测点信息
        LineALLInfoDTO.LineLineDTO lineLineDTO = new LineALLInfoDTO.LineLineDTO();
        lineLineDTO.setLineId(monitor.getId());
        lineLineDTO.setLinename(monitor.getLineName());
        lineLineDTO.setObjName(monitor.getMonitorObjectName());
        lineLineDTO.setLoadType(dicDataFeignClient.getDicDataById(monitor.getMonitorTag()).getData().getName());
        //电压使用母线电压
        lineLineDTO.setVoltageLevel(dicDataFeignClient.getDicDataById(monitor.getVoltageLevel()).getData().getName());
        lineALLInfoDTO.setLineLineDTO(lineLineDTO);
        //处理母线信息
        LineALLInfoDTO.LineBusbarDTO lineBusbarDTO = new LineALLInfoDTO.LineBusbarDTO();
        lineBusbarDTO.setBusBarId(monitor.getLineId());
        lineBusbarDTO.setBusBarName(monitor.getLineName());
        lineALLInfoDTO.setLineBusbarDTO(lineBusbarDTO);
        //处理设备信息
        LineALLInfoDTO.LineDeviceDTO lineDeviceDTO = new LineALLInfoDTO.LineDeviceDTO();
        lineDeviceDTO.setDeviceId(monitor.getTerminalId());
        lineDeviceDTO.setDeviceName(pmsTerminal.getName());
        lineALLInfoDTO.setLineDeviceDTO(lineDeviceDTO);
        //处理电站信息
        LineALLInfoDTO.LineSubStationDTO lineSubStationDTO = new LineALLInfoDTO.LineSubStationDTO();
        lineSubStationDTO.setSubStationId(monitor.getPowerrId());
        lineSubStationDTO.setSubStationName(monitor.getPowerrName());

        lineALLInfoDTO.setLineSubStationDTO(lineSubStationDTO);
        //todo 处理部门信息后续需要部门信息在添加


        return lineALLInfoDTO;
    }

    @Override
    public Page<TypicalSourceOnLine> monitorTypicalList(TypicalSourceParam param) {
        List<TypicalSourceOnLine> info = new ArrayList<>();
        TypicalSourceOnLine typicalSourceOnLine;
        List<String> objTypeIds = new ArrayList<>();
        LambdaQueryWrapper<Monitor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(param.getOrgId())) {
            List<String> data = deptFeignClient.getDepSonSelfCodetByCode(param.getOrgId()).getData();
            lambdaQueryWrapper.in(Monitor::getOrgId, data);
        }
        if ("04".equals(param.getStatisticsType())) {
            //特殊处理
            List<SysDicTreePO> sysDicTreePOList = dictTreeFeignClient.queryAll().getData();
            List<SysDicTreePO> typicDic = sysDicTreePOList.stream()
                    .filter(item -> Objects.equals(DicTreeEnum.Power_Station.getCode(), item.getCode()) ||
                            Objects.equals(DicTreeEnum.Ele_Railways.getCode(), item.getCode()) ||
                            Objects.equals(DicTreeEnum.Wind_Farms.getCode(), item.getCode()) ||
                            Objects.equals(DicTreeEnum.Imp_Users.getCode(), item.getCode()))
                    .collect(Collectors.toList());

            for (SysDicTreePO sysDicTreePO : typicDic) {
                List<DictTreeVO> temList = dictTreeFeignClient.query(sysDicTreePO.getId()).getData();
                List<String> ids = temList.stream().map(DictTreeVO::getId).collect(Collectors.toList());
                objTypeIds.addAll(ids);
                objTypeIds.add(sysDicTreePO.getId());
            }
            lambdaQueryWrapper.notIn(Monitor::getObjType, objTypeIds);
        } else {
            //01-牵引站,02-风电场,03-光伏电站,04-其他干扰用户
            String code;
            switch (param.getStatisticsType()) {
                case "01":
                    code = DicTreeEnum.Ele_Railways.getCode();
                    break;
                case "02":
                    code = DicTreeEnum.Wind_Farms.getCode();
                    break;
                case "03":
                    code = DicTreeEnum.Power_Station.getCode();
                    break;
                default:
                    return new Page<>(param.getPageNum(), param.getPageSize());
            }
            String id = dictTreeFeignClient.queryByCode(code).getData().getId();
            List<DictTreeVO> objType = dictTreeFeignClient.query(id).getData();
            objTypeIds.add(id);
            if (CollUtil.isNotEmpty(objType)) {
                objTypeIds.addAll(objType.stream().map(DictTreeVO::getId).collect(Collectors.toList()));
            }
            lambdaQueryWrapper.in(Monitor::getObjType, objTypeIds);
        }

        //获取监测点信息
        lambdaQueryWrapper.eq(Monitor::getIsUpToGrid, 1);
        lambdaQueryWrapper.in(CollUtil.isNotEmpty(param.getMonitorIds()),Monitor::getId,param.getMonitorIds());
        Page<Monitor> monitorList = this.page(new Page<>(param.getPageNum(), param.getPageSize()), lambdaQueryWrapper);
        //线路变电站
        List<String> lineIds = monitorList.getRecords().stream().map(Monitor::getLineId).distinct().collect(Collectors.toList());
        List<String> powerIds = monitorList.getRecords().stream().map(Monitor::getPowerrId).distinct().collect(Collectors.toList());
        List<GeneratrixWire> wiresList =new ArrayList<>();
        List<StatationStat> stationStats=new ArrayList<>();
        if(CollUtil.isNotEmpty(lineIds)){
            wiresList.addAll(generatrixWireMapper.selectBatchIds(lineIds));
        }
        if(CollUtil.isNotEmpty(powerIds)){
            stationStats.addAll(statationStatMapper.selectBatchIds(powerIds));
        }
        Map<String, GeneratrixWire> wireMap = wiresList.stream().collect(Collectors
                .toMap(GeneratrixWire::getId, Function.identity()));
        Map<String, StatationStat> powerMap = stationStats.stream().collect(Collectors
                .toMap(StatationStat::getPowerId, Function.identity()));
        //电压等级
        List<DictData> voltage = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.DEV_VOLTAGE.getCode()).getData();
        Map<String, DictData> mapVoltage = voltage.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));
        //运行状态
        List<DictData> lineState = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.LINE_STATE.getCode()).getData();
        Map<String, DictData> mapLineState = lineState.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));
        //分类行业
        List<DictData> industryType = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.INDUSTRY_TYPE.getCode()).getData();
        Map<String, DictData> mapIndustryType = industryType.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));
        //获取已存在牵引站的信息
        List<String> tractionIds = monitorList.getRecords().stream().map(Monitor::getTractionId).collect(Collectors.toList());
        List<TractionStation> tractionStationList =new ArrayList<>();
        if(CollUtil.isNotEmpty(powerIds)){
            tractionStationList.addAll(tractionStationService.list(new LambdaQueryWrapper<TractionStation>()
                    .in(TractionStation::getId, tractionIds)));
        }
        Map<String, TractionStation> tractionMap = tractionStationList.stream().collect(Collectors.toMap(TractionStation::getId, Function.identity()));
        TractionStation traction;
        for (Monitor monitor : monitorList.getRecords()) {
            typicalSourceOnLine = new TypicalSourceOnLine();
            typicalSourceOnLine.setId(monitor.getId());
            typicalSourceOnLine.setMonitorId(monitor.getMonitorId());
            typicalSourceOnLine.setName(monitor.getName());
            //母线的电压等级
            if (wireMap.containsKey(monitor.getLineId())) {
                GeneratrixWire generatrixWire = wireMap.get(monitor.getLineId());
                typicalSourceOnLine.setBusId(generatrixWire.getMidBusId());
                typicalSourceOnLine.setBusName(generatrixWire.getName());
                if (mapVoltage.containsKey(generatrixWire.getScale())) {
                    typicalSourceOnLine.setBusVoltageLevel(String.format("%02d", mapVoltage.get(generatrixWire.getScale()).getAlgoDescribe()));
                    typicalSourceOnLine.setBusVoltageLevelName(mapVoltage.get(generatrixWire.getScale()).getName());
                }
            }
            typicalSourceOnLine.setCapacity(monitor.getUserAgreementCapacity().toString());
            typicalSourceOnLine.setCityOrg(monitor.getOrgId());
            typicalSourceOnLine.setCityOrgName(monitor.getOrgName());
            typicalSourceOnLine.setEffectMonitorNum(1);
            typicalSourceOnLine.setMaintOrg(monitor.getOperationId());
            typicalSourceOnLine.setMaintOrgName(monitor.getOperationName());
            typicalSourceOnLine.setMonitorObjectType(monitor.getFieldStation());
            typicalSourceOnLine.setMonitorObjectTypeName(monitorObjectTypeName(monitor.getFieldStation()));
            //运行状态
            if (mapLineState.containsKey(monitor.getMonitorState())) {
                typicalSourceOnLine.setRunStatus(mapLineState.get(monitor.getMonitorState()).getValue());
                typicalSourceOnLine.setRunStatusName(mapLineState.get(monitor.getMonitorState()).getName());
            }
            //变电站
            if (powerMap.containsKey(monitor.getPowerrId())) {
                StatationStat statationStat = powerMap.get(monitor.getPowerrId());
                typicalSourceOnLine.setStationId(statationStat.getMidStationId());
                typicalSourceOnLine.setStationName(statationStat.getPowerName());
                typicalSourceOnLine.setMainSubstationId(statationStat.getMidStationId());
                typicalSourceOnLine.setMainSubstationName(statationStat.getPowerName());
                if (mapVoltage.containsKey(statationStat.getVoltageLevel())) {
                    typicalSourceOnLine.setStationVoltageLevel(String.format("%02d", mapVoltage.get(statationStat.getVoltageLevel()).getAlgoDescribe()));
                    typicalSourceOnLine.setStationVoltageLevelName(mapVoltage.get(statationStat.getVoltageLevel()).getName());
                }
                //牵引站的主备变电站
                if (StrUtil.isNotBlank(monitor.getTractionId())) {
                    typicalSourceOnLine.setMainVoltageLevel(String.format("%02d", mapVoltage.get(statationStat.getVoltageLevel()).getAlgoDescribe()));
                    typicalSourceOnLine.setMainVoltageLevelName(mapVoltage.get(statationStat.getVoltageLevel()).getName());
                }
            }
//            typicalSourceOnLine.setStationType();
            //行业分类
            if (mapIndustryType.containsKey(monitor.getTradeCode())) {
                typicalSourceOnLine.setTradeCode(mapIndustryType.get(monitor.getTradeCode()).getValue());
                typicalSourceOnLine.setTradeCodeName(mapIndustryType.get(monitor.getTradeCode()).getName());
            }
            //电压等级
            if (mapVoltage.containsKey(monitor.getVoltageLevel())) {
                typicalSourceOnLine.setVoltageLevel(String.format("%02d", mapVoltage.get(monitor.getVoltageLevel()).getAlgoDescribe()));
                typicalSourceOnLine.setVoltageLevelName(mapVoltage.get(monitor.getVoltageLevel()).getName());
            }
            //根据是否存在牵引站id来判断是否存在牵引站
            if (StrUtil.isNotBlank(monitor.getTractionId())) {
                if (tractionMap.containsKey(monitor.getTractionId())) {
                    traction = tractionMap.get(monitor.getTractionId());
                    typicalSourceOnLine.setName(traction.getName());
                    //牵引站的主备变电站
                    if (mapVoltage.containsKey(traction.getVoltageLevel())) {
                        typicalSourceOnLine.setMainVoltageLevel(String.format("%02d", mapVoltage.get(traction.getVoltageLevel()).getAlgoDescribe()));
                        typicalSourceOnLine.setMainVoltageLevelName(mapVoltage.get(traction.getVoltageLevel()).getName());
                    }
                    typicalSourceOnLine.setRailWayName(traction.getRailwayLineName());
                    typicalSourceOnLine.setRailWayNumber(traction.getRailwayLineId());
                    typicalSourceOnLine.setRailWayType(traction.getRailwayType());
                    typicalSourceOnLine.setRailWayTypeName(railWayTypeName(traction.getRailwayType()));

                }
//                typicalSourceOnLine.setAuxiliarySubstationId();
//                typicalSourceOnLine.setAuxiliarySubstationName();
//                typicalSourceOnLine.setAuxiliaryVoltageLevel();
//                typicalSourceOnLine.setAuxiliaryVoltageLevelName();

            }
            info.add(typicalSourceOnLine);
        }
        Page pmsPage = BeanUtil.copyProperties(monitorList, Page.class);
        pmsPage.setRecords(info);
        return pmsPage;
    }

    @Override
    public List<PollutionLineDTO> getLineInfo(List<String> ids) {
        List<PollutionLineDTO> result = new ArrayList<>();
        LambdaQueryWrapper<Monitor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(Monitor::getId,ids).eq(Monitor::getStatus,DataStateEnum.ENABLE.getCode());
        List<Monitor> monitors = this.list(lambdaQueryWrapper);
        monitors.forEach(item->{
            PollutionLineDTO pollutionLineDTO = new PollutionLineDTO();
            pollutionLineDTO.setId(item.getId());
            pollutionLineDTO.setName(item.getName());
            pollutionLineDTO.setBusBar(item.getLineId());
            pollutionLineDTO.setSubstationId(item.getPowerrId());
            pollutionLineDTO.setSubstation(item.getPowerrName());
            pollutionLineDTO.setPowerCompany(item.getOrgName());
            result.add(pollutionLineDTO);
        });
        return result;
    }

    private String monitorObjectTypeName(String name) {
        if(StrUtil.isNotBlank(name)){
            switch (name) {
                case "01":
                    return "在运站";
                case "02":
                    return "新(改、扩)建站";
            }
        }
        return null;
    }

    private String railWayTypeName(String name) {
        if(StrUtil.isNotBlank(name)){
            switch (name) {
                case "1":
                    return "高铁";
                case "2":
                    return "普铁";
            }
        }
        return null;
    }

    private String dealDataBatchUpdate(List<PmsLedgerExcel> pmsLedgerExcelList) {
        List<PmsLedgerExcel> oracleTerminalExcelMsg = new ArrayList<>();

        List<DeptDTO> allDept = deptFeignClient.getDeptDescendantIndexes(deptFeignClient.getRootDept().getData().getId(), Stream.of(0, 1, 2).collect(Collectors.toList())).getData();
        Map<String, DeptDTO> mapDept = allDept.stream().collect(Collectors.toMap(DeptDTO::getName, Function.identity()));

        List<DictData> voltageLevelDic = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.DEV_VOLTAGE.getCode()).getData();
        Map<String, DictData> voltageLevelMap = voltageLevelDic.stream().collect(Collectors.toMap(DictData::getName, Function.identity()));

        //装置型号
        List<DictData> devTypelDic = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.DEV_TYPE.getCode()).getData();
        Map<String, DictData> devTypelDicMap = devTypelDic.stream().collect(Collectors.toMap(DictData::getName, Function.identity()));

        //装置类别
        DictData devCategoryDic = dicDataFeignClient.getDicDataByNameAndTypeName(DicDataTypeEnum.DEV_CATEGORY.getName(), DicDataEnum.Monitor_Terminals.getName()).getData();

        //装置状态
        List<DictData> devStatelDic = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.DEV_STATUS.getCode()).getData();
        Map<String, DictData> devStateDicMap = devStatelDic.stream().collect(Collectors.toMap(DictData::getName, Function.identity()));

        //监测点状态
        List<DictData> monitorStatelDic = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.LINE_STATE.getCode()).getData();
        Map<String, DictData> monitorStateDicMap = monitorStatelDic.stream().collect(Collectors.toMap(DictData::getName, Function.identity()));

        //检测点对象类型（原监测点标签）
        List<DictData> objTypeList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.MONITORING_LABELS.getCode()).getData();
        Map<String, DictData> objTypeDicMap = objTypeList.stream().collect(Collectors.toMap(DictData::getName, Function.identity()));

        //装置厂家
        List<DictData> manList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.DEV_MANUFACTURER.getCode()).getData();
        Map<String, DictData> manDicMap = manList.stream().collect(Collectors.toMap(DictData::getName, Function.identity()));

        //装作等级
        DictData devGrade = dicDataFeignClient.getDicDataByNameAndTypeName(DicDataTypeEnum.DEV_GRADE.getName(), DicDataEnum.MOST_IMPORMENT.getName()).getData();

        //
        DictData devInputType = dicDataFeignClient.getDicDataByNameAndTypeName(DicDataTypeEnum.INPUT_SIGNAL.getName(), DicDataEnum.SIMULATION_SIGNAL.getName()).getData();

        //监测点类型
        DictData monitorType = dicDataFeignClient.getDicDataByNameAndTypeName(DicDataTypeEnum.LINE_TYPE.getName(), DicDataEnum.Power_Supply_Point.getName()).getData();

        //接线方式
        List<DictData> wireList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.DEV_CONNECT.getCode()).getData();
        Map<String, DictData> wireListMap = wireList.stream().collect(Collectors.toMap(DictData::getName, Function.identity()));

        //电压互感器类型
        List<DictData> potentialDic = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.VOLTAGE_TRANSFORMER.getCode()).getData();
        Map<String, DictData> potentialDicMap = potentialDic.stream().collect(Collectors.toMap(DictData::getName, Function.identity()));

        //中性点接地方式
        List<DictData> neutralDic = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.Neutral_Point.getCode()).getData();
        Map<String, DictData> neutralDicMap = neutralDic.stream().collect(Collectors.toMap(DictData::getName, Function.identity()));


        //行业分类
        List<DictData> businessType = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.INDUSTRY_TYPE.getCode()).getData();
        Map<String, DictData> businessDicMap = businessType.stream().collect(Collectors.toMap(DictData::getName, Function.identity()));


        //TODO 零时处理
        List<SysDicTreePO> dicTree = dictTreeFeignClient.queryAll().getData();
        dicTree = dicTree.stream().filter(item->item.getCode()!="Device_Unit" && !item.getCode().contains("@")).collect(Collectors.toList());
        Map<String,SysDicTreePO> objTypeMap = dicTree.stream().collect(Collectors.toMap(SysDicTreePO::getName,Function.identity()));

        int count = 0;
        for (PmsLedgerExcel pmsLedgerExcel : pmsLedgerExcelList) {


            LambdaQueryWrapper<Monitor> monitorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            monitorLambdaQueryWrapper.eq(Monitor::getName,pmsLedgerExcel.getName()).eq(Monitor::getPowerrName,pmsLedgerExcel.getPowerrName());

           Monitor monitor =  this.getOne(monitorLambdaQueryWrapper);
           if(Objects.nonNull(monitor)){

               Monitor po = new Monitor();
               po.setId(monitor.getId());
               po.setMinShortCircuitCapacity(pmsLedgerExcel.getMinShortCircuitCapacity());
               po.setPowerSupplyEqCapacity(pmsLedgerExcel.getPowerSupplyEqCapacity());
               po.setUserAgreementCapacity(pmsLedgerExcel.getUserAgreementCapacity());


               String monitorStateId= monitorStateDicMap.get(pmsLedgerExcel.getMonitorState()).getId();
               if(StrUtil.isBlank(monitorStateId)){
                   throw new BusinessException("监测点状态为空");
               }
               po.setMonitorState(monitorStateId);

               String getPotentialTransFormerTypeId= potentialDicMap.get(pmsLedgerExcel.getPotentialTransFormerType()).getId();

               if(StrUtil.isBlank(getPotentialTransFormerTypeId)){
                   throw new BusinessException("电压互感器类型缺失");
               }
               po.setPotentialTransFormerType(getPotentialTransFormerTypeId);


               String neutralDicMapId= neutralDicMap.get(pmsLedgerExcel.getNeutralGroundingMode()).getId();

               if(StrUtil.isBlank(neutralDicMapId)){
                   throw new BusinessException("中性点接地方式缺失");
               }
               po.setPotentialTransFormerType(getPotentialTransFormerTypeId);
               po.setIsSpecialSupplyElectricity(pmsLedgerExcel.getIsSpecialSupplyElectricity());

               String getMonitorTagId = objTypeDicMap.get(pmsLedgerExcel.getMonitorTag()).getId();
               if(StrUtil.isBlank(getMonitorTagId)){
                   throw new BusinessException("监测点标签缺失");
               }
               po.setMonitorTag(getMonitorTagId);


               String getObjTypeId = objTypeMap.get(pmsLedgerExcel.getObjType()).getId();
               if(StrUtil.isBlank(getObjTypeId)){
                   throw new BusinessException("对象类型缺少");
               }
               po.setObjType(getObjTypeId);


               //行业分类
               if(businessDicMap.containsKey(pmsLedgerExcel.getTradeCode())){
                   String getTradeCodeId = businessDicMap.get(pmsLedgerExcel.getTradeCode()).getId();
                   po.setTradeCode(getTradeCodeId);
               }else {
                   po.setTradeCode("");
               }


               //监测对象名称
               po.setMonitorObjectName(pmsLedgerExcel.getMonitorObjectName());




               //装置
            /*  PmsTerminal pmsTerminal = terminalMapper.selectOne(new LambdaQueryWrapper<PmsTerminal>().eq(PmsTerminal::getId,monitor.getTerminalId()));

              if(Objects.nonNull(pmsTerminal)){
                  PmsTerminal t = new PmsTerminal();
                  t.setId(pmsTerminal.getId());
                  t.setTerminalCode(pmsLedgerExcel.getTerminalCode());
                  t.setIp(pmsLedgerExcel.getDevIp());
                  terminalMapper.updateById(t);
              }*/








              po.setTerminalCode(pmsLedgerExcel.getTerminalCode());


              if(StrUtil.isNotBlank(po.getTerminalCode())){
                  po.setIsUpToGrid(1);
              }


               if(StrUtil.isBlank(pmsLedgerExcel.getBusId())){
                   po.setIsUpToGrid(0);
               }


              this.updateById(po);








               count++;
           }else {

               System.out.println("4444444444444444");

           }

        }

        if (CollectionUtil.isNotEmpty(oracleTerminalExcelMsg)) {
            ExcelUtil.exportExcel("失败列表.xlsx", OracleTerminalExcel.OracleTerminalExcelMsg.class, oracleTerminalExcelMsg);
            return null;
        }
        return CommonResponseEnum.SUCCESS.getMessage();
    }


    /**
     * 获取主配网监测点id集合
     *
     * @param deptDTO
     * @param deptIdList
     * @return
     */
    private DeptGetChildrenDTO getPmsMonitor(DeptDTO deptDTO, DictData dictData, List<String> deptIdList, Integer systemType) {
        DeptGetChildrenDTO pmsDeptGetChildrenDTO = new DeptGetChildrenDTO();
        pmsDeptGetChildrenDTO.setDeptId(deptDTO.getCode());
        if (deptDTO.getType() == 0) {
            pmsDeptGetChildrenDTO.setDeptName(deptDTO.getArea());
        } else {
            pmsDeptGetChildrenDTO.setDeptName(deptDTO.getName());
        }
        pmsDeptGetChildrenDTO.setDeptChildren(deptIdList);
        if (CollUtil.isNotEmpty(deptIdList)) {
            //主网监测点
            if (systemType == 0 || systemType == 2) {
                List<Monitor> monitorList = this.list(new LambdaQueryWrapper<Monitor>()
                        .select(Monitor::getId)
                        .eq(Monitor::getMonitorState, dictData.getId())
                        .in(CollUtil.isNotEmpty(deptIdList), Monitor::getOrgId, deptIdList));
                pmsDeptGetChildrenDTO.setLineIds(monitorList.stream().map(Monitor::getId).distinct().collect(Collectors.toList()));
            }else {
                pmsDeptGetChildrenDTO.setLineIds(new ArrayList<>());
            }

            if (systemType == 1 || systemType == 2) {
                //配网监测点
                List<PmsMonitorBaseDTO> pwMonitorList = iDistributionMonitorService.getMonitorByCondition(deptIdList, null);
                pmsDeptGetChildrenDTO.setPwMonitorIds(pwMonitorList.stream().map(PmsMonitorBaseDTO::getMonitorId).distinct().collect(Collectors.toList()));
            }else {
                pmsDeptGetChildrenDTO.setPwMonitorIds(new ArrayList<>());
            }
        } else {
            pmsDeptGetChildrenDTO.setLineIds(new ArrayList<>());
            pmsDeptGetChildrenDTO.setPwMonitorIds(new ArrayList<>());
        }
        return pmsDeptGetChildrenDTO;
    }

    private void checkParam(MonitorParam monitorParam, boolean update) {

        //校验同一单位下面不能有同名1类监测点
        LambdaQueryWrapper<Monitor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Monitor::getName, monitorParam.getName())
                .eq(Monitor::getPowerrId, monitorParam.getPowerrId())
                .eq(Monitor::getStatus, DataStateEnum.ENABLE.getCode());

        if (update) {
            lambdaQueryWrapper.ne(Monitor::getId, monitorParam.getId());
        }

        int count = this.count(lambdaQueryWrapper);
        if (count > 0) {
            throw new BusinessException(PmsDeviceResponseEnum.DEPT_MONITOR_REPEAT);
        }

        //校验电压等级数据
        DictData voltageDic = dicDataFeignClient.getDicDataById(monitorParam.getVoltageLevel()).getData();
        if (Objects.isNull(voltageDic)) {
            throw new BusinessException(SystemResponseEnum.VOLTAGE_EMPTY);
        }

        //校验监测点状态
        DictData stateDic = dicDataFeignClient.getDicDataById(monitorParam.getMonitorState()).getData();
        if (Objects.isNull(stateDic)) {
            throw new BusinessException(SystemResponseEnum.LINE_STATE_EMPTY);
        }

        //校验监测点类型
        DictData typeDic = dicDataFeignClient.getDicDataById(monitorParam.getMonitorType()).getData();
        if (Objects.isNull(typeDic)) {
            throw new BusinessException(SystemResponseEnum.LINE_TYPE_EMPTY);
        }

        //校验电压互感器
        DictData potentialDic = dicDataFeignClient.getDicDataById(monitorParam.getPotentialTransFormerType()).getData();
        if (Objects.isNull(potentialDic)) {
            throw new BusinessException(SystemResponseEnum.POTENTIAL_TYPE_EMPTY);
        }

        //校验中性点接地方式
        DictData neutralDic = dicDataFeignClient.getDicDataById(monitorParam.getNeutralGroundingMode()).getData();
        if (Objects.isNull(neutralDic)) {
            throw new BusinessException(SystemResponseEnum.Neutral_Mode_EMPTY);
        }

        //校验监测点标签
        DictData tagDic = dicDataFeignClient.getDicDataById(monitorParam.getMonitorTag()).getData();
        if (Objects.isNull(tagDic)) {
            throw new BusinessException(SystemResponseEnum.MONITOR_TAG_EMPTY);
        }


        //校验监测终端接线方式
        DictData wireDic = dicDataFeignClient.getDicDataById(monitorParam.getTerminalWiringMethod()).getData();
        if (Objects.isNull(wireDic)) {
            throw new BusinessException(SystemResponseEnum.TERMINAL_WIRING_EMPTY);
        }
    }

    private void checkOther(MonitorParam monitorParam, Monitor monitor, boolean update) {
        //校验组织机构
        Dept dept = deptFeignClient.getDeptByCode(monitorParam.getOrgId()).getData();
        if (Objects.isNull(dept)) {
            throw new BusinessException(PmsDeviceResponseEnum.ORG_ITEM_EMPTY);
        }

        //校验运维单位
        Dept deptOp = deptFeignClient.getDeptByCode(monitorParam.getOperationId()).getData();
        if (Objects.isNull(deptOp)) {
            throw new BusinessException(PmsDeviceResponseEnum.Operation_ITEM_EMPTY);
        }

        //校验线路
        GeneratrixWire generatrix = generatrixWireMapper.selectById(monitorParam.getLineId());
        if (Objects.isNull(generatrix)) {
            throw new BusinessException(PmsDeviceResponseEnum.VOLTAGE_EMPTY);
        }

    }


    /**
     * 监测点限值计算
     */
    public Overlimit overLimitCal(MonitorParam monitorParam, Monitor monitor) {
        //主网测点限值计算
        DictData dictData = dicDataFeignClient.getDicDataById(monitor.getVoltageLevel()).getData();
        float voltageLevel = Float.parseFloat(dictData.getValue());
        Overlimit overlimit = COverlimitUtil.globalAssemble(voltageLevel, monitor.getUserAgreementCapacity(), monitor.getPowerSupplyEqCapacity(), monitor.getMinShortCircuitCapacity(), 1, 0);
        if (Objects.nonNull(monitorParam.getVoltageDeviationUpperLimit())) {
            monitor.setVoltageDeviationUpperLimit(monitorParam.getVoltageDeviationUpperLimit());
            overlimit.setVoltageDev(monitorParam.getVoltageDeviationUpperLimit());
        } else {
            monitor.setVoltageDeviationUpperLimit(overlimit.getVoltageDev());
        }
        if (Objects.nonNull(monitorParam.getVoltageDeviationLowerLimit())) {
            monitor.setVoltageDeviationLowerLimit(monitorParam.getVoltageDeviationLowerLimit());
            overlimit.setUvoltageDev(monitorParam.getVoltageDeviationLowerLimit());
        } else {
            monitor.setVoltageDeviationLowerLimit(overlimit.getUvoltageDev());
        }
        return overlimit;
    }


    // 初始化字典数据的通用方法
    private Map<String, DictData> initDictData(DicDataTypeEnum type) {
        return dicDataFeignClient.getDicDataByTypeCode(type.getCode()).getData()
                .stream().collect(Collectors.toMap(DictData::getName, Function.identity()));
    }


    private String dealData(List<OracleTerminalExcel> oracleTerminalExcelList) {
        List<OracleTerminalExcel.OracleTerminalExcelMsg> oracleTerminalExcelMsg = new ArrayList<>();

        List<DeptDTO> allDept = deptFeignClient.getDeptDescendantIndexes(deptFeignClient.getRootDept().getData().getId(), Stream.of(0, 1, 2).collect(Collectors.toList())).getData();
        Map<String, DeptDTO> mapDept = allDept.stream().collect(Collectors.toMap(DeptDTO::getName, Function.identity()));

        Map<String, DictData> voltageLevelMap = initDictData(DicDataTypeEnum.DEV_VOLTAGE);

        //装置型号
        Map<String, DictData> devTypelDicMap = initDictData(DicDataTypeEnum.DEV_TYPE);

        //装置状态
        Map<String, DictData> devStateDicMap = initDictData(DicDataTypeEnum.DEV_STATUS);

        //监测点状态
        Map<String, DictData> monitorStateDicMap = initDictData(DicDataTypeEnum.LINE_STATE);

        //监测点标签
        Map<String, DictData> objTypeDicMap = initDictData(DicDataTypeEnum.MONITORING_LABELS);

        //装置厂家
        Map<String, DictData> manDicMap = initDictData(DicDataTypeEnum.DEV_MANUFACTURER);

        //接线方式
        Map<String, DictData> wireListMap = initDictData(DicDataTypeEnum.DEV_CONNECT);

        //装作等级
        DictData devGrade = dicDataFeignClient.getDicDataByNameAndTypeName(DicDataTypeEnum.DEV_GRADE.getName(), DicDataEnum.MOST_IMPORMENT.getName()).getData();

        //
        DictData devInputType = dicDataFeignClient.getDicDataByNameAndTypeName(DicDataTypeEnum.INPUT_SIGNAL.getName(), DicDataEnum.SIMULATION_SIGNAL.getName()).getData();

        //监测点类型
        DictData monitorType = dicDataFeignClient.getDicDataByNameAndTypeName(DicDataTypeEnum.LINE_TYPE.getName(), DicDataEnum.Power_Supply_Point.getName()).getData();

        DictData potentialDic = dicDataFeignClient.getDicDataByCodeAndType(DicDataEnum.Cap_V.getCode(),DicDataTypeEnum.VOLTAGE_TRANSFORMER.getCode()).getData();

        DictData neutralDic = dicDataFeignClient.getDicDataByNameAndTypeName(DicDataTypeEnum.Neutral_Point.getName(), DicDataEnum.Ground_Res.getName()).getData();
        //装置类别
        DictData devCategoryDic = dicDataFeignClient.getDicDataByNameAndTypeName(DicDataTypeEnum.DEV_CATEGORY.getName(), DicDataEnum.Monitor_Terminals.getName()).getData();


        //对象类型
        List<SysDicTreePO> dicTree = dictTreeFeignClient.queryAll().getData();
        dicTree = dicTree.stream().filter(item->item.getCode()!="Device_Unit" && !item.getCode().contains("@")).collect(Collectors.toList());
        Map<String,SysDicTreePO> objTypeMap = dicTree.stream().collect(Collectors.toMap(SysDicTreePO::getName,Function.identity()));



        for (OracleTerminalExcel oracleTerminalExcel : oracleTerminalExcelList) {

            //单位
            if (oracleTerminalExcel.getGdName().equals("省检修")) {
                oracleTerminalExcel.setGdName("国网河北超高压公司本部");
            } else {
                oracleTerminalExcel.setGdName("国网" + oracleTerminalExcel.getGdName() + "本部");
            }

            if (!mapDept.containsKey(oracleTerminalExcel.getGdName())) {
                oracleTerminalExcelMsg.add(assembleMsg(oracleTerminalExcel, "单位名称不存在，请确认单位名称是否正确"));
                continue;
            }

            //判断是否操作过该条记录
            LineBak lineBak = lineBakMapper.selectOne(new LambdaQueryWrapper<LineBak>().eq(LineBak::getLineId, oracleTerminalExcel.getId()));
            DeviceBak deviceBak = deviceBakMapper.selectOne(new LambdaQueryWrapper<DeviceBak>().eq(DeviceBak::getDevId, oracleTerminalExcel.getDeviceId()));


            //单位
            DeptDTO deptDTO = mapDept.get(oracleTerminalExcel.getGdName());

            //电站
            String stationId = null, stationName = null;
            LambdaQueryWrapper<StatationStat> statLambdaQueryWrapper = new LambdaQueryWrapper<>();
            statLambdaQueryWrapper.eq(StatationStat::getPowerName, oracleTerminalExcel.getSubstationName())
                    .eq(StatationStat::getOrgId, deptDTO.getCode());
            StatationStat statationStat = statationStatMapper.selectOne(statLambdaQueryWrapper);

            StatationStat statationStatPO = new StatationStat();
            statationStatPO.setOrgId(deptDTO.getCode());
            statationStatPO.setOrgName(deptDTO.getName());
            statationStatPO.setPowerName(oracleTerminalExcel.getSubstationName());
            statationStatPO.setLongitude(oracleTerminalExcel.getLng().doubleValue());
            statationStatPO.setLatitude(oracleTerminalExcel.getLat().doubleValue());
            statationStatPO.setShouldBeNum(100);
            statationStatPO.setStatus(DataStateEnum.ENABLE.getCode());

            String dicVoltage = dealVoltageLevel(oracleTerminalExcel.getSubStationScale());
            if (voltageLevelMap.containsKey(dicVoltage)) {
                statationStatPO.setVoltageLevel(voltageLevelMap.get(dicVoltage).getId());
            } else {
                oracleTerminalExcelMsg.add(assembleMsg(oracleTerminalExcel, "字典变电站电压等级不存在，请确认电压等级存在"));
                continue;
            }
            if (Objects.isNull(statationStat)) {
                statationStatMapper.insert(statationStatPO);
                stationId = statationStatPO.getPowerId();
                stationName = statationStatPO.getPowerName();
            } else {
                //更新信息
                statationStatPO.setPowerId(statationStat.getPowerId());
                statationStatMapper.updateById(statationStatPO);
                stationId = statationStat.getPowerId();
                stationName = statationStat.getPowerName();
            }

            //装置
            String devId = null;
            LambdaQueryWrapper<PmsTerminal> terminalLambdaQueryWrapper = new LambdaQueryWrapper<>();
            terminalLambdaQueryWrapper.eq(PmsTerminal::getName, oracleTerminalExcel.getDeviceName())
                    .eq(PmsTerminal::getPowerStationId, stationId);
            PmsTerminal pmsTerminal = terminalMapper.selectOne(terminalLambdaQueryWrapper);

            PmsTerminal pmsTerminalPO = new PmsTerminal();
            pmsTerminalPO.setOrgId(deptDTO.getCode());
            pmsTerminalPO.setOrgName(deptDTO.getName());
            pmsTerminalPO.setName(oracleTerminalExcel.getDeviceName());
            pmsTerminalPO.setOperationId(deptDTO.getCode());
            pmsTerminalPO.setOperationName(deptDTO.getName());
            pmsTerminalPO.setPowerrName(stationName);
            pmsTerminalPO.setPowerStationId(stationId);
            pmsTerminalPO.setIp(oracleTerminalExcel.getIp());
            pmsTerminalPO.setUseDate(oracleTerminalExcel.getLoginTime());
            pmsTerminalPO.setVerificationDate(oracleTerminalExcel.getThisTimeCheck());
            pmsTerminalPO.setDeviceCategory(devCategoryDic.getId());

            if (devTypelDicMap.containsKey(oracleTerminalExcel.getDevType())) {
                pmsTerminalPO.setDeviceModel(devTypelDicMap.get(oracleTerminalExcel.getDevType()).getId());
            } else {
                oracleTerminalExcelMsg.add(assembleMsg(oracleTerminalExcel, "字典装置类型不存在，请确认后重试"));
                continue;
            }

            //终端状态
            String devState = null;
            switch (oracleTerminalExcel.getRunFlag()) {
                case 0:
                    devState = DicDataEnum.RUNNING.getName();
                    break;
                case 1:
                    devState = DicDataEnum.NOT_OPERATION.getName();
                    break;
                case 2:
                    devState = DicDataEnum.RETIRE.getName();
                    break;
            }
            if (devStateDicMap.containsKey(devState)) {
                pmsTerminalPO.setTerminalState(devStateDicMap.get(devState).getId());
            } else {
                oracleTerminalExcelMsg.add(assembleMsg(oracleTerminalExcel, "字典装置运行状态不存在，请确认后重试"));
                continue;
            }
            pmsTerminalPO.setTerminalLevel(devGrade.getId());
            pmsTerminalPO.setInputType(devInputType.getId());
            pmsTerminalPO.setStatus(DataStateEnum.ENABLE.getCode());
            pmsTerminalPO.setPort(oracleTerminalExcel.getPort().toString());
            pmsTerminalPO.setIsUpToGrid(0);
            //pmsTerminalPO.setId(or);

            if (manDicMap.containsKey(oracleTerminalExcel.getManufacturer())) {
                pmsTerminalPO.setManufacture(manDicMap.get(oracleTerminalExcel.getManufacturer()).getId());
            } else {
                oracleTerminalExcelMsg.add(assembleMsg(oracleTerminalExcel, "字典制造厂商不存在，请确认后重试"));
                continue;
            }
            if (Objects.isNull(pmsTerminal) && Objects.isNull(deviceBak)) {
                terminalMapper.insert(pmsTerminalPO);
                devId = pmsTerminalPO.getId();

                DeviceBak deviceBakPO = new DeviceBak();
                deviceBakPO.setId(devId);
                deviceBakPO.setDevId(oracleTerminalExcel.getDeviceId());
                deviceBakMapper.insert(deviceBakPO);
            } else {
                if (Objects.isNull(deviceBak)) {
                    pmsTerminalPO.setId(pmsTerminal.getId());
                    DeviceBak deviceBakPO = new DeviceBak();
                    deviceBakPO.setId(pmsTerminal.getId());
                    deviceBakPO.setDevId(oracleTerminalExcel.getDeviceId());
                    deviceBakMapper.insert(deviceBakPO);
                    terminalMapper.updateById(pmsTerminalPO);
                    devId = pmsTerminal.getId();
                } else {
                    devId = deviceBak.getId();
                    pmsTerminalPO.setId(devId);
                    terminalMapper.updateById(pmsTerminalPO);
                }

            }

            //线路
            LambdaQueryWrapper<GeneratrixWire> generatrixWireLambdaQueryWrapper = new LambdaQueryWrapper<>();
            generatrixWireLambdaQueryWrapper.eq(GeneratrixWire::getName, oracleTerminalExcel.getSubvName())
                    .eq(GeneratrixWire::getStationId, stationId);
            GeneratrixWire generatrixWire = generatrixWireMapper.selectOne(generatrixWireLambdaQueryWrapper);

            String lineId = null, lineName = null, genScale = null;
            GeneratrixWire generatrixWirePO = new GeneratrixWire();
            generatrixWirePO.setGeneratrixName(oracleTerminalExcel.getSubvName());
            generatrixWirePO.setStatus(DataStateEnum.ENABLE.getCode());
            generatrixWirePO.setName(oracleTerminalExcel.getSubvName());
            generatrixWirePO.setOrgId(deptDTO.getCode());
            generatrixWirePO.setStationId(stationId);
            generatrixWirePO.setStationName(stationName);

            String dicVoltagePms = dealVoltageLevel(oracleTerminalExcel.getSubvScale());
            if (voltageLevelMap.containsKey(dicVoltagePms)) {
                DictData temVoltage = voltageLevelMap.get(dicVoltagePms);
                generatrixWirePO.setScale(temVoltage.getId());
            } else {
                oracleTerminalExcelMsg.add(assembleMsg(oracleTerminalExcel, "字典母线电压等级不存在，请确认后重试"));
                continue;
            }

            if (Objects.isNull(generatrixWire)) {
                generatrixWireMapper.insert(generatrixWirePO);
                lineId = generatrixWirePO.getId();
                lineName = generatrixWirePO.getName();
                genScale = generatrixWirePO.getScale();
            } else {
                generatrixWirePO.setId(generatrixWire.getId());
                generatrixWireMapper.updateById(generatrixWirePO);
                lineId = generatrixWirePO.getId();
                lineName = generatrixWirePO.getName();
                genScale = generatrixWirePO.getScale();
            }

            //监测点
            LambdaQueryWrapper<Monitor> monitorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            monitorLambdaQueryWrapper.eq(Monitor::getLineId, lineId)
                    .eq(Monitor::getName, oracleTerminalExcel.getLineName());
            Monitor monitor = monitorMapper.selectOne(monitorLambdaQueryWrapper);


            //当前电站下面没有监测点，可以新增
            Monitor monitorPO = new Monitor();

            String monitorId = "04";
            String one = "";
            if (deptDTO.getName().contains("石家庄")) {
                one = "01";
            } else if (deptDTO.getName().contains("邯郸")) {
                one = "02";
            } else if (deptDTO.getName().contains("保定")) {
                one = "03";
            } else if (deptDTO.getName().contains("沧州")) {
                one = "04";
            } else if (deptDTO.getName().contains("邢台")) {
                one = "05";
            } else if (deptDTO.getName().contains("衡水")) {
                one = "06";
            } else if (deptDTO.getName().contains("超高压")) {
                one = "07";
            } else if (deptDTO.getName().contains("雄安")) {
                one = "08";
            } else {
                one = "3.14159";
            }

            String last = String.format("M%05d", oracleTerminalExcel.getId());

            monitorPO.setMonitorId(monitorId + one + last);

            monitorPO.setLineNum(oracleTerminalExcel.getLineNum());
            monitorPO.setName(oracleTerminalExcel.getLineName());
            monitorPO.setPowerrName(stationName);
            monitorPO.setPowerrId(stationId);
            monitorPO.setOperationName(deptDTO.getName());
            monitorPO.setOperationId(deptDTO.getCode());
            monitorPO.setOrgName(deptDTO.getName());
            monitorPO.setOrgId(deptDTO.getCode());
            monitorPO.setLineName(lineName);
            monitorPO.setLineId(lineId);
            monitorPO.setVoltageLevel(genScale);
            monitorPO.setIsUploadHead(0);
            monitorPO.setMonitorOverlimitStatus(0);
            monitorPO.setMonitorOverlimitStatus(0);

            String monitorState = null;
            switch (oracleTerminalExcel.getRunFlag()) {
                case 0:
                    monitorState = DicDataEnum.RUN.getName();
                    break;
                case 1:
                    monitorState = DicDataEnum.DEBUGGING.getName();
                    break;
                case 2:
                    monitorState = DicDataEnum.DECOMMISSIONING.getName();
                    break;
                default:
                    oracleTerminalExcelMsg.add(assembleMsg(oracleTerminalExcel, "字典监测点状态不存在，请确认后重试"));
                    break;

            }
            if (monitorStateDicMap.containsKey(monitorState)) {
                monitorPO.setMonitorState(monitorStateDicMap.get(monitorState).getId());
            } else {
                oracleTerminalExcelMsg.add(assembleMsg(oracleTerminalExcel, "字典监测点运行状态不存在，请确认后重试"));
                continue;
            }
            monitorPO.setPutDate(oracleTerminalExcel.getLoginTime());
            monitorPO.setMonitorType(monitorType.getId());
            monitorPO.setStandShortCapacity(oracleTerminalExcel.getStandardCapacity());
            monitorPO.setMinShortCircuitCapacity(oracleTerminalExcel.getShortCapacity());
            monitorPO.setUserAgreementCapacity(oracleTerminalExcel.getDealCapacity());
            monitorPO.setPowerSupplyEqCapacity(oracleTerminalExcel.getDevCapacity());
            DictData scale = dicDataFeignClient.getDicDataById(monitorPO.getVoltageLevel()).getData();
            Overlimit overlimitTem = new Overlimit();
            COverlimitUtil.voltageDeviation(overlimitTem, Float.parseFloat(scale.getValue()));
            monitorPO.setVoltageDeviationLowerLimit(overlimitTem.getUvoltageDev());
            monitorPO.setVoltageDeviationUpperLimit(overlimitTem.getVoltageDev());
            monitorPO.setPotentialTransFormerType(potentialDic.getId());
            monitorPO.setNeutralGroundingMode(neutralDic.getId());
            monitorPO.setStatisticalInterval(oracleTerminalExcel.getTimeInterval());
            monitorPO.setTerminalId(devId);
            monitorPO.setIsSpecialSupplyElectricity(0);

            monitorPO.setMonitorObjectName(oracleTerminalExcel.getObjName());


            if (oracleTerminalExcel.getLoadType().equals("电加热负荷") || oracleTerminalExcel.getLoadType().equals("轧机") || oracleTerminalExcel.getLoadType().equals("其他非线性负荷")|| oracleTerminalExcel.getLoadType().equals("变频调速负荷")) {
                if (objTypeDicMap.containsKey("冶炼负荷")) {
                    String objTypeId = objTypeDicMap.get("冶炼负荷").getId();
                    monitorPO.setMonitorTag(objTypeId);
                } else {
                    oracleTerminalExcelMsg.add(assembleMsg(oracleTerminalExcel, "冶炼负荷字典监测标签不存在，请确认后重试"));
                    continue;
                }
            } else if (oracleTerminalExcel.getLoadType().equals("商业/市政/民用/电子通讯负荷")|| "电动汽车充电站".equals(oracleTerminalExcel.getLoadType()) ||"轨道交通".equals(oracleTerminalExcel.getLoadType())) {
                if (objTypeDicMap.containsKey("城市商业")) {
                    String objTypeId = objTypeDicMap.get("城市商业").getId();
                    monitorPO.setMonitorTag(objTypeId);
                } else {
                    oracleTerminalExcelMsg.add(assembleMsg(oracleTerminalExcel, "城市商业字典监测标签不存在，请确认后重试"));
                    continue;
                }

            } else if (oracleTerminalExcel.getLoadType().equals("半导体制造") || oracleTerminalExcel.getLoadType().equals("精密加工") || oracleTerminalExcel.getLoadType().equals("党政机关")||"敏感/重要/高危用户".equals(oracleTerminalExcel.getLoadType())) {
                if (objTypeDicMap.containsKey("敏感用户")) {
                    String objTypeId = objTypeDicMap.get("敏感用户").getId();
                    monitorPO.setMonitorTag(objTypeId);
                } else {
                    oracleTerminalExcelMsg.add(assembleMsg(oracleTerminalExcel, "敏感用户字典监测标签不存在，请确认后重试"));
                    continue;
                }

            } else if (oracleTerminalExcel.getLoadType().equals("二类变电站") || oracleTerminalExcel.getLoadType().equals("三类变电站") || oracleTerminalExcel.getLoadType().equals("四类变电站")) {
                if (objTypeDicMap.containsKey("主变高压侧")) {
                    String objTypeId = objTypeDicMap.get("主变高压侧").getId();
                    monitorPO.setMonitorTag(objTypeId);
                } else {
                    oracleTerminalExcelMsg.add(assembleMsg(oracleTerminalExcel, "主变高压侧字典监测标签不存在，请确认后重试"));
                    continue;
                }
            } else if (oracleTerminalExcel.getLoadType().equals("跨省计量关口")) {
                if (objTypeDicMap.containsKey("跨省联络线")) {
                    String objTypeId = objTypeDicMap.get("跨省联络线").getId();
                    monitorPO.setMonitorTag(objTypeId);
                } else {
                    oracleTerminalExcelMsg.add(assembleMsg(oracleTerminalExcel, "跨省联络线字典监测标签不存在，请确认后重试"));
                    continue;
                }

            } else if (oracleTerminalExcel.getLoadType().equals("光伏电站")) {
                if (objTypeDicMap.containsKey("光伏电站")) {
                    String objTypeId = objTypeDicMap.get("光伏电站").getId();
                    monitorPO.setMonitorTag(objTypeId);
                } else {
                    oracleTerminalExcelMsg.add(assembleMsg(oracleTerminalExcel, "光伏电站字典监测标签不存在，请确认后重试"));
                    continue;
                }

            }else if (oracleTerminalExcel.getLoadType().equals("风电场")) {
                if (objTypeDicMap.containsKey("陆上风电")) {
                    String objTypeId = objTypeDicMap.get("陆上风电").getId();
                    monitorPO.setMonitorTag(objTypeId);
                } else {
                    oracleTerminalExcelMsg.add(assembleMsg(oracleTerminalExcel, "风电场字典监测标签不存在，请确认后重试"));
                    continue;
                }

            }else if (oracleTerminalExcel.getLoadType().equals("其他发电厂")) {
                if (objTypeDicMap.containsKey("其他电源")) {
                    String objTypeId = objTypeDicMap.get("其他电源").getId();
                    monitorPO.setMonitorTag(objTypeId);
                } else {
                    oracleTerminalExcelMsg.add(assembleMsg(oracleTerminalExcel, "其他电源监测标签不存在，请确认后重试"));
                    continue;
                }

            }  else {
                if (objTypeDicMap.containsKey(oracleTerminalExcel.getLoadType())) {
                    String objTypeId = objTypeDicMap.get(oracleTerminalExcel.getLoadType()).getId();
                    monitorPO.setMonitorTag(objTypeId);
                } else {
                    oracleTerminalExcelMsg.add(assembleMsg(oracleTerminalExcel, oracleTerminalExcel.getLoadType()+"字典监测标签不存在，请确认后重试"));
                    continue;
                }
            }


            //监测点对象类型
            if (objTypeMap.containsKey(oracleTerminalExcel.getLoadType())) {
                String objTypeId = objTypeMap.get(oracleTerminalExcel.getLoadType()).getId();
                monitorPO.setObjType(objTypeId);
            } else if (oracleTerminalExcel.getLoadType().equals("电加热负荷")) {
                String objTypeId = objTypeMap.get("电加热负荷（含电弧炉、中频炉、电热炉、单/多晶硅生产设备）").getId();
                monitorPO.setObjType(objTypeId);
            } else if (oracleTerminalExcel.getLoadType().equals("变频调速负荷")) {
                String objTypeId = objTypeMap.get("变频调速负荷（变频电机、变频水泵等）").getId();
                monitorPO.setObjType(objTypeId);
            } else if (oracleTerminalExcel.getLoadType().equals("敏感/重要/高危用户")) {
                String objTypeId = objTypeMap.get("敏感/重要/高危用户").getId();
                monitorPO.setObjType(objTypeId);
            } else {
                oracleTerminalExcelMsg.add(assembleMsg(oracleTerminalExcel, oracleTerminalExcel.getLoadType() + "字典监测点对象类型不存在，请确认后重试"));
                continue;
            }


            //TODO 监测点对象名称
            String wireMethod = "";
            switch (oracleTerminalExcel.getPtType()) {
                case 0:
                    wireMethod = DicDataEnum.STAR.getName();
                    break;
                case 1:
                    wireMethod = DicDataEnum.STAR_TRIANGLE.getName();
                    break;
                case 2:
                    wireMethod = DicDataEnum.OPEN_DELTA.getName();
                    break;
                default:
                    oracleTerminalExcelMsg.add(assembleMsg(oracleTerminalExcel, "字典接线方式不存在，请确认后重试"));
                    break;
            }
            if (wireListMap.containsKey(wireMethod)) {
                monitorPO.setTerminalWiringMethod(wireListMap.get(wireMethod).getId());
            } else {
                oracleTerminalExcelMsg.add(assembleMsg(oracleTerminalExcel, "字典接线方式不存在，请确认后重试"));
                continue;
            }

            monitorPO.setStatus(DataStateEnum.ENABLE.getCode());
            monitorPO.setIsSpecialMonitor(0);
            monitorPO.setPt1(oracleTerminalExcel.getPt1());
            monitorPO.setPt2(oracleTerminalExcel.getPt2());
            monitorPO.setCt1(oracleTerminalExcel.getCt1());
            monitorPO.setCt2(oracleTerminalExcel.getCt2());


            if (oracleTerminalExcel.getLoadType().equals("光伏电站") || oracleTerminalExcel.getLoadType().equals("风电场")) {
                monitorPO.setFieldStation("01");
            }

            if (oracleTerminalExcel.getPowerFlag() == 0) {
                monitorPO.setPowerFlag("101");
            } else if (oracleTerminalExcel.getPowerFlag() == 1) {
                monitorPO.setPowerFlag("102");
            }

                    if (Objects.isNull(lineBak) && Objects.isNull(monitor)) {
                        monitorPO.setIsUpToGrid(0);
                        monitorMapper.insert(monitorPO);
                        Overlimit overlimit = COverlimitUtil.globalAssemble(Float.parseFloat(scale.getValue()), oracleTerminalExcel.getDealCapacity(), oracleTerminalExcel.getDevCapacity(), oracleTerminalExcel.getShortCapacity(), 0, 0);
                        overlimit.setId(monitorPO.getId());
                        Overlimit overlimitRes = overlimitMapper.selectById(monitorPO.getId());
                        if (Objects.isNull(overlimitRes)) {
                            overlimitMapper.insert(overlimit);
                        } else {
                            overlimitMapper.updateById(overlimit);
                        }

                        LineBak lineBakPO = new LineBak();
                        lineBakPO.setId(monitorPO.getId());
                        lineBakPO.setLineId(oracleTerminalExcel.getId());
                        lineBakMapper.insert(lineBakPO);

                    } else {
                        if (Objects.isNull(lineBak)) {

                            lineBakMapper.delete(new LambdaQueryWrapper<LineBak>().eq(LineBak::getId,monitor.getId()));
                            LineBak lineBakPO = new LineBak();
                            lineBakPO.setId(monitor.getId());
                            lineBakPO.setLineId(oracleTerminalExcel.getId());
                            System.out.println(oracleTerminalExcel.getId());
                            lineBakMapper.insert(lineBakPO);
                            monitorMapper.updateById(monitorPO);
                        } else {
                            monitorPO.setId(lineBak.getId());
                            monitorMapper.updateById(monitorPO);
                        }


                        Overlimit overlimit = COverlimitUtil.globalAssemble(Float.parseFloat(scale.getValue()), oracleTerminalExcel.getDealCapacity(), oracleTerminalExcel.getDevCapacity(), oracleTerminalExcel.getShortCapacity(), 0, 0);
                        overlimit.setId(monitorPO.getId());
                        Overlimit overlimitRes = overlimitMapper.selectById(monitorPO.getId());
                        if (Objects.isNull(overlimitRes)) {
                            overlimitMapper.insert(overlimit);
                        } else {
                            overlimitMapper.updateById(overlimit);
                        }

                    }

        }


        if (CollectionUtil.isNotEmpty(oracleTerminalExcelMsg)) {
            ExcelUtil.exportExcel("失败列表.xlsx", OracleTerminalExcel.OracleTerminalExcelMsg.class, oracleTerminalExcelMsg);
            return null;
        }
        return CommonResponseEnum.SUCCESS.getMessage();
    }


    private String dealVoltageLevel(String voltage) {
        float scale = Float.parseFloat(voltage.substring(0, voltage.indexOf("kV")));
        if (scale < 500) {
            return "交流" + voltage;
        } else {
            return "直流" + voltage;
        }

    }

    /**
     * 组装不能正常插入的记录，稍后导出给用户
     *
     * @param oracleTerminalExcel 记录信息
     * @param msg                 错误信息
     */
    private OracleTerminalExcel.OracleTerminalExcelMsg assembleMsg(OracleTerminalExcel oracleTerminalExcel, String msg) {
        OracleTerminalExcel.OracleTerminalExcelMsg oracleTerminalExcelMsg = new OracleTerminalExcel.OracleTerminalExcelMsg();
        BeanUtils.copyProperties(oracleTerminalExcel, oracleTerminalExcelMsg);
        oracleTerminalExcelMsg.setMsg(msg);
        return oracleTerminalExcelMsg;
    }

}
