package com.njcn.device.pq.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.common.pojo.response.HttpResult;
import com.njcn.common.utils.LogUtil;
import com.njcn.common.utils.PubUtils;
import com.njcn.device.biz.enums.DeviceResponseEnum;
import com.njcn.device.biz.pojo.po.DeviceBak;
import com.njcn.device.biz.pojo.po.Overlimit;
import com.njcn.device.biz.utils.COverlimitUtil;
import com.njcn.device.pq.enums.LineBaseEnum;
import com.njcn.device.pq.mapper.*;
import com.njcn.device.pq.pojo.bo.BaseLineInfo;
import com.njcn.device.pq.pojo.bo.DeviceType;
import com.njcn.device.pq.pojo.bo.excel.NodeExcel;
import com.njcn.device.pq.pojo.bo.excel.OracleTerminalExcel;
import com.njcn.device.pq.pojo.bo.excel.OverLimitExcel;
import com.njcn.device.pq.pojo.bo.excel.TerminalBaseExcel;
import com.njcn.device.pq.pojo.param.*;
import com.njcn.device.pq.pojo.po.*;
import com.njcn.device.pq.pojo.vo.*;
import com.njcn.device.pq.service.*;
import com.njcn.device.pq.utils.ExcelStyleUtil;
import com.njcn.oss.constant.OssPath;
import com.njcn.oss.utils.FileStorageUtil;
import com.njcn.poi.excel.ExcelUtil;
import com.njcn.poi.util.PoiUtil;
import com.njcn.system.api.AreaFeignClient;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.system.enums.DicDataTypeEnum;
import com.njcn.system.pojo.po.Area;
import com.njcn.system.pojo.po.DictData;
import com.njcn.web.utils.RequestUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * pqs
 *
 * @author cdf
 * @date 2022/1/4
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TerminalBaseServiceImpl extends ServiceImpl<LineMapper, Line> implements TerminalBaseService {

    private final DeviceMapper deviceMapper;

    private final SuperDataMapper superDataMapper;

    private final IPqsTerminalLogsService iPqsTerminalLogsService;

    private final LineMapper lineMapper;

    private final DevFuctionMapper devFuctionMapper;

    private final AreaFeignClient areaFeignClient;

    private final DicDataFeignClient dicDataFeignClient;

    private final SubstationMapper substationMapper;

    private final VoltageMapper voltageMapper;

    private final LineDetailMapper lineDetailMapper;

    private final OverlimitMapper overlimitMapper;

    private final DeptLineMapper deptLineMapper;

    private final INodeService nodeService;

    private final LineBakService lineBakService;

    private final DeviceBakService deviceBakService;

    private final FileStorageUtil fileStorageUtil;


    /**
     * 终端新增操作
     *
     * @author cdf
     * @date 2021/7/19
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addTerminal(AddTerminalParam addTerminalParam) {
        String projectIndex = null;
        String provinceIndex = null;
        String gdIndex = null;
        String subIndex = null;
        if (StrUtil.isNotBlank(addTerminalParam.getProjectIndex())) {
            projectIndex = addTerminalParam.getProjectIndex();
            if (Objects.isNull(this.getById(projectIndex))) {
                throw new BusinessException(DeviceResponseEnum.PROJECT_NO);
            }
        }
        if (StrUtil.isNotBlank(addTerminalParam.getProvinceIndex())) {
            provinceIndex = addTerminalParam.getProvinceIndex();
            if (Objects.isNull(this.getById(provinceIndex))) {
                throw new BusinessException(DeviceResponseEnum.PROVINCE_GET_ERROR);
            }
        }
        if (StrUtil.isNotBlank(addTerminalParam.getGdIndex())) {
            gdIndex = addTerminalParam.getGdIndex();
            if (Objects.isNull(this.getById(gdIndex))) {
                throw new BusinessException(DeviceResponseEnum.GD_NO);
            }
        }
        if (StrUtil.isNotBlank(addTerminalParam.getSubIndex())) {
            subIndex = addTerminalParam.getSubIndex();
            if (Objects.isNull(this.getById(subIndex))) {
                throw new BusinessException(DeviceResponseEnum.SUB_NO);
            }
        }


        //项目
        if (Objects.nonNull(addTerminalParam.getProjectParam())) {
            if (StrUtil.isBlank(projectIndex)) {
                checkName(addTerminalParam, LineBaseEnum.PROJECT_LEVEL.getCode(), null);
                Line line = assembleLine(addTerminalParam.getProjectParam().getName(), LineBaseEnum.PROJECT_LEVEL.getCode(), "0", "0", addTerminalParam.getProjectParam().getSort());
                this.baseMapper.insert(line);
                projectIndex = line.getId();
            }
        }
        //省份
        if (Objects.nonNull(addTerminalParam.getProvinceParam())) {
            if (StrUtil.isBlank(provinceIndex) && StrUtil.isNotBlank(projectIndex)) {
                Area result = areaFeignClient.selectIdArea(addTerminalParam.getProvinceParam().getName()).getData();
                if (Objects.isNull(result)) {
                    throw new BusinessException(DeviceResponseEnum.PROVINCE_GET_ERROR);
                }
                LogUtil.njcnDebug(log, "获取区域信息：{}", result.toString());
                checkName(addTerminalParam, LineBaseEnum.PROVINCE_LEVEL.getCode(), projectIndex);
                Line province = assembleLine(result.getId(), LineBaseEnum.PROVINCE_LEVEL.getCode(), projectIndex, projectIndex, addTerminalParam.getProvinceParam().getSort());
                this.baseMapper.insert(province);
                provinceIndex = province.getId();
            }
        }

        //供电公司
        if (Objects.nonNull(addTerminalParam.getGdInformationParam())) {
            if (StrUtil.isBlank(gdIndex) && StrUtil.isNotBlank(provinceIndex)) {
                checkName(addTerminalParam, LineBaseEnum.GD_LEVEL.getCode(), provinceIndex);
                Line gdInformation = assembleLine(addTerminalParam.getGdInformationParam().getName(), LineBaseEnum.GD_LEVEL.getCode(), provinceIndex, projectIndex + StrUtil.COMMA + provinceIndex, addTerminalParam.getGdInformationParam().getSort());
                this.baseMapper.insert(gdInformation);
                gdIndex = gdInformation.getId();
            }
        }

        //变电站
        if (Objects.nonNull(addTerminalParam.getSubStationParam())) {
            if (StrUtil.isBlank(subIndex) && StrUtil.isNotBlank(gdIndex)) {
                checkName(addTerminalParam, LineBaseEnum.SUB_LEVEL.getCode(), gdIndex);
                Line subStation = assembleLine(addTerminalParam.getSubStationParam().getName(), LineBaseEnum.SUB_LEVEL.getCode(), gdIndex, projectIndex + StrUtil.COMMA + provinceIndex + StrUtil.COMMA + gdIndex, addTerminalParam.getSubStationParam().getSort());
                this.baseMapper.insert(subStation);
                subIndex = subStation.getId();

                //变电站下的经纬度入库
                Substation sub = new Substation();
                sub.setId(subIndex);
                sub.setScale(addTerminalParam.getSubStationParam().getScale());
                sub.setLng(addTerminalParam.getSubStationParam().getLng());
                sub.setLat(addTerminalParam.getSubStationParam().getLat());
                substationMapper.insert(sub);
            }
        }

        //装置
        if (Objects.nonNull(addTerminalParam.getDeviceParam())) {
            LambdaQueryWrapper<Line> lineLambdaQueryWrapper = new LambdaQueryWrapper<>();
            if (CollectionUtil.isNotEmpty(addTerminalParam.getDeviceParam()) && StrUtil.isNotBlank(subIndex)) {
                //校验变电站下的装置名称ip是否重复
                checkDevNameAndIp(addTerminalParam, subIndex, lineLambdaQueryWrapper);


                for (DeviceParam deviceParam : addTerminalParam.getDeviceParam()) {
                    //用于记录装置id
                    String devIdIndex;
                    //监测点序号
                    List<Integer> listLineNum = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).collect(Collectors.toList());
                    //母线序号
                    List<Integer> listVoltageNum = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).collect(Collectors.toList());
                    //标识当前装置下的监测点数量
                    int lineNum = 0, voltageNum = 0;

                    //校验监测点总数不超过10
                    if (CollectionUtil.isNotEmpty(deviceParam.getSubVoltageParam())) {
                        for (SubVoltageParam subVoltage : deviceParam.getSubVoltageParam()) {
                            if (CollectionUtil.isNotEmpty(subVoltage.getLineParam())) {
                                for (LineParam lineValid : subVoltage.getLineParam()) {
                                    if (StrUtil.isBlank(lineValid.getLineIndex())) {
                                        lineNum++;
                                    }
                                }
                            }

                            //一台装置母线最多10路
                            if (StrUtil.isBlank(subVoltage.getSubvIndex())) {
                                voltageNum++;
                            }

                        }
                    }

                    if (StrUtil.isBlank(deviceParam.getDevIndex())) {

                        Line device = assembleLine(deviceParam.getName(), LineBaseEnum.DEVICE_LEVEL.getCode(), subIndex, projectIndex + StrUtil.COMMA + provinceIndex + StrUtil.COMMA + gdIndex + StrUtil.COMMA + subIndex, deviceParam.getSort());
                        this.baseMapper.insert(device);
                        devIdIndex = device.getId();

                        //装置详情
                        Device deviceDetail = new Device();
                        BeanUtils.copyProperties(deviceParam, deviceDetail);
                        deviceDetail.setId(device.getId());
                        deviceDetail.setRunFlag(0);
                        deviceDetail.setCallFlag(0);
                        deviceDetail.setComFlag(0);
                        deviceDetail.setCheckFlag(1);
                        deviceDetail.setThisTimeCheck(PubUtils.localDateFormat(deviceParam.getThisTimeCheck()));
                        deviceDetail.setNextTimeCheck(PubUtils.localDateFormat(deviceParam.getNextTimeCheck()));
                        deviceDetail.setLoginTime(PubUtils.localDateFormat(deviceParam.getNextTimeCheck()));
                        deviceDetail.setUpdateTime(LocalDateTime.now());
                        deviceMapper.insert(deviceDetail);
                        //装置功能
                        List<DictData> funList = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.DEV_FUN.getName()).getData();
                        if (CollectionUtil.isEmpty(funList)) {
                            throw new BusinessException(DeviceResponseEnum.DIC_GET_EMPTY);
                        }

                        List<DevFuction> insertFunList = new ArrayList<>();
                        for (DictData dicData : funList) {
                            DevFuction devFunction = new DevFuction();
                            devFunction.setLineId(device.getId());
                            devFunction.setFucName(dicData.getId());
                            devFunction.setId(IdUtil.simpleUUID());
                            insertFunList.add(devFunction);
                        }
                        QueryWrapper<DevFuction> funQueryWrapper = new QueryWrapper<>();
                        funQueryWrapper.lambda().eq(DevFuction::getLineId, device.getId());
                        devFuctionMapper.delete(funQueryWrapper);
                        devFuctionMapper.addBatch(insertFunList);
                    } else {
                        devIdIndex = deviceParam.getDevIndex();
                        List<LineDetail> lineDetails = lineMapper.getLineDetailByDeviceId(devIdIndex);
                        if (CollectionUtil.isNotEmpty(lineDetails)) {
                            lineNum = lineNum + lineDetails.size();
                            for (LineDetail sline : lineDetails) {
                                listLineNum.removeIf(integer -> sline.getNum().equals(integer));
                            }
                        }
                        //母线
                        List<Voltage> voltageList = lineMapper.getVoltageByDevId(devIdIndex);
                        if (CollectionUtil.isNotEmpty(voltageList)) {
                            voltageNum = voltageNum + voltageList.size();
                            for (Voltage v : voltageList) {
                                listVoltageNum.removeIf(integer -> v.getNum().equals(integer));
                            }
                        }
                    }

                    if (lineNum > 10) {
                        throw new BusinessException(DeviceResponseEnum.DEVICE_LINE_BIG);
                    }
                    if (voltageNum > 10) {
                        throw new BusinessException(DeviceResponseEnum.DEVICE_VOLTAGE_BIG);
                    }

                    //判断设备下是否存在母线
                    if (CollectionUtil.isNotEmpty(deviceParam.getSubVoltageParam())) {
                        //当通过设备节点新增时候需要校验是否存在同名母线名称
                        List<String> subvNameList = deviceParam.getSubVoltageParam().stream()
                                .filter((subv) -> subv.getSubvIndex() == null)
                                .map(SubVoltageParam::getName).collect(Collectors.toList());
                        if (CollectionUtil.isNotEmpty(subvNameList)) {
                            lineLambdaQueryWrapper.clear();
                            lineLambdaQueryWrapper.eq(Line::getPid, devIdIndex)
                                    .eq(Line::getState, DataStateEnum.ENABLE.getCode())
                                    .in(Line::getName, subvNameList);
                            List<Line> subvRes = this.list(lineLambdaQueryWrapper);
                            if (subvRes.size() > 0) {
                                List<String> subvList = subvRes.stream().map(Line::getName).collect(Collectors.toList());
                                throw new BusinessException(DeviceResponseEnum.SUBV_NAME_SAME, String.join(";", subvList));
                            }
                        }


                        //母线
                        List<String> voltageName = deviceParam.getSubVoltageParam().stream().filter(item -> StrUtil.isBlank(item.getSubvIndex())).map(SubVoltageParam::getName).collect(Collectors.toList());
                        if (CollectionUtil.isNotEmpty(voltageName)) {
                            List<Line> voltageList = this.baseMapper.getVoltageListBySubId(subIndex, voltageName);
                            if (CollectionUtil.isNotEmpty(voltageList)) {
                                throw new BusinessException(DeviceResponseEnum.SUBV_NAME_SAME, String.join(";", voltageList.stream().map(Line::getName).collect(Collectors.toList())));
                            }
                        }


                        //校验同一变电站下只能有唯一母线名称
                        List<String> addVoltage = deviceParam.getSubVoltageParam().stream().filter(item -> item.getSubvIndex() == null).map(SubVoltageParam::getName).collect(Collectors.toList());
                        if (CollectionUtil.isNotEmpty(addVoltage)) {
                            List<Line> voltageListBySubId = this.baseMapper.getVoltageListBySubId(subIndex, addVoltage);
                            if (CollectionUtil.isNotEmpty(voltageListBySubId)) {
                                throw new BusinessException(DeviceResponseEnum.SUBV_NAME_SAME, String.join(";", voltageListBySubId.stream().map(Line::getName).collect(Collectors.toList())));
                            }
                        }

                        for (SubVoltageParam subVoltageParam : deviceParam.getSubVoltageParam()) {
                            //母线id
                            String subvIndex;

                            if (StrUtil.isBlank(subVoltageParam.getSubvIndex()) && StrUtil.isNotBlank(devIdIndex)) {


                                DictData scaleRes = dicDataFeignClient.getDicDataById(subVoltageParam.getScale()).getData();
                                if (Objects.isNull(scaleRes)) {
                                    throw new BusinessException(DeviceResponseEnum.DIC_GET_EMPTY);
                                }

                                //校验母线
                                if (CollectionUtil.isNotEmpty(listVoltageNum)) {
                                    if (!listVoltageNum.contains(subVoltageParam.getNum())) {
                                        throw new BusinessException(DeviceResponseEnum.VOLTAGE_NUM_USE, "母线序号:" + subVoltageParam.getNum());
                                    }
                                } else {
                                    throw new BusinessException(DeviceResponseEnum.DEVICE_VOLTAGE_BIG);
                                }


                                Line subVoltage = assembleLine(subVoltageParam.getName(), LineBaseEnum.SUB_V_LEVEL.getCode(), devIdIndex, projectIndex + StrUtil.COMMA + provinceIndex + StrUtil.COMMA + gdIndex + StrUtil.COMMA + subIndex + StrUtil.COMMA + devIdIndex, subVoltageParam.getSort());
                                this.baseMapper.insert(subVoltage);
                                subvIndex = subVoltage.getId();
                                Voltage voltage = new Voltage();
                                voltage.setId(subVoltage.getId());
                                voltage.setNum(subVoltageParam.getNum());
                                voltage.setScale(scaleRes.getId());
                                voltage.setModel(subVoltageParam.getModel());
                                voltageMapper.insert(voltage);
                            } else {
                                subvIndex = subVoltageParam.getSubvIndex();
                            }

                            //监测点
                            if (CollectionUtil.isNotEmpty(subVoltageParam.getLineParam())) {
                                //校验监测点名称重复
                                List<String> lineNameList = subVoltageParam.getLineParam().stream().filter((line) -> line.getLineIndex() == null).map(LineParam::getName).collect(Collectors.toList());
                                if (CollectionUtil.isNotEmpty(lineNameList)) {
                                    lineLambdaQueryWrapper.clear();
                                    lineLambdaQueryWrapper.eq(Line::getPid, subvIndex)
                                            .eq(Line::getState, DataStateEnum.ENABLE.getCode())
                                            .in(Line::getName, lineNameList);
                                    List<Line> lineList = this.list(lineLambdaQueryWrapper);
                                    if (lineList.size() > 0) {
                                        List<String> lineRes = lineList.stream().map(Line::getName).collect(Collectors.toList());
                                        throw new BusinessException(DeviceResponseEnum.LINE_NAME_REPETITION, String.join(";", lineRes));
                                    }
                                }
                                //通用新增监测点
                                for (LineParam lineParam : subVoltageParam.getLineParam()) {
                                    if (StrUtil.isBlank(lineParam.getLineIndex()) && StrUtil.isNotBlank(subvIndex)) {
                                        //判断监测点序号是否重复
                                        if (CollectionUtil.isNotEmpty(listLineNum)) {
                                            if (!listLineNum.contains(lineParam.getNum())) {
                                                throw new BusinessException(DeviceResponseEnum.LINE_NUM_USE, "监测点序号:" + lineParam.getNum());
                                            }
                                        } else {
                                            throw new BusinessException(DeviceResponseEnum.DEVICE_LINE_BIG);
                                        }
                                        //删除与当前线路号重复的项
                                        listLineNum.removeIf(lineNo -> lineNo.equals(lineParam.getNum()));
                                        HttpResult<DictData> httpScale = dicDataFeignClient.getDicDataById(subVoltageParam.getScale());
                                        Line line = assembleLine(lineParam.getName(), LineBaseEnum.LINE_LEVEL.getCode(), subvIndex, projectIndex + StrUtil.COMMA + provinceIndex + StrUtil.COMMA + gdIndex + StrUtil.COMMA + subIndex + StrUtil.COMMA + devIdIndex + StrUtil.COMMA + subvIndex, lineParam.getSort());
                                        this.baseMapper.insert(line);
                                        LineDetail lineDetail = new LineDetail();
                                        BeanUtils.copyProperties(lineParam, lineDetail);
                                        lineDetail.setId(line.getId());

                                        //判断国网监测点id
                                        if (StrUtil.isNotBlank(lineDetail.getMonitorId())) {
                                            lineDetail.setMonitorFlag(1);
                                        } else {
                                            lineDetail.setMonitorFlag(0);
                                        }

                                        lineDetailMapper.insert(lineDetail);

                                        //通过监测点id获取母线电压等级
                                        Voltage voltage = lineMapper.getVoltageByLineId(line.getId());
                                        //监测点限值
                                        DictData scaleResult = dicDataFeignClient.getDicDataById(voltage.getScale()).getData();
                                        float scaTmp = Float.parseFloat(scaleResult.getValue());
                                        Overlimit overlimit = COverlimitUtil.globalAssemble(scaTmp, lineDetail.getDealCapacity(), lineDetail.getDevCapacity(), lineDetail.getShortCapacity(), 1, 1);

                                        if (Objects.isNull(lineParam.getVoltageDev())) {
                                            overlimit.setVoltageDev(overlimit.getVoltageDev());
                                        } else {
                                            overlimit.setVoltageDev(lineParam.getVoltageDev());
                                        }
                                        if (Objects.isNull(lineParam.getUvoltageDev())) {
                                            overlimit.setUvoltageDev(overlimit.getUvoltageDev());
                                        } else {
                                            overlimit.setUvoltageDev(lineParam.getUvoltageDev());
                                        }
                                        //Overlimit overlimit = new Overlimit(line.getId(), scaTmp, lineDetail.getShortCapacity(), lineDetail.getStandardCapacity(), lineDetail.getDealCapacity(), lineDetail.getDevCapacity());
                                        overlimitMapper.deleteById(line.getId());

                                        overlimit.setId(line.getId());
                                        overlimitMapper.insert(overlimit);

                                    }

                                }
                            }
                        }
                    }
                }
            } else {
                throw new BusinessException(CommonResponseEnum.FAIL);
            }
        }
        return true;
    }

    /**
     * 校验装置
     */
    private void checkDevNameAndIp(AddTerminalParam addTerminalParam, String subIndex, LambdaQueryWrapper<Line> lineLambdaQueryWrapper) {


        List<String> devNameList = addTerminalParam.getDeviceParam().stream().filter((dev -> dev.getDevIndex() == null)).map(DeviceParam::getName).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(devNameList)) {
            lineLambdaQueryWrapper.eq(Line::getPid, subIndex).in(Line::getName, devNameList);
            List<Line> deviceListRes = this.list(lineLambdaQueryWrapper);
            //校验当前变电站下是否有同名设备
            if (CollectionUtil.isNotEmpty(deviceListRes)) {
                List<String> stringList = deviceListRes.stream().map(Line::getName).collect(Collectors.toList());
                throw new BusinessException(DeviceResponseEnum.DEVICE_SAME_NAME, String.join(";", stringList));
            }
        }
        List<DeviceParam> devIpList = addTerminalParam.getDeviceParam().stream().filter((dev -> dev.getDevIndex() == null)).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(devIpList)) {
            for (DeviceParam deviceParam : devIpList) {
                List<Device> deviceListIpRes = deviceMapper.getDeviceBySubId(subIndex, deviceParam.getIp(), deviceParam.getPort(), null);
                if (CollectionUtil.isNotEmpty(deviceListIpRes)) {
                    throw new BusinessException(DeviceResponseEnum.DEVICE_SAME_IP, deviceListIpRes.get(0).getIp());
                }

            }
            //校验当前变电站下的装置是否有相同ip
          /*  if (CollectionUtil.isNotEmpty(deviceListIpRes)) {
                List<String> stringList = deviceListIpRes.stream().map(Device::getIp).collect(Collectors.toList());
                throw new BusinessException(DeviceResponseEnum.DEVICE_SAME_IP, String.join(";", stringList));
            }*/
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateTerminal(UpdateTerminalParam updateTerminalParam) {
        LambdaQueryWrapper<Line> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //项目
        if (Objects.nonNull(updateTerminalParam.getProjectUpdateParam())) {
            Line projectRes = this.getById(updateTerminalParam.getProjectUpdateParam().getProjectIndex());
            if (Objects.isNull(projectRes)) {
                throw new BusinessException(DeviceResponseEnum.PROJECT_NO);
            }
            checkUpdateName(updateTerminalParam, 0, null);
            Line project = new Line();
            project.setId(updateTerminalParam.getProjectUpdateParam().getProjectIndex());
            project.setName(updateTerminalParam.getProjectUpdateParam().getName());
            project.setSort(updateTerminalParam.getProjectUpdateParam().getSort());
            this.updateById(project);
        }

        //省份
        if (Objects.nonNull(updateTerminalParam.getProvinceUpdateParam())) {
            Line provinceRes = this.getById(updateTerminalParam.getProvinceUpdateParam().getProvinceIndex());
            if (Objects.isNull(provinceRes)) {
                throw new BusinessException(DeviceResponseEnum.PROVINCE_EMPTY);
            }
            Line province = new Line();
            province.setId(updateTerminalParam.getProvinceUpdateParam().getProvinceIndex());
            province.setSort(updateTerminalParam.getProvinceUpdateParam().getSort());
            this.updateById(province);
        }

        //供电公司
        if (Objects.nonNull(updateTerminalParam.getGdInformationUpdateParam())) {
            Line gdRes = this.getById(updateTerminalParam.getGdInformationUpdateParam().getGdIndex());
            if (Objects.isNull(gdRes)) {
                throw new BusinessException(DeviceResponseEnum.GD_NO);
            }
            Line gdInformation = new Line();
            gdInformation.setId(updateTerminalParam.getGdInformationUpdateParam().getGdIndex());
            gdInformation.setName(updateTerminalParam.getGdInformationUpdateParam().getName());
            gdInformation.setSort(updateTerminalParam.getGdInformationUpdateParam().getSort());

            checkUpdateName(updateTerminalParam, 2, gdRes.getPid());
            this.updateById(gdInformation);
        }
        //变电站
        if (Objects.nonNull(updateTerminalParam.getSubStationUpdateParam())) {
            Line subStationRes = this.getById(updateTerminalParam.getSubStationUpdateParam().getSubIndex());
            if (Objects.isNull(subStationRes)) {
                throw new BusinessException(DeviceResponseEnum.SUB_NO);
            }
            Line subStation = new Line();
            subStation.setId(updateTerminalParam.getSubStationUpdateParam().getSubIndex());
            subStation.setName(updateTerminalParam.getSubStationUpdateParam().getName());
            subStation.setSort(updateTerminalParam.getSubStationUpdateParam().getSort());
            checkUpdateName(updateTerminalParam, 3, subStationRes.getPid());

            this.updateById(subStation);
            Substation pqsMap = new Substation();
            BeanUtils.copyProperties(updateTerminalParam.getSubStationUpdateParam(), pqsMap);
            pqsMap.setId(subStation.getId());
            substationMapper.updateById(pqsMap);

        }
        //装置
        if (CollectionUtil.isNotEmpty(updateTerminalParam.getDeviceUpdateParamList())) {
            List<DeviceParam> devList = updateTerminalParam.getDeviceUpdateParamList();
            List<String> devNameList = devList.stream()
                    .filter(item -> item.getUpdateFlag() == 1)
                    .map(DeviceParam::getName).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(devNameList)) {
                long devCount = devNameList.stream().distinct().count();
                if (devCount != devNameList.size()) {
                    throw new BusinessException(DeviceResponseEnum.DEVICE_REPETITION);
                }
            }

            //IP校验
            List<DeviceParam> devIpList = devList.stream()
                    .filter(item -> item.getUpdateFlag() == 1).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(devIpList)) {
                Set<String> set = new HashSet<>();
                devIpList.forEach(item -> set.add(item.getIp() + item.getPort()));
                if (devIpList.size() != set.size()) {
                    throw new BusinessException(DeviceResponseEnum.DEVICE_IP_REPETITION);
                }
            }
            Line deviceValid = this.getById(updateTerminalParam.getDeviceUpdateParamList().get(0).getDevIndex());

            //校验同名设备
            List<String> devIndexList = devList.stream()
                    .filter(item -> item.getUpdateFlag() == 1)
                    .map(DeviceParam::getDevIndex).collect(Collectors.toList());

            if (CollectionUtil.isNotEmpty(devIndexList)) {
                lambdaQueryWrapper.clear();
                lambdaQueryWrapper.in(Line::getName, devNameList)
                        .notIn(Line::getId, devIndexList)
                        .eq(Line::getPid, deviceValid.getPid());
                List<Line> deviceList = this.list(lambdaQueryWrapper);
                if (CollectionUtil.isNotEmpty(deviceList)) {
                    List<String> repeatDevNames = deviceList.stream().map(Line::getName).collect(Collectors.toList());
                    throw new BusinessException(DeviceResponseEnum.DEVICE_SAME_NAME, "重复装置:" + String.join(";", repeatDevNames));
                }
                //校验装置ip
                for (DeviceParam deviceParam : devIpList) {
                    List<Device> deviceIpList = deviceMapper.getDeviceBySubId(deviceValid.getPid(), deviceParam.getIp(), deviceParam.getPort(), deviceParam.getDevIndex());
                    if (CollectionUtil.isNotEmpty(deviceIpList)) {
                        throw new BusinessException(DeviceResponseEnum.DEVICE_SAME_IP, "重复IP:" + deviceIpList.get(0).getIp());
                    }
                }

            }

            for (DeviceParam updateDeviceParam : devList) {
                if (updateDeviceParam.getUpdateFlag() == 1) {
                    Line device = new Line();
                    BeanUtils.copyProperties(updateDeviceParam, device);
                    device.setId(updateDeviceParam.getDevIndex());
                    Device deviceDetail = new Device();
                    BeanUtils.copyProperties(updateDeviceParam, deviceDetail);
                    deviceDetail.setId(updateDeviceParam.getDevIndex());
                    this.updateById(device);
                    deviceMapper.updateById(deviceDetail);
                }

                //母线
                if (CollectionUtil.isNotEmpty(updateDeviceParam.getSubVoltageParam())) {
                    List<SubVoltageParam> subVoltageBOList = updateDeviceParam.getSubVoltageParam();
                    List<SubVoltageParam> useSubVoltageBOList = subVoltageBOList.stream()
                            .filter(item -> item.getUpdateFlag() == 1)
                            .collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(useSubVoltageBOList)) {
                        //判断母线名称是否重复
                        List<String> subVNameList = useSubVoltageBOList.stream()
                                .map(SubVoltageParam::getName)
                                .collect(Collectors.toList());
                        if (CollectionUtil.isNotEmpty(subVNameList)) {
                            long subvCount = subVNameList.stream().distinct().count();
                            if (subvCount != subVNameList.size()) {
                                throw new BusinessException(DeviceResponseEnum.SUBV_NAME_REPETITION);
                            }
                            //校验母线名称是否已经存在
                            List<String> subVIndexList = useSubVoltageBOList.stream()
                                    .map(SubVoltageParam::getSubvIndex)
                                    .collect(Collectors.toList());
                            Line voltage = this.getById(subVIndexList.get(0));
                            if (Objects.isNull(voltage)) {
                                throw new BusinessException(DeviceResponseEnum.SUBV_NO);
                            }
                            lambdaQueryWrapper.clear();
                            lambdaQueryWrapper.in(Line::getName, subVNameList)
                                    .notIn(Line::getId, subVIndexList)
                                    .eq(Line::getPid, voltage.getPid());
                            List<Line> subVoltageList = this.list(lambdaQueryWrapper);
                            if (CollectionUtil.isNotEmpty(subVoltageList)) {
                                List<String> repeatSubVNames = subVoltageList.stream().map(Line::getName).collect(Collectors.toList());
                                throw new BusinessException(DeviceResponseEnum.SUBV_NAME_SAME, "已存在母线名称:" + String.join(";", repeatSubVNames));
                            }
                        }
                    }

                    for (SubVoltageParam updateSubVoltageParam : subVoltageBOList) {
                        if (updateSubVoltageParam.getUpdateFlag() == 1) {
                            Voltage voltageTem = voltageMapper.selectById(updateSubVoltageParam.getSubvIndex());
                            Line subVoltage = new Line();
                            subVoltage.setId(updateSubVoltageParam.getSubvIndex());
                            subVoltage.setName(updateSubVoltageParam.getName());
                            this.updateById(subVoltage);

                            Voltage voltage = new Voltage();
                            BeanUtils.copyProperties(updateSubVoltageParam, voltage);
                            voltage.setId(updateSubVoltageParam.getSubvIndex());
                            voltageMapper.updateById(voltage);

                            //如果电压等级变化重新计算母线下面监测点的限值
                            if (!voltageTem.getScale().equals(voltage.getScale())) {
                                List<LineDetail> lineList = voltageMapper.getLineDetailByBusBarId(voltage.getId());
                                DictData dictData = dicDataFeignClient.getDicDataById(voltage.getScale()).getData();
                                float voltageLevel = Float.parseFloat(dictData.getValue());
                                if (CollectionUtil.isNotEmpty(lineList)) {
                                    for (LineDetail lineDetail : lineList) {
                                        Overlimit overlimit = COverlimitUtil.globalAssemble(voltageLevel, lineDetail.getDealCapacity(), lineDetail.getDevCapacity(), lineDetail.getShortCapacity(), 1, 0);
                                        overlimit.setId(lineDetail.getId());
                                        overlimitMapper.deleteById(lineDetail.getId());
                                        overlimitMapper.insert(overlimit);
                                    }
                                }
                            }

                        }

                        //监测点
                        if (CollectionUtil.isNotEmpty(updateSubVoltageParam.getLineParam())) {
                            List<LineParam> updateLineBOS = updateSubVoltageParam.getLineParam();
                            Line lineR = this.getById(updateLineBOS.get(0).getLineIndex());
                            if (Objects.isNull(lineR)) {
                                throw new BusinessException(DeviceResponseEnum.LINE_NO);
                            }
                            //校验监测点名称是否已经存在
                            List<LineParam> useLineBOS = updateLineBOS.stream().filter(item -> item.getUpdateFlag() == 1).collect(Collectors.toList());
                            if (CollectionUtil.isNotEmpty(useLineBOS)) {
                                //判断监测点名称是否重复
                                List<String> LineNameList = useLineBOS.stream().map(LineParam::getName).collect(Collectors.toList());
                                long LineCount = LineNameList.stream().distinct().count();
                                if (LineCount != LineNameList.size()) {
                                    throw new BusinessException(DeviceResponseEnum.LINE_NAME_REPETITION);
                                }

                                List<String> lineIndexList = useLineBOS.stream().map(LineParam::getLineIndex).collect(Collectors.toList());
                                lambdaQueryWrapper.clear();
                                lambdaQueryWrapper.in(Line::getName, LineNameList)
                                        .notIn(Line::getId, lineIndexList)
                                        .eq(Line::getPid, lineR.getPid());
                                List<Line> lineList = this.list(lambdaQueryWrapper);
                                if (CollectionUtil.isNotEmpty(lineList)) {
                                    List<String> repeatLineNames = lineList.stream().map(Line::getName).collect(Collectors.toList());
                                    throw new BusinessException(DeviceResponseEnum.LINE_NAME_REPETITION, "已存在监测点名称:" + String.join(";", repeatLineNames));
                                }
                            }

                            for (LineParam updateLineBO : useLineBOS) {
                                String lineId = updateLineBO.getLineIndex();
                                LineDetail lineDetailRes = lineDetailMapper.selectById(lineId);
                                if (Objects.isNull(lineDetailRes)) {
                                    throw new BusinessException(DeviceResponseEnum.LINE_NO);
                                }

                                Line line = new Line();
                                BeanUtils.copyProperties(updateLineBO, line);
                                line.setId(updateLineBO.getLineIndex());
                                this.updateById(line);

                                LineDetail lineDetail = new LineDetail();
                                BeanUtils.copyProperties(updateLineBO, lineDetail);
                                lineDetail.setId(updateLineBO.getLineIndex());
                                //判断国网监测点id
                                if (StrUtil.isNotBlank(lineDetail.getMonitorId())) {
                                    lineDetail.setMonitorFlag(1);
                                } else {
                                    lineDetail.setMonitorFlag(0);
                                }
                                lineDetailMapper.updateById(lineDetail);

                                Overlimit overlimitTem = overlimitMapper.selectById(lineId);
                                if ((!lineDetailRes.getDevCapacity().equals(lineDetail.getDevCapacity()))
                                        || ((!lineDetailRes.getShortCapacity().equals(lineDetail.getShortCapacity())))
                                        || ((!lineDetailRes.getDealCapacity().equals(lineDetail.getDealCapacity())))
                                        || ((!lineDetailRes.getStandardCapacity().equals(lineDetail.getStandardCapacity())))
                                        || ((!overlimitTem.getVoltageDev().equals(updateLineBO.getVoltageDev()))
                                        || ((!overlimitTem.getUvoltageDev().equals(updateLineBO.getUvoltageDev()))))

                                ) {

                                    //监测点限值
                                    DictData scaleResult = dicDataFeignClient.getDicDataById(updateSubVoltageParam.getScale()).getData();
                                    float scaTmp = Float.parseFloat(scaleResult.getValue());

                                    //监测点限值
                                    Overlimit overlimit = COverlimitUtil.globalAssemble(scaTmp, lineDetail.getDealCapacity(), lineDetail.getDevCapacity(), lineDetail.getShortCapacity(), 1, 0);
                                    if (Objects.isNull(updateLineBO.getVoltageDev())) {
                                        overlimit.setVoltageDev(overlimit.getVoltageDev());
                                    } else {
                                        overlimit.setVoltageDev(updateLineBO.getVoltageDev());
                                    }
                                    if (Objects.isNull(updateLineBO.getUvoltageDev())) {
                                        overlimit.setUvoltageDev(overlimit.getUvoltageDev());
                                    } else {
                                        overlimit.setUvoltageDev(updateLineBO.getUvoltageDev());
                                    }
                                    overlimit.setId(line.getId());
                                    overlimitMapper.deleteById(line.getId());
                                    overlimitMapper.insert(overlimit);
                                }
                                if (!Objects.equals(lineDetail.getCt1(), lineDetailRes.getCt1()) || !Objects.equals(lineDetail.getCt2(), lineDetailRes.getCt2())
                                        || !Objects.equals(lineDetail.getPt1(), lineDetailRes.getPt1()) || !Objects.equals(lineDetail.getPt2(), lineDetailRes.getPt2())
                                        || !Objects.equals(lineDetail.getDevCapacity(), lineDetailRes.getDevCapacity()) || !Objects.equals(lineDetail.getShortCapacity(), lineDetailRes.getShortCapacity())
                                        || !Objects.equals(lineDetail.getStandardCapacity(), lineDetailRes.getStandardCapacity()) || !Objects.equals(lineDetail.getDealCapacity(), lineDetailRes.getDealCapacity())) {
                                    //获取用户信息
                                    String userName = RequestUtil.getUsername();
                                    String index = RequestUtil.getUserIndex();
                                    queryUpdateAndInsertLog(userName, index, lineDetail, lineDetailRes);
                                }
                            }
                        }
                    }
                }
            }
        }
        return true;
    }

    /**
     * 查询监测点信息修改处,并新增日志
     *
     * @param userName
     * @param newLine
     * @param oldLine
     * @return
     */
    @Async
    public void queryUpdateAndInsertLog(String userName, String index, LineDetail newLine, LineDetail oldLine) {
        SuperDataParam superDataParam = superDataMapper.getPointSuper(newLine.getId());
        StringBuilder sb = new StringBuilder();
        sb.append(userName).append("修改了").append(superDataParam.getUrbanName()).append(" - ")
                .append(superDataParam.getSubName()).append(" - ").append(superDataParam.getDevName()).append(" - ").append(superDataParam.getPName())
                .append(" - ").append(superDataParam.getMName()).append(" - 监测点的参数;");
        StringBuilder sbNew = new StringBuilder();
        StringBuilder sbOld = new StringBuilder();
        sbNew.append("操作历史,");
        sbOld.append("修改后参数,");
        //pt变化
        if (!Objects.equals(newLine.getPt1(), oldLine.getPt1()) || !Objects.equals(newLine.getPt2(), oldLine.getPt2())) {
            sbNew.append("pt变比: ").append(newLine.getPt1()).append(" : ").append(newLine.getPt2()).append(";");
            sbOld.append("pt变比: ").append(oldLine.getPt1()).append(" : ").append(oldLine.getPt2()).append(";");
        }
        //ct变化
        if (!Objects.equals(newLine.getCt1(), oldLine.getCt1()) || !Objects.equals(newLine.getCt2(), oldLine.getCt2())) {
            sbNew.append("ct变比: ").append(newLine.getCt1()).append(" : ").append(newLine.getCt2()).append(";");
            sbOld.append("ct变比: ").append(oldLine.getCt1()).append(" : ").append(oldLine.getCt2()).append(";");
        }
        //设备容量
        if (!Objects.equals(newLine.getDevCapacity(), oldLine.getDevCapacity())) {
            sbNew.append("设备容量: ").append(newLine.getDevCapacity()).append(";");
            sbOld.append("设备容量: ").append(oldLine.getDevCapacity()).append(";");
        }
        //短路容量
        if (!Objects.equals(newLine.getShortCapacity(), oldLine.getShortCapacity())) {
            sbNew.append("短路容量: ").append(newLine.getShortCapacity()).append(";");
            sbOld.append("短路容量: ").append(oldLine.getShortCapacity()).append(";");
        }
        //基准容量
        if (!Objects.equals(newLine.getStandardCapacity(), oldLine.getStandardCapacity())) {
            sbNew.append("基准容量: ").append(newLine.getStandardCapacity()).append(";");
            sbOld.append("基准容量: ").append(oldLine.getStandardCapacity()).append(";");
        }
        //协议容量
        if (!Objects.equals(newLine.getDealCapacity(), oldLine.getDealCapacity())) {
            sbNew.append("协议容量: ").append(newLine.getDealCapacity()).append(";");
            sbOld.append("协议容量: ").append(oldLine.getDealCapacity()).append(";");
        }
        sb.append(sbNew).append(sbOld);
        HttpResult<DictData> dicDataByCode = dicDataFeignClient.getDicDataByCode(DicDataEnum.LINE_PARAMETER.getCode());
        DictData data = dicDataByCode.getData();
        //创建对象
        PqsTerminalLogs terminalLogsNew = new PqsTerminalLogs();
        terminalLogsNew.setObjIndex(newLine.getId());
        terminalLogsNew.setTerminalDescribe(sb.toString());
        terminalLogsNew.setCreateBy(index);
        terminalLogsNew.setCreateTime(LocalDateTime.now());
        terminalLogsNew.setTerminalType(data.getId());
        terminalLogsNew.setState(1);
        iPqsTerminalLogsService.save(terminalLogsNew);
    }

    /**
     * 终端查询操作
     *
     * @param id pq_line表 id
     * @author cdf
     * @date 2021/7/19
     */
    @Override
    public TerminalVO queryTerminal(String id) {
        Line obj = this.getById(id);
        if (Objects.isNull(obj)) {
            throw new BusinessException(CommonResponseEnum.FAIL);
        }
        LambdaQueryWrapper<Line> lineLambdaQueryWrapper = new LambdaQueryWrapper<>();
        TerminalVO terminalVO = new TerminalVO();
        if (obj.getLevel().equals(LineBaseEnum.PROJECT_LEVEL.getCode())) {
            //点击项目节点
            assProject(obj, terminalVO);
        } else if (obj.getLevel().equals(LineBaseEnum.PROVINCE_LEVEL.getCode())) {
            //点击省份节点
            Line project = this.getById(obj.getPid());
            assProject(project, terminalVO);
            assProvince(obj, terminalVO);
        } else if (obj.getLevel().equals(LineBaseEnum.GD_LEVEL.getCode())) {
            //点击供电公司节点
            assGd(obj, terminalVO);
            Line province = this.getById(obj.getPid());
            assProvince(province, terminalVO);
            Line project = this.getById(province.getPid());
            assProject(project, terminalVO);
        } else if (obj.getLevel().equals(LineBaseEnum.SUB_LEVEL.getCode())) {
            //变电站
            assSub(obj, terminalVO);
            Line gdInformation = this.getById(obj.getPid());
            assGd(gdInformation, terminalVO);

            Line province = this.getById(gdInformation.getPid());
            assProvince(province, terminalVO);

            Line project = this.getById(province.getPid());
            assProject(project, terminalVO);


            //展示所有下级装置母线监测点
            lineLambdaQueryWrapper.clear();
            lineLambdaQueryWrapper.eq(Line::getPid, id)
                    .eq(Line::getState, DataStateEnum.ENABLE.getCode())
                    .orderByAsc(Line::getSort);
            List<Line> devList = this.list(lineLambdaQueryWrapper);
            List<DeviceVO> deviceDTOList = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(devList)) {
                for (Line device : devList) {
                    DeviceVO deviceVO = new DeviceVO();
                    BeanUtils.copyProperties(device, deviceVO);


                    Device deviceDetail = deviceMapper.selectById(device.getId());
                    BeanUtils.copyProperties(deviceDetail, deviceVO);
                    deviceVO.setDevIndex(device.getId());
                    //母线
                    lineLambdaQueryWrapper.clear();
                    lineLambdaQueryWrapper.eq(Line::getPid, device.getId())
                            .orderByAsc(Line::getSort)
                            .eq(Line::getState, DataStateEnum.ENABLE.getCode());

                    List<Line> subVoltageList = this.list(lineLambdaQueryWrapper);
                    if (CollectionUtil.isNotEmpty(subVoltageList)) {
                        List<SubVoltageVO> subVoltageVOS = new ArrayList<>();
                        for (Line subVoltage : subVoltageList) {
                            SubVoltageVO subVoltageVO = new SubVoltageVO();
                            BeanUtils.copyProperties(subVoltage, subVoltageVO);

                            Voltage voltage = voltageMapper.selectById(subVoltage.getId());
                            BeanUtils.copyProperties(voltage, subVoltageVO);
                            subVoltageVO.setSubvIndex(subVoltage.getId());
                            //监测点
                            lineLambdaQueryWrapper.clear();
                            lineLambdaQueryWrapper.eq(Line::getPid, subVoltage.getId())
                                    .eq(Line::getState, DataStateEnum.ENABLE.getCode());
                            List<Line> lineList = this.list(lineLambdaQueryWrapper);
                            if (CollectionUtil.isNotEmpty(lineList)) {
                                List<LineVO> lineVOS = new ArrayList<>();
                                for (Line line : lineList) {
                                    LineVO lineVO = new LineVO();
                                    BeanUtils.copyProperties(line, lineVO);
                                    LineDetail lineDetail = lineDetailMapper.selectById(line.getId());
                                    BeanUtils.copyProperties(lineDetail, lineVO);

                                    Overlimit overLimit = overlimitMapper.selectById(line.getId());
                                    lineVO.setVoltageDev(overLimit.getVoltageDev());
                                    lineVO.setUvoltageDev(overLimit.getUvoltageDev());
                                    lineVO.setLineIndex(line.getId());
                                    lineVOS.add(lineVO);
                                }
                                subVoltageVO.setLineVO(lineVOS);
                            }

                            subVoltageVOS.add(subVoltageVO);
                        }
                        deviceVO.setSubVoltageVOList(subVoltageVOS);
                    }
                    deviceDTOList.add(deviceVO);
                }
            }
            terminalVO.setDeviceVO(deviceDTOList);

        } else if (obj.getLevel().equals(LineBaseEnum.DEVICE_LEVEL.getCode())) {
            //点击装置节点

            List<DeviceVO> deviceList = new ArrayList<>();
            DeviceVO deviceVO = new DeviceVO();
            deviceVO.setName(obj.getName());
            deviceVO.setSort(obj.getSort());

            Device deviceDetail = deviceMapper.selectById(obj.getId());
            BeanUtils.copyProperties(deviceDetail, deviceVO);
            deviceVO.setDevIndex(obj.getId());

            lineLambdaQueryWrapper.clear();
            lineLambdaQueryWrapper.eq(Line::getPid, obj.getId())
                    .orderByAsc(Line::getSort)
                    .eq(Line::getState, DataStateEnum.ENABLE.getCode());
            List<Line> subvList = this.list(lineLambdaQueryWrapper);

            if (CollectionUtil.isNotEmpty(subvList)) {
                List<SubVoltageVO> subVList = new ArrayList<>();
                for (Line subVoltage : subvList) {

                    SubVoltageVO subVoltageVO = new SubVoltageVO();
                    BeanUtils.copyProperties(subVoltage, subVoltageVO);

                    Voltage voltage = voltageMapper.selectById(subVoltage.getId());
                    BeanUtils.copyProperties(voltage, subVoltageVO);
                    subVoltageVO.setSubvIndex(subVoltage.getId());

                    lineLambdaQueryWrapper.clear();
                    lineLambdaQueryWrapper.eq(Line::getPid, subVoltage.getId())
                            .orderByAsc(Line::getSort)
                            .eq(Line::getState, DataStateEnum.ENABLE.getCode());
                    List<Line> lineList = this.list(lineLambdaQueryWrapper);
                    if (CollectionUtil.isNotEmpty(lineList)) {
                        List<LineVO> lineVOList = new ArrayList<>();
                        for (Line line : lineList) {
                            LineVO lineVO = new LineVO();
                            BeanUtils.copyProperties(line, lineVO);

                            LineDetail lineDetail = lineDetailMapper.selectById(line.getId());
                            BeanUtils.copyProperties(lineDetail, lineVO);
                            lineVO.setLineIndex(line.getId());

                            Overlimit overLimit = overlimitMapper.selectById(line.getId());
                            lineVO.setVoltageDev(overLimit.getVoltageDev());
                            lineVO.setUvoltageDev(overLimit.getUvoltageDev());
                            lineVOList.add(lineVO);
                        }
                        subVoltageVO.setLineVO(lineVOList);
                    }

                    subVList.add(subVoltageVO);

                }
                deviceVO.setSubVoltageVOList(subVList);
            }
            deviceList.add(deviceVO);
            terminalVO.setDeviceVO(deviceList);

            commTerminalValue(terminalVO, obj.getPid());

        } else if (obj.getLevel().equals(LineBaseEnum.SUB_V_LEVEL.getCode())) {
            //点击母线节点
            SubVoltageVO subVoltageVO = new SubVoltageVO();
            subVoltageVO.setName(obj.getName());
            subVoltageVO.setSort(obj.getSort());
            Voltage voltage = voltageMapper.selectById(obj.getId());
            BeanUtils.copyProperties(voltage, subVoltageVO);
            subVoltageVO.setSubvIndex(obj.getId());

            lineLambdaQueryWrapper.clear();
            lineLambdaQueryWrapper.eq(Line::getPid, obj.getId())
                    .orderByAsc(Line::getSort)
                    .eq(Line::getState, DataStateEnum.ENABLE.getCode());
            List<Line> lineList = this.list(lineLambdaQueryWrapper);
            if (CollectionUtil.isNotEmpty(lineList)) {
                List<LineVO> lineVOS = new ArrayList<>();
                for (Line line : lineList) {
                    LineVO lineVO = new LineVO();
                    lineVO.setName(line.getName());
                    lineVO.setSort(line.getSort());
                    LineDetail lineDetail = lineDetailMapper.selectById(line.getId());
                    BeanUtils.copyProperties(lineDetail, lineVO);
                    lineVO.setLineIndex(line.getId());

                    Overlimit overlimit = overlimitMapper.selectById(line.getId());
                    lineVO.setVoltageDev(overlimit.getVoltageDev());
                    lineVO.setUvoltageDev(overlimit.getUvoltageDev());
                    lineVOS.add(lineVO);
                }
                subVoltageVO.setLineVO(lineVOS);
            }
            List<SubVoltageVO> subvList = new ArrayList<>();
            subvList.add(subVoltageVO);

            Line device = this.getById(obj.getPid());
            List<DeviceVO> deviceVOList = new ArrayList<>();
            if (Objects.nonNull(device)) {
                DeviceVO deviceVO = new DeviceVO();
                deviceVO.setName(device.getName());
                deviceVO.setSort(device.getSort());
                Device deviceDetail = deviceMapper.selectById(device.getId());
                BeanUtils.copyProperties(deviceDetail, deviceVO);
                deviceVO.setDevIndex(device.getId());

                deviceVO.setSubVoltageVOList(subvList);
                deviceVOList.add(deviceVO);
                terminalVO.setDeviceVO(deviceVOList);

                commTerminalValue(terminalVO, device.getPid());

            }


        } else if (obj.getLevel().equals(LineBaseEnum.LINE_LEVEL.getCode())) {

            //点击监测点
            DeviceVO deviceVO = new DeviceVO();

            LineVO lineVO = new LineVO();
            BeanUtils.copyProperties(obj, lineVO);
            LineDetail lineDetail = lineDetailMapper.selectById(id);
            if (Objects.nonNull(lineDetail)) {
                List<LineVO> lineVOS = new ArrayList<>();

                BeanUtils.copyProperties(lineDetail, lineVO);
                lineVO.setLineIndex(obj.getId());
                Overlimit overlimit = overlimitMapper.selectById(obj.getId());
                lineVO.setVoltageDev(overlimit.getVoltageDev());
                lineVO.setUvoltageDev(overlimit.getUvoltageDev());

                lineVOS.add(lineVO);

                Line subVoltage = this.getById(obj.getPid());
                if (Objects.nonNull(subVoltage)) {
                    List<SubVoltageVO> subVoltageVOS = new ArrayList<>();
                    SubVoltageVO subVoltageVO = new SubVoltageVO();
                    BeanUtils.copyProperties(subVoltage, subVoltageVO);
                    Voltage voltage = voltageMapper.selectById(subVoltage.getId());
                    subVoltageVO.setSubvIndex(subVoltage.getId());
                    BeanUtils.copyProperties(voltage, subVoltageVO);
                    subVoltageVO.setLineVO(lineVOS);
                    subVoltageVOS.add(subVoltageVO);


                    Line device = this.getById(subVoltage.getPid());
                    List<DeviceVO> deviceVOList = new ArrayList<>();
                    if (Objects.nonNull(device)) {
                        BeanUtils.copyProperties(device, deviceVO);

                        Device deviceDetail = deviceMapper.selectById(device.getId());
                        BeanUtils.copyProperties(deviceDetail, deviceVO);
                        deviceVO.setDevIndex(device.getId());

                        deviceVO.setSubVoltageVOList(subVoltageVOS);
                        deviceVOList.add(deviceVO);
                        terminalVO.setDeviceVO(deviceVOList);
                        //公共操作
                        commTerminalValue(terminalVO, device.getPid());
                    }


                }

            }

        }

        return terminalVO;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delTerminal(String id) {
        Line obj = this.getById(id);
        if (Objects.isNull(obj)) {
            throw new BusinessException(CommonResponseEnum.FAIL);
        }
        this.removeById(obj.getId());
        LambdaQueryWrapper<Line> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (obj.getLevel().equals(LineBaseEnum.PROJECT_LEVEL.getCode())) {
            //项目
            lambdaQueryWrapper.eq(Line::getPid, obj.getId())
                    .eq(Line::getState, DataStateEnum.ENABLE.getCode());
            List<Line> provinceList = this.list(lambdaQueryWrapper);
            if (CollectionUtil.isNotEmpty(provinceList)) {
                List<String> provinceIndexList = provinceList.stream().map(Line::getId).collect(Collectors.toList());
                //省份
                this.removeByIds(provinceIndexList);

                for (String provinceIndex : provinceIndexList) {
                    lambdaQueryWrapper.clear();
                    lambdaQueryWrapper.eq(Line::getPid, provinceIndex);
                    List<Line> gdInformationList = this.list(lambdaQueryWrapper);
                    if (CollectionUtil.isNotEmpty(gdInformationList)) {
                        List<String> gdIndexList = gdInformationList.stream().map(Line::getId).collect(Collectors.toList());
                        //供电公司
                        this.removeByIds(gdIndexList);

                        for (String gdIndex : gdIndexList) {
                            lambdaQueryWrapper.clear();
                            lambdaQueryWrapper.eq(Line::getPid, gdIndex);
                            List<Line> subStationList = this.list(lambdaQueryWrapper);
                            if (CollectionUtil.isNotEmpty(subStationList)) {
                                List<String> subIndexList = subStationList.stream().map(Line::getId).collect(Collectors.toList());
                                this.removeByIds(subIndexList);
                                substationMapper.deleteBatchIds(subIndexList);

                                for (String subIndex : subIndexList) {
                                    lambdaQueryWrapper.clear();
                                    lambdaQueryWrapper.in(Line::getPid, subIndex);
                                    List<Line> deviceList = this.list(lambdaQueryWrapper);
                                    if (CollectionUtil.isNotEmpty(deviceList)) {
                                        List<String> devIndexList = deviceList.stream().map(Line::getId).collect(Collectors.toList());
                                        this.removeByIds(devIndexList);
                                        deviceMapper.deleteBatchIds(devIndexList);
                                        devFuctionMapper.deleteBatchIds(devIndexList);

                                        for (String devIndex : devIndexList) {
                                            lambdaQueryWrapper.clear();
                                            lambdaQueryWrapper.eq(Line::getPid, devIndex);
                                            List<Line> subVoltageList = this.list(lambdaQueryWrapper);
                                            if (CollectionUtil.isNotEmpty(subVoltageList)) {
                                                List<String> subvIndexList = subVoltageList.stream().map(Line::getId).collect(Collectors.toList());
                                                this.removeByIds(subvIndexList);
                                                voltageMapper.deleteBatchIds(subvIndexList);

                                                for (String subvIndex : subvIndexList) {
                                                    lambdaQueryWrapper.clear();
                                                    lambdaQueryWrapper.eq(Line::getPid, subvIndex);
                                                    List<Line> lineList = this.list(lambdaQueryWrapper);
                                                    if (CollectionUtil.isNotEmpty(lineList)) {
                                                        List<String> lineIndexList = lineList.stream().map(Line::getId).collect(Collectors.toList());

                                                        this.removeByIds(lineIndexList);
                                                        lineDetailMapper.deleteBatchIds(lineIndexList);
                                                        overlimitMapper.deleteBatchIds(lineIndexList);

                                                        LambdaQueryWrapper<DeptLine> lineLambdaQueryWrapper = new LambdaQueryWrapper<>();
                                                        lineLambdaQueryWrapper.in(DeptLine::getLineId, lineIndexList);
                                                        deptLineMapper.delete(lineLambdaQueryWrapper);

                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

            }


        } else if (obj.getLevel().equals(LineBaseEnum.PROVINCE_LEVEL.getCode())) {
            //省份
            lambdaQueryWrapper.eq(Line::getPid, obj.getId());
            List<Line> gdInformationList = this.list(lambdaQueryWrapper);
            if (CollectionUtil.isNotEmpty(gdInformationList)) {
                List<String> gdIndexList = gdInformationList.stream().map(Line::getId).collect(Collectors.toList());
                //供电公司
                this.removeByIds(gdIndexList);

                for (String gdIndex : gdIndexList) {
                    lambdaQueryWrapper.clear();
                    lambdaQueryWrapper.eq(Line::getPid, gdIndex);
                    List<Line> subStationList = this.list(lambdaQueryWrapper);
                    if (CollectionUtil.isNotEmpty(subStationList)) {
                        List<String> subIndexList = subStationList.stream().map(Line::getId).collect(Collectors.toList());
                        this.removeByIds(subIndexList);
                        substationMapper.deleteBatchIds(subIndexList);

                        for (String subIndex : subIndexList) {
                            lambdaQueryWrapper.clear();
                            lambdaQueryWrapper.in(Line::getPid, subIndex);
                            List<Line> deviceList = this.list(lambdaQueryWrapper);
                            if (CollectionUtil.isNotEmpty(deviceList)) {
                                List<String> devIndexList = deviceList.stream().map(Line::getId).collect(Collectors.toList());
                                this.removeByIds(devIndexList);
                                deviceMapper.deleteBatchIds(devIndexList);
                                devFuctionMapper.deleteBatchIds(devIndexList);

                                for (String devIndex : devIndexList) {
                                    lambdaQueryWrapper.clear();
                                    lambdaQueryWrapper.eq(Line::getPid, devIndex);
                                    List<Line> subVoltageList = this.list(lambdaQueryWrapper);
                                    if (CollectionUtil.isNotEmpty(subVoltageList)) {
                                        List<String> subvIndexList = subVoltageList.stream().map(Line::getId).collect(Collectors.toList());
                                        this.removeByIds(subvIndexList);
                                        voltageMapper.deleteBatchIds(subvIndexList);

                                        for (String subvIndex : subvIndexList) {
                                            lambdaQueryWrapper.clear();
                                            lambdaQueryWrapper.eq(Line::getPid, subvIndex);
                                            List<Line> lineList = this.list(lambdaQueryWrapper);
                                            if (CollectionUtil.isNotEmpty(lineList)) {
                                                List<String> lineIndexList = lineList.stream().map(Line::getId).collect(Collectors.toList());

                                                this.removeByIds(lineIndexList);
                                                lineDetailMapper.deleteBatchIds(lineIndexList);
                                                overlimitMapper.deleteBatchIds(lineIndexList);

                                                LambdaQueryWrapper<DeptLine> lineLambdaQueryWrapper = new LambdaQueryWrapper<>();
                                                lineLambdaQueryWrapper.in(DeptLine::getLineId, lineIndexList);
                                                deptLineMapper.delete(lineLambdaQueryWrapper);

                                            }

                                        }
                                    }

                                }
                            }

                        }
                    }
                }
            }

        } else if (obj.getLevel().equals(LineBaseEnum.GD_LEVEL.getCode())) {
            //供电公司
            lambdaQueryWrapper.eq(Line::getPid, obj.getId());
            List<Line> subStationList = this.list(lambdaQueryWrapper);
            if (CollectionUtil.isNotEmpty(subStationList)) {
                List<String> subIndexList = subStationList.stream().map(Line::getId).collect(Collectors.toList());
                this.removeByIds(subIndexList);
                substationMapper.deleteBatchIds(subIndexList);


                for (String subIndex : subIndexList) {

                    lambdaQueryWrapper.clear();
                    lambdaQueryWrapper.in(Line::getPid, subIndex);
                    List<Line> deviceList = this.list(lambdaQueryWrapper);
                    if (CollectionUtil.isNotEmpty(deviceList)) {
                        List<String> devIndexList = deviceList.stream().map(Line::getId).collect(Collectors.toList());
                        this.removeByIds(devIndexList);
                        deviceMapper.deleteBatchIds(devIndexList);
                        devFuctionMapper.deleteBatchIds(devIndexList);

                        for (String devIndex : devIndexList) {
                            lambdaQueryWrapper.clear();
                            lambdaQueryWrapper.eq(Line::getPid, devIndex);
                            List<Line> subVoltageList = this.list(lambdaQueryWrapper);
                            if (CollectionUtil.isNotEmpty(subVoltageList)) {
                                List<String> subvIndexList = subVoltageList.stream().map(Line::getId).collect(Collectors.toList());
                                this.removeByIds(subvIndexList);
                                voltageMapper.deleteBatchIds(subvIndexList);

                                for (String subvIndex : subvIndexList) {
                                    lambdaQueryWrapper.clear();
                                    lambdaQueryWrapper.eq(Line::getPid, subvIndex);
                                    List<Line> lineList = this.list(lambdaQueryWrapper);
                                    if (CollectionUtil.isNotEmpty(lineList)) {
                                        List<String> lineIndexList = lineList.stream().map(Line::getId).collect(Collectors.toList());

                                        this.removeByIds(lineIndexList);
                                        lineDetailMapper.deleteBatchIds(lineIndexList);
                                        overlimitMapper.deleteBatchIds(lineIndexList);

                                        LambdaQueryWrapper<DeptLine> lineLambdaQueryWrapper = new LambdaQueryWrapper<>();
                                        lineLambdaQueryWrapper.in(DeptLine::getLineId, lineIndexList);
                                        deptLineMapper.delete(lineLambdaQueryWrapper);


                                    }

                                }
                            }

                        }
                    }

                }
            }

        } else if (obj.getLevel().equals(LineBaseEnum.SUB_LEVEL.getCode())) {
            //变电站
            lambdaQueryWrapper.clear();
            lambdaQueryWrapper.in(Line::getPid, obj.getId());
            List<Line> deviceList = this.list(lambdaQueryWrapper);
            if (CollectionUtil.isNotEmpty(deviceList)) {
                List<String> devIndexList = deviceList.stream().map(Line::getId).collect(Collectors.toList());
                this.removeByIds(devIndexList);
                deviceMapper.deleteBatchIds(devIndexList);
                devFuctionMapper.deleteBatchIds(devIndexList);

                for (String devIndex : devIndexList) {
                    lambdaQueryWrapper.clear();
                    lambdaQueryWrapper.eq(Line::getPid, devIndex);
                    List<Line> subVoltageList = this.list(lambdaQueryWrapper);
                    if (CollectionUtil.isNotEmpty(subVoltageList)) {
                        List<String> subvIndexList = subVoltageList.stream().map(Line::getId).collect(Collectors.toList());
                        this.removeByIds(subvIndexList);
                        voltageMapper.deleteBatchIds(subvIndexList);

                        for (String subvIndex : subvIndexList) {
                            lambdaQueryWrapper.clear();
                            lambdaQueryWrapper.eq(Line::getPid, subvIndex);
                            List<Line> lineList = this.list(lambdaQueryWrapper);
                            if (CollectionUtil.isNotEmpty(lineList)) {
                                List<String> lineIndexList = lineList.stream().map(Line::getId).collect(Collectors.toList());

                                this.removeByIds(lineIndexList);
                                lineDetailMapper.deleteBatchIds(lineIndexList);
                                overlimitMapper.deleteBatchIds(lineIndexList);

                                LambdaQueryWrapper<DeptLine> lineLambdaQueryWrapper = new LambdaQueryWrapper<>();
                                lineLambdaQueryWrapper.in(DeptLine::getLineId, lineIndexList);
                                deptLineMapper.delete(lineLambdaQueryWrapper);


                            }

                        }
                    }

                }
            }

        } else if (obj.getLevel().equals(LineBaseEnum.DEVICE_LEVEL.getCode())) {
            deviceMapper.deleteById(obj.getId());
            lambdaQueryWrapper.eq(Line::getPid, obj.getId());
            List<Line> subVoltageList = this.list(lambdaQueryWrapper);
            if (CollectionUtil.isNotEmpty(subVoltageList)) {
                List<String> subvIndexList = subVoltageList.stream().map(Line::getId).collect(Collectors.toList());
                this.removeByIds(subvIndexList);
                voltageMapper.deleteBatchIds(subvIndexList);

                for (String subvIndex : subvIndexList) {
                    lambdaQueryWrapper.clear();
                    lambdaQueryWrapper.eq(Line::getPid, subvIndex);
                    List<Line> lineList = this.list(lambdaQueryWrapper);
                    if (CollectionUtil.isNotEmpty(lineList)) {
                        List<String> lineIndexList = lineList.stream().map(Line::getId).collect(Collectors.toList());

                        this.removeByIds(lineIndexList);
                        lineDetailMapper.deleteBatchIds(lineIndexList);
                        overlimitMapper.deleteBatchIds(lineIndexList);

                        LambdaQueryWrapper<DeptLine> lineLambdaQueryWrapper = new LambdaQueryWrapper<>();
                        lineLambdaQueryWrapper.in(DeptLine::getLineId, lineIndexList);
                        deptLineMapper.delete(lineLambdaQueryWrapper);


                    }

                }
            }

        } else if (obj.getLevel().equals(LineBaseEnum.SUB_V_LEVEL.getCode())) {
            //母线
            lambdaQueryWrapper.eq(Line::getPid, obj.getId());
            List<Line> lineList = this.list(lambdaQueryWrapper);
            if (CollectionUtil.isNotEmpty(lineList)) {
                List<String> lineIndexList = lineList.stream().map(Line::getId).collect(Collectors.toList());

                this.removeByIds(lineIndexList);
                lineDetailMapper.deleteBatchIds(lineIndexList);
                overlimitMapper.deleteBatchIds(lineIndexList);

                LambdaQueryWrapper<DeptLine> lineLambdaQueryWrapper = new LambdaQueryWrapper<>();
                lineLambdaQueryWrapper.in(DeptLine::getLineId, lineIndexList);
                deptLineMapper.delete(lineLambdaQueryWrapper);


            }

        } else if (obj.getLevel().equals(LineBaseEnum.LINE_LEVEL.getCode())) {
            //监测点

            lineDetailMapper.deleteById(obj.getId());
            overlimitMapper.deleteById(obj.getId());
            deptLineMapper.deleteById(obj.getId());

        } else {
            throw new BusinessException(CommonResponseEnum.FAIL);
        }
        return true;
    }

    @Override
    public List<Line> getSubstationByIds(List<String> substationIds, List<String> scale) {
        return this.baseMapper.getSubStations(substationIds, scale);
//                .in(Line::getId, substationIds)
//                .eq(Line::getLevel, 3)
//                .in(CollUtil.isNotEmpty(scale),Line::getLevel)
//                .eq(Line::getState, DataStateEnum.ENABLE.getCode())
//                .list();
    }

    @Override
    public List<Line> getLineById(List<String> lineIds) {
        return this.lambdaQuery()
                .in(Line::getId, lineIds)
                .eq(Line::getLevel, 6)
                .eq(Line::getState, DataStateEnum.ENABLE.getCode())
                .list();
    }

    @Deprecated
    @Override
    public List<Line> getDeviceById(List<String> devIds, DeviceType deviceType) {
        return this.baseMapper.getDeviceById(devIds, deviceType);
    }

    @Override
    public List<TerminalBaseVO> getDeviceByIdOnOrOff(List<String> devIds, DeviceType deviceType, Integer comFlag) {
        return this.baseMapper.getDeviceByIdOnOrOff(devIds, deviceType, comFlag);
    }


    @Override
    public List<Line> getSubstationById(List<String> list) {
        return this.lambdaQuery().in(Line::getId, list).list();
    }

    @Override
    public List<Line> getLineByCondition(List<String> ids, DeviceInfoParam deviceInfoParam) {
        return this.baseMapper.getLineByCondition(ids, deviceInfoParam);
    }

    @Override
    public List<Line> getDeviceByCondition(List<String> devIds, DeviceType deviceType, List<SimpleDTO> manufacturer) {
        return this.baseMapper.getDeviceByCondition(devIds, deviceType, manufacturer);
    }

    @Override
    public List<Line> getVoltageByCondition(List<String> voltageIds, List<SimpleDTO> scale) {
        return this.baseMapper.getVoltageByCondition(voltageIds, scale);
    }

    @Override
    public List<String> getVoltageIdByScale(List<String> voltageIds, String scale) {
        return this.baseMapper.getVoltageIdByScale(voltageIds, scale);
    }

    @Override
    public List<String> getLineIdByLoadType(List<String> lineIds, String loadType) {
        return this.baseMapper.getLineIdByLoadType(lineIds, loadType);
    }

    @Override
    public List<String> getDeviceIdByManufacturer(List<String> deviceIds, String manufacturer) {
        return this.baseMapper.getDeviceIdByManufacturer(deviceIds, manufacturer);
    }

    @Override
    public List<BaseLineInfo> getBaseLineInfo(List<String> lineIndex) {
        return this.baseMapper.getBaseLineInfo(lineIndex);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importOracleTerminalData(MultipartFile file, HttpServletResponse response) {
        ImportParams params = new ImportParams();
        params.setHeadRows(1);
        params.setTitleRows(1);
        params.setNeedVerify(true);
        //第一个sheet为台账信息
        params.setStartSheetIndex(0);
        params.setSheetNum(1);
        try {
            ExcelImportResult<OracleTerminalExcel> terminalExcelExcelImportResult = ExcelImportUtil.importExcelMore(file.getInputStream(), OracleTerminalExcel.class, params);
            //第二个sheet为前置信息
            params.setStartSheetIndex(1);
            ExcelImportResult<NodeExcel> nodeExcelExcelImportResult = ExcelImportUtil.importExcelMore(file.getInputStream(), NodeExcel.class, params);
            //第三个sheet为限值信息
            params.setStartSheetIndex(2);
            ExcelImportResult<OverLimitExcel> overLimitExcelExcelImportResult = ExcelImportUtil.importExcelMore(file.getInputStream(), OverLimitExcel.class, params);
            //如果存在非法数据，将不合格的数据导出
            if (terminalExcelExcelImportResult.isVerifyFail()) {
                PoiUtil.exportFileByWorkbook(terminalExcelExcelImportResult.getFailWorkbook(), "非法台账信息.xlsx", response);
            } else {
                //执行前置机信息导入
                nodeService.saveBatchNodeInfo(nodeExcelExcelImportResult.getList());
                //执行台账信息导入（不考虑，存在监测点却不存在限值信息）
                return saveTerminalInfo(terminalExcelExcelImportResult.getList(), overLimitExcelExcelImportResult.getList());
            }
        } catch (Exception e) {
            throw new BusinessException(DeviceResponseEnum.IMPORT_ORACLE_EXCEPTION);
        }
        return null;
    }

    @Override
    public List<TerminalBaseExcel> exportTerminalBase() {
        return this.baseMapper.getTerminalBaseExcel();
    }

    @Override
    public void downTerminalTemplate(HttpServletResponse response) {
        ExportParams exportParams = new ExportParams("批量导入模板（请严格按照模板标准填入数据）", "台账信息");
        exportParams.setStyle(ExcelStyleUtil.class);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, TerminalBaseExcel.class, new ArrayList<TerminalBaseExcel>());
        List<DictData> businessList = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.BUSINESS_TYPE.getName()).getData();
        List<DictData> loadTypeList = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.INTERFERENCE_SOURCE_TYPE.getName()).getData();
        List<DictData> manufacturerList = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.DEV_MANUFACTURER.getName()).getData();
        List<DictData> devTypeList = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.DEV_TYPE.getName()).getData();
        List<DictData> frontList = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.FRONT_TYPE.getName()).getData();
        List<DictData> scaleList = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.DEV_VOLTAGE_STAND.getName()).getData();
        List<Node> nodeList = nodeService.nodeAllList();


        //这里是自己加的 带下拉框的代码
        ExcelUtil.selectList(workbook, 8, 8, new String[]{"虚拟设备", "实际设备", "离线设备"});
        ExcelUtil.selectList(workbook, 9, 9, new String[]{"暂态系统", "稳态系统", "双系统"});
        ExcelUtil.selectList(workbook, 10, 10, new String[]{"投运", "热备用", "停运"});
        ExcelUtil.selectList(workbook, 11, 11, manufacturerList.stream().map(DictData::getName).collect(Collectors.toList()).toArray(new String[]{}));
        ExcelUtil.selectList(workbook, 12, 12, devTypeList.stream().map(DictData::getName).collect(Collectors.toList()).toArray(new String[]{}));
        ExcelUtil.selectList(workbook, 17, 17, new String[]{"周期触发", "变为触发"});
        ExcelUtil.selectList(workbook, 18, 18, nodeList.stream().map(Node::getName).collect(Collectors.toList()).toArray(new String[]{}));
        ExcelUtil.selectList(workbook, 19, 19, frontList.stream().map(DictData::getName).collect(Collectors.toList()).toArray(new String[]{}));

        /*母线序号*/
        ExcelUtil.selectList(workbook, 23, 23, new String[]{"1", "2", "3", "3", "4", "5", "6"});
        ExcelUtil.selectList(workbook, 24, 24, scaleList.stream().map(DictData::getName).collect(Collectors.toList()).toArray(new String[]{}));
        ExcelUtil.selectList(workbook, 25, 25, new String[]{"虚拟母线", "实际母线"});
        ExcelUtil.selectList(workbook, 27, 27, new String[]{"1", "2", "3", "3", "4", "5", "6"});
        ExcelUtil.selectList(workbook, 28, 28, new String[]{"极重要", "重要", "普通", "不重要"});
        ExcelUtil.selectList(workbook, 35, 35, new String[]{"星型接法", "三角型接法", "开口三角型接法"});
        ExcelUtil.selectList(workbook, 36, 36, new String[]{"3", "5", "10"});
        ExcelUtil.selectList(workbook, 37, 37, loadTypeList.stream().map(DictData::getName).collect(Collectors.toList()).toArray(new String[]{}));
        ExcelUtil.selectList(workbook, 38, 38, businessList.stream().map(DictData::getName).collect(Collectors.toList()).toArray(new String[]{}));
        ExcelUtil.selectList(workbook, 41, 41, new String[]{"电网侧", "非电网侧"});
        ExcelUtil.selectList(workbook, 42, 42, new String[]{"不参与统计", "参与统计"});
        PoiUtil.exportFileByWorkbook(workbook, "台账导入模板.xlsx", response);
    }

    @Override
    public void downTerminalAutonomeTemplate(HttpServletResponse response) {
        ExportParams exportParams = new ExportParams("批量导入模板（请严格按照模板标准填入数据）", "台账信息");
        exportParams.setStyle(ExcelStyleUtil.class);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, TerminalBaseExcel.class, new ArrayList<TerminalBaseExcel>());
        List<DictData> businessList = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.BUSINESS_TYPE.getName()).getData();
        List<DictData> loadTypeList = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.INTERFERENCE_SOURCE_TYPE.getName()).getData();
        List<DictData> manufacturerList = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.DEV_MANUFACTURER.getName()).getData();
        List<DictData> devTypeList = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.DEV_TYPE.getName()).getData();
        List<DictData> frontList = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.FRONT_TYPE.getName()).getData();
        List<DictData> scaleList = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.DEV_VOLTAGE_STAND.getName()).getData();
        List<Node> nodeList = nodeService.nodeAllList();


        //这里是自己加的 带下拉框的代码
        ExcelUtil.selectList(workbook, 8, 8, new String[]{"离线设备"});
        ExcelUtil.selectList(workbook, 9, 9, new String[]{"暂态系统", "稳态系统", "双系统"});
        ExcelUtil.selectList(workbook, 10, 10, new String[]{"投运", "热备用", "停运"});
        ExcelUtil.selectList(workbook, 11, 11, manufacturerList.stream().map(DictData::getName).collect(Collectors.toList()).toArray(new String[]{}));
        ExcelUtil.selectList(workbook, 12, 12, devTypeList.stream().map(DictData::getName).collect(Collectors.toList()).toArray(new String[]{}));
        ExcelUtil.selectList(workbook, 17, 17, new String[]{"周期触发", "变为触发"});
        ExcelUtil.selectList(workbook, 18, 18, nodeList.stream().map(Node::getName).collect(Collectors.toList()).toArray(new String[]{}));
        ExcelUtil.selectList(workbook, 19, 19, frontList.stream().map(DictData::getName).collect(Collectors.toList()).toArray(new String[]{}));

        /*母线序号*/
        ExcelUtil.selectList(workbook, 23, 23, new String[]{"1", "2", "3", "3", "4", "5", "6"});
        ExcelUtil.selectList(workbook, 24, 24, scaleList.stream().map(DictData::getName).collect(Collectors.toList()).toArray(new String[]{}));
        ExcelUtil.selectList(workbook, 25, 25, new String[]{"虚拟母线", "实际母线"});
        ExcelUtil.selectList(workbook, 27, 27, new String[]{"1", "2", "3", "3", "4", "5", "6"});
        ExcelUtil.selectList(workbook, 28, 28, new String[]{"极重要", "重要", "普通", "不重要"});
        ExcelUtil.selectList(workbook, 35, 35, new String[]{"星型接法", "三角型接法", "开口三角型接法"});
        ExcelUtil.selectList(workbook, 36, 36, new String[]{"3", "5", "10"});
        ExcelUtil.selectList(workbook, 37, 37, loadTypeList.stream().map(DictData::getName).collect(Collectors.toList()).toArray(new String[]{}));
        ExcelUtil.selectList(workbook, 38, 38, businessList.stream().map(DictData::getName).collect(Collectors.toList()).toArray(new String[]{}));
        ExcelUtil.selectList(workbook, 41, 41, new String[]{"电网侧", "非电网侧"});
        ExcelUtil.selectList(workbook, 42, 42, new String[]{"不参与统计", "参与统计"});
        PoiUtil.exportFileByWorkbook(workbook, "台账导入模板.xlsx", response);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importTerminalBase(MultipartFile file, HttpServletResponse response) {
        ImportParams params = new ImportParams();
        params.setHeadRows(1);
        params.setTitleRows(1);
        params.setNeedVerify(true);
        //第一个sheet为台账信息
        params.setStartSheetIndex(0);
        params.setSheetNum(1);
        try {
            ExcelImportResult<TerminalBaseExcel> terminalBaseList = ExcelImportUtil.importExcelMore(file.getInputStream(), TerminalBaseExcel.class, params);
            //如果存在非法数据，将不合格的数据导出
            if (terminalBaseList.isVerifyFail()) {
                PoiUtil.exportFileByWorkbook(terminalBaseList.getFailWorkbook(), "非法台账信息.xlsx", response);
            } else {
                saveTerminalBase(terminalBaseList.getList());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Integer updatePqOverLimit() {
        List<LineDetail> lineDetailList = lineDetailMapper.selectList(new LambdaQueryWrapper<>());

        int count = 0;
        for (LineDetail lineDetail : lineDetailList) {
            overlimitMapper.deleteById(lineDetail.getId());
            Line line = lineMapper.selectById(lineDetail.getId());
            if (Objects.nonNull(line)) {
                Voltage voltage = voltageMapper.selectById(line.getPid());
                //监测点限值
                DictData scaleResult = dicDataFeignClient.getDicDataById(voltage.getScale()).getData();
                if (Objects.isNull(scaleResult)) {
                    throw new BusinessException(CommonResponseEnum.DIC_DATA);
                }


                float voltageLevel = Float.parseFloat(scaleResult.getValue());
                Overlimit overlimit = COverlimitUtil.globalAssemble(voltageLevel, lineDetail.getDealCapacity(), lineDetail.getDevCapacity(), lineDetail.getShortCapacity(), 1, 0);
                overlimit.setId(lineDetail.getId());
                overlimitMapper.insert(overlimit);
                count++;
            }
        }
        return count;
    }

    @Override
    public Boolean wiringDiagramUpload(MultipartFile[] files, String lineId) {

        LineDetail lineDetailValid = lineDetailMapper.selectById(lineId);
        if (Objects.isNull(lineDetailValid)) {
            throw new BusinessException(DeviceResponseEnum.LINE_NO);
        }
        String[] urls = new String[0];
        if(StrUtil.isNotBlank(lineDetailValid.getWiringDiagram())){
            urls = lineDetailValid.getWiringDiagram().split(StrUtil.COMMA);
        }

        if (urls.length + files.length > 2) {
            throw new BusinessException(DeviceResponseEnum.LINE_WIRING_MORE);
        }

        List<String> list = new ArrayList<>(Arrays.asList(urls));
        StrBuilder strBuilder = new StrBuilder();
        Arrays.stream(files).map(file -> fileStorageUtil.uploadMultipart(file, OssPath.WIRING_DIAGRAM)).forEach(list::add);

        for (int i = 0; i < list.size(); i++) {
            if (i == list.size() - 1) {
                strBuilder.append(list.get(i));
            } else {
                strBuilder.append(list.get(i)).append(StrUtil.COMMA);
            }
        }

        LineDetail lineDetail = new LineDetail();
        lineDetail.setWiringDiagram(strBuilder.toString());
        lineDetail.setId(lineId);
        lineDetailMapper.updateById(lineDetail);
        return true;
    }

    @Override
    public List<LineWiringDiagramVO> wiringDiagramShow(String lineId) {
        List<LineWiringDiagramVO> result = new ArrayList<>();
        LineDetail detail = lineDetailMapper.selectById(lineId);
        if (Objects.isNull(detail)) {
            throw new BusinessException(DeviceResponseEnum.LINE_NO);
        }
        if (StrUtil.isBlank(detail.getWiringDiagram())) {
            return result;
        }

        String[] urlStr = detail.getWiringDiagram().split(StrUtil.COMMA);
        for (String url : urlStr) {
            LineWiringDiagramVO lineWiringDiagramVO = new LineWiringDiagramVO();
            String realUrl = fileStorageUtil.getFileUrl(url);
            lineWiringDiagramVO.setLineId(detail.getId());
            lineWiringDiagramVO.setWiringDiagramName(url);
            lineWiringDiagramVO.setUrl(realUrl);
            result.add(lineWiringDiagramVO);
        }
        return result;
    }

    @Override
    public boolean wiringDiagramChange(MultipartFile file, String lineId, String wiringDiagramName) {
        LineDetail detail = lineDetailMapper.selectById(lineId);
        if (Objects.isNull(detail)) {
            throw new BusinessException(DeviceResponseEnum.LINE_NO);
        }
        if (StrUtil.isBlank(detail.getWiringDiagram())) {
            throw new BusinessException(DeviceResponseEnum.LINE_WIRING_DEL);
        }
        if (!detail.getWiringDiagram().contains(wiringDiagramName)) {
            throw new BusinessException(DeviceResponseEnum.LINE_WIRING_NO);
        }

        String[] urlArr = detail.getWiringDiagram().split(StrUtil.COMMA);
        List<String> newUrlList = Arrays.stream(urlArr).filter(s -> !s.equalsIgnoreCase(wiringDiagramName)).collect(Collectors.toList());

        if (newUrlList.size() > 1) {
            throw new BusinessException(DeviceResponseEnum.LINE_WIRING_MORE);
        }

        fileStorageUtil.deleteFile(wiringDiagramName);
        String url = fileStorageUtil.uploadMultipart(file, OssPath.WIRING_DIAGRAM);
        newUrlList.add(url);

        StrBuilder strBuilder = new StrBuilder();
        for (int i = 0; i < newUrlList.size(); i++) {
            if (i == newUrlList.size() - 1) {
                strBuilder.append(newUrlList.get(i));
            } else {
                strBuilder.append(newUrlList.get(i)).append(StrUtil.COMMA);
            }
        }

        LineDetail lineDetail = new LineDetail();
        lineDetail.setId(detail.getId());
        lineDetail.setWiringDiagram(strBuilder.toString());
        lineDetailMapper.updateById(lineDetail);
        return true;
    }

    @Override
    public boolean wiringDiagramDel(String lineId, String wiringDiagramName) {
        LineDetail detail = lineDetailMapper.selectById(lineId);
        if (Objects.isNull(detail)) {
            throw new BusinessException(DeviceResponseEnum.LINE_NO);
        }
        if (StrUtil.isBlank(detail.getWiringDiagram())) {
            throw new BusinessException(DeviceResponseEnum.LINE_WIRING_DEL);
        }
        if (!detail.getWiringDiagram().contains(wiringDiagramName)) {
            throw new BusinessException(DeviceResponseEnum.LINE_WIRING_NO);
        }
        fileStorageUtil.deleteFile(wiringDiagramName);

        String[] urlArr = detail.getWiringDiagram().split(StrUtil.COMMA);
        List<String> newUrlList = Arrays.stream(urlArr).filter(s -> !s.equalsIgnoreCase(wiringDiagramName)).collect(Collectors.toList());
        StrBuilder strBuilder = new StrBuilder();
        for (int i = 0; i < newUrlList.size(); i++) {
            if (i == newUrlList.size() - 1) {
                strBuilder.append(newUrlList.get(i));
            } else {
                strBuilder.append(newUrlList.get(i)).append(StrUtil.COMMA);
            }
        }
        LineDetail lineDetail = new LineDetail();
        lineDetail.setId(detail.getId());
        lineDetail.setWiringDiagram(strBuilder.toString());
        lineDetailMapper.updateById(lineDetail);
        return true;
    }


    private String saveTerminalInfo(List<OracleTerminalExcel> oracleTerminalExcels, List<OverLimitExcel> overLimitExcels) {
        List<OracleTerminalExcel.OracleTerminalExcelMsg> oracleTerminalExcelMsg = new ArrayList<>();
        //任意集合数据为空，不处理
        if (CollectionUtil.isNotEmpty(oracleTerminalExcels)) {
            Line temp;
            List<String> pids = new ArrayList<>();
            for (OracleTerminalExcel oracleTerminalExcel : oracleTerminalExcels) {
                //清空父id集合
                pids.clear();
                LambdaQueryWrapper<Line> lineLambdaQueryWrapper = new LambdaQueryWrapper<>();
                /*
                 * 处理项目,判断数据库中是否已存在，存在则保留其索引，不存在则插入新纪录
                 */
                String projectName = oracleTerminalExcel.getProjectName();
                temp = queryLine(lineLambdaQueryWrapper, projectName, "0", LineBaseEnum.PROJECT_LEVEL.getCode(), DataStateEnum.ENABLE.getCode());
                if (Objects.isNull(temp)) {
                    temp = assembleLine(projectName, LineBaseEnum.PROJECT_LEVEL.getCode(), "0", Stream.of("0").collect(Collectors.toList()));
                    this.baseMapper.insert(temp);
                }
                //添加项目索引
                pids.add(temp.getId());
                /*
                 * 处理省会
                 * 1、根据省会名称从sys_area中查询对应的id
                 * 2、再根据省会id去pq_line中查询是否存在省会记录
                 * 注：如果sys_ara不存在该省会，记录到oracleTerminalExcelMsg中，稍后导出给用户查看
                 */
                Area area = areaFeignClient.selectAreaByName(oracleTerminalExcel.getProvinceName()).getData();
                if (Objects.isNull(area)) {
                    oracleTerminalExcelMsg.add(assembleMsg(oracleTerminalExcel, "省会名称不存在，请联系管理员"));
                    continue;
                }
                temp = queryLine(lineLambdaQueryWrapper, area.getId(), pids.get(LineBaseEnum.PROJECT_LEVEL.getCode()), LineBaseEnum.PROVINCE_LEVEL.getCode(), DataStateEnum.ENABLE.getCode());
                if (Objects.isNull(temp)) {
                    temp = assembleLine(area.getId(), LineBaseEnum.PROVINCE_LEVEL.getCode(), pids.get(LineBaseEnum.PROJECT_LEVEL.getCode()), pids);
                    this.baseMapper.insert(temp);
                }
                //添加省会索引
                pids.add(temp.getId());
                /*
                 * 处理供电公司,判断数据库中是否已存在，存在则保留其索引，不存在则插入新纪录
                 */
                String gdName = oracleTerminalExcel.getGdName();
                temp = queryLine(lineLambdaQueryWrapper, gdName, pids.get(LineBaseEnum.PROVINCE_LEVEL.getCode()), LineBaseEnum.GD_LEVEL.getCode(), DataStateEnum.ENABLE.getCode());
                if (Objects.isNull(temp)) {
                    temp = assembleLine(gdName, LineBaseEnum.GD_LEVEL.getCode(), pids.get(LineBaseEnum.PROVINCE_LEVEL.getCode()), pids);
                    this.baseMapper.insert(temp);
                }
                //添加供电公司索引
                pids.add(temp.getId());
                /*
                 * 处理变电站
                 * 1、判断是否存在，不存在则插入
                 * 2、变电站的电压等级，如果字典表不存在，则自动录入
                 */
                String substationName = oracleTerminalExcel.getSubstationName();
                temp = queryLine(lineLambdaQueryWrapper, substationName, pids.get(LineBaseEnum.GD_LEVEL.getCode()), LineBaseEnum.SUB_LEVEL.getCode(), DataStateEnum.ENABLE.getCode());
                if (Objects.isNull(temp)) {
                    temp = assembleLine(substationName, LineBaseEnum.SUB_LEVEL.getCode(), pids.get(LineBaseEnum.GD_LEVEL.getCode()), pids);
                    this.baseMapper.insert(temp);
                    //处理电压等级字典表
                    DictData substationScale = dicDataFeignClient.getDicDataByNameAndTypeName(DicDataTypeEnum.DEV_VOLTAGE_STAND.getName(),oracleTerminalExcel.getSubStationScale()).getData();
                    if (Objects.isNull(substationScale)) {
                        //在电压等级内新增一条记录
                        substationScale = dicDataFeignClient.addDicData(DicDataTypeEnum.DEV_VOLTAGE.getName(), oracleTerminalExcel.getSubStationScale()).getData();
                    }
                    Substation substation = new Substation();
                    substation.setId(temp.getId());
                    substation.setScale(substationScale.getId());
                    substation.setLng(oracleTerminalExcel.getLng());
                    substation.setLat(oracleTerminalExcel.getLat());
                    substationMapper.insert(substation);
                } else {
                    //避免漏掉oracle项目中变电站经纬度的更改
                    Substation substation = substationMapper.selectById(temp.getId());
                    substation.setLng(oracleTerminalExcel.getLng());
                    substation.setLat(oracleTerminalExcel.getLat());
                    substationMapper.updateById(substation);
                }
                //添加变电站索引
                pids.add(temp.getId());
                /*
                 * 处理装置
                 * 1、判断是否存在，不存在则插入
                 * 2、终端厂家字典表中如果不存在，则自动录入
                 * 3、终端类型字典表中如果不存在，则自动录入
                 * 4、通讯类型需要截取，再做判断 CLD MMS PQDIF
                 * 5、当前变电站下的终端ip地址需要保持唯一，因为需要先插入终端，如果ip不唯一，需要删除插入的数据，并收集到错误信息列表中
                 */
                String deviceName = oracleTerminalExcel.getDeviceName();
                temp = queryLine(lineLambdaQueryWrapper, deviceName, pids.get(LineBaseEnum.SUB_LEVEL.getCode()), LineBaseEnum.DEVICE_LEVEL.getCode(), DataStateEnum.ENABLE.getCode());
                if (Objects.isNull(temp)) {
                    //判断是否因为改了终端名称导致没有查到数据
                    LambdaQueryWrapper<DeviceBak> deviceBakLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    deviceBakLambdaQueryWrapper.eq(DeviceBak::getDevId, oracleTerminalExcel.getDeviceId());
                    List<DeviceBak> deviceBaks = deviceBakService.list(deviceBakLambdaQueryWrapper);
                    List<String> devIds = deviceBaks.stream().map(DeviceBak::getId).collect(Collectors.toList());
                    List<Line> devList = new ArrayList<>();
                    if(!CollectionUtil.isEmpty(devIds)){
                        LambdaQueryWrapper<Line> devLambda = new LambdaQueryWrapper<>();
                        devLambda.in(Line::getId, devIds)
                                .orderByAsc(Line::getCreateTime)
                                .eq(Line::getState, DataStateEnum.ENABLE.getCode());
                        devList = lineMapper.selectList(devLambda);
                    }
                    if (CollectionUtil.isEmpty(deviceBaks) || CollectionUtil.isEmpty(devList)) {
                        temp = assembleLine(deviceName, LineBaseEnum.DEVICE_LEVEL.getCode(), pids.get(LineBaseEnum.SUB_LEVEL.getCode()), pids);
                        this.baseMapper.insert(temp);
                        List<Device> existIp = deviceMapper.getDeviceBySubId(pids.get(LineBaseEnum.SUB_LEVEL.getCode()), oracleTerminalExcel.getIp(), oracleTerminalExcel.getPort(), null);
                        if (CollectionUtil.isNotEmpty(existIp)) {
                            Device device = existIp.get(0);
                            if (!device.getId().equalsIgnoreCase(temp.getId())) {
                                oracleTerminalExcelMsg.add(assembleMsg(oracleTerminalExcel, "IP地址：" + oracleTerminalExcel.getIp() + "已存在"));
                                //删除刚刚新增装置信息
                                this.baseMapper.deleteById(temp.getId());
                                continue;
                            }
                        }
                        //处理终端厂家
                        DictData manufacturer = dicDataFeignClient.getDicDataByNameAndTypeName(DicDataTypeEnum.DEV_MANUFACTURER.getName(),oracleTerminalExcel.getManufacturer()).getData();
                        if (Objects.isNull(manufacturer)) {
                            //在终端厂家字典内新增一条记录
                            manufacturer = dicDataFeignClient.addDicData(DicDataTypeEnum.DEV_MANUFACTURER.getName(), oracleTerminalExcel.getManufacturer()).getData();
                        }
                        Device device = new Device();
                        BeanUtils.copyProperties(oracleTerminalExcel, device);
                        device.setId(temp.getId());
                        device.setManufacturer(manufacturer.getId());
                        device.setIp(oracleTerminalExcel.getIp());
                        //处理前置ID
                        Node node = nodeService.getNodeByNodeName(oracleTerminalExcel.getNodeName());
                        if (Objects.isNull(node)) {
                            oracleTerminalExcelMsg.add(assembleMsg(oracleTerminalExcel, "前置名：" + oracleTerminalExcel.getNodeName() + "不存在"));
                            //删除刚刚新增装置信息
                            this.baseMapper.deleteById(temp.getId());
                            continue;
                        }
                        device.setNodeId(node.getId());
                        String oracleDevType = oracleTerminalExcel.getDevType().toUpperCase();
                        String frontType = getComType(oracleDevType);
                        if (StringUtils.isBlank(frontType)) {
                            oracleTerminalExcelMsg.add(assembleMsg(oracleTerminalExcel, "前置类型不存在"));
                            //删除刚刚新增装置信息
                            this.baseMapper.deleteById(temp.getId());
                            continue;
                        }
                        //处理前置类型
                        DictData frontTypeDicData = dicDataFeignClient.getDicDataByNameAndTypeName(DicDataTypeEnum.FRONT_TYPE.getName(), frontType).getData();
                        if (Objects.isNull(frontTypeDicData)) {
                            //在通讯类型字典内新增一条记录
                            frontTypeDicData = dicDataFeignClient.addDicData(DicDataTypeEnum.FRONT_TYPE.getName(), frontType).getData();
                        }
                        device.setFrontType(frontTypeDicData.getId());
                        String devType = oracleDevType.replace("_" + frontType, "");
                        //处理终端类型
                        DictData devTypeDicData = dicDataFeignClient.getDicDataByNameAndTypeName(DicDataTypeEnum.DEV_TYPE.getName(),devType).getData();
                        if (Objects.isNull(devTypeDicData)) {
                            //在终端类型字典内新增一条记录
                            devTypeDicData = dicDataFeignClient.addDicData(DicDataTypeEnum.DEV_TYPE.getName(), devType).getData();
                        }
                        device.setDevType(devTypeDicData.getId());
                        deviceMapper.insert(device);
                        //插入新旧终端ID中间表
                        DeviceBak deviceBak = new DeviceBak();
                        deviceBak.setId(temp.getId());
                        deviceBak.setDevId(oracleTerminalExcel.getDeviceId());
                        deviceBakService.saveOrUpdate(deviceBak);
                    } else {
                        if (CollectionUtil.isNotEmpty(devList)) {
                            //仅保留最早创建的记录
                            List<String> ids = new ArrayList<>();
                            if (devList.size() > 2) {
                                for (int i = 1; i < devList.size(); i++) {
                                    ids.add(devList.get(i).getId());
                                }
                                //删除错误关系和错误数据，避免丢失influx数据，保留最早的终端记录
                                lineMapper.deleteBatchIds(ids);
                                deviceMapper.deleteBatchIds(ids);
                                LambdaQueryWrapper<DeviceBak> deviceBakLambdaQueryWrapper1 = new LambdaQueryWrapper<>();
                                deviceBakLambdaQueryWrapper1.in(DeviceBak::getId, ids);
                                deviceBakService.remove(deviceBakLambdaQueryWrapper1);
                            }else if(devList.size()==1){
                                temp = lineMapper.selectById(devList.get(0).getId());
                            }
                        }
                    }
                }
                //添加终端索引
                pids.add(temp.getId());
                /*
                 * 处理母线
                 * 1、判断是否存在，不存在则插入
                 * 2、判断线路号是否已被占用，被占用，返回错误信息
                 * 3、处理母线电压等级
                 */
                String subvName = oracleTerminalExcel.getSubvName();
                temp = queryLine(lineLambdaQueryWrapper, subvName, pids.get(LineBaseEnum.DEVICE_LEVEL.getCode()), LineBaseEnum.SUB_V_LEVEL.getCode(), DataStateEnum.ENABLE.getCode());
                if (Objects.isNull(temp)) {
                    temp = assembleLine(subvName, LineBaseEnum.SUB_V_LEVEL.getCode(), pids.get(LineBaseEnum.DEVICE_LEVEL.getCode()), pids);
                    this.baseMapper.insert(temp);
                    //判断线路号
                    Integer subvNum = oracleTerminalExcel.getSubvNum();
                    List<Voltage> voltages = voltageMapper.getVoltageByNum(pids.get(LineBaseEnum.DEVICE_LEVEL.getCode()), Stream.of(subvNum).collect(Collectors.toList()));
                    if (CollectionUtil.isNotEmpty(voltages)) {
                        Voltage voltage = voltages.get(0);
                        if (!voltage.getId().equalsIgnoreCase(temp.getId())) {
                            oracleTerminalExcelMsg.add(assembleMsg(oracleTerminalExcel, "母线线路号：" + subvNum + "已存在"));
                            //删除刚刚新增母线信息
                            this.baseMapper.deleteById(temp.getId());
                            continue;
                        }
                    }
                    Voltage voltage = new Voltage();
                    voltage.setNum(subvNum);
                    voltage.setId(temp.getId());
                    voltage.setModel(oracleTerminalExcel.getSubvModel());
                    //处理电压等级字典表
                    DictData subvScale = dicDataFeignClient.getDicDataByNameAndTypeName(DicDataTypeEnum.DEV_VOLTAGE_STAND.getName(),oracleTerminalExcel.getSubvScale()).getData();
                    if (Objects.isNull(subvScale)) {
                        //在电压等级内新增一条记录
                        subvScale = dicDataFeignClient.addDicData(DicDataTypeEnum.DEV_VOLTAGE.getName(), oracleTerminalExcel.getSubvScale()).getData();
                    }
                    voltage.setScale(subvScale.getId());
                    voltageMapper.insert(voltage);
                }
                //添加母线索引
                pids.add(temp.getId());
                /*
                 * 处理监测点
                 * 1、判断是否存在，不存在则插入
                 * 2、监测点线路号排重
                 * 3、干扰源类型字典判断
                 * 4、行业类型字典判断
                 * 5、终端等级字典判断
                 */
                String lineName = oracleTerminalExcel.getLineName();
                temp = queryLine(lineLambdaQueryWrapper, lineName, pids.get(LineBaseEnum.SUB_V_LEVEL.getCode()), LineBaseEnum.LINE_LEVEL.getCode(), DataStateEnum.ENABLE.getCode());
                if (Objects.nonNull(temp)) {
                    oracleTerminalExcelMsg.add(assembleMsg(oracleTerminalExcel, "监测点名称重复，请联系管理员"));
                } else {
                    //判断是否因为改了终端名称导致没有查到数据
                    LambdaQueryWrapper<LineBak> lineBakLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lineBakLambdaQueryWrapper.eq(LineBak::getLineId, oracleTerminalExcel.getId());
                    List<LineBak> lineBaks = lineBakService.list(lineBakLambdaQueryWrapper);
                    List<String> lineIds = lineBaks.stream().map(LineBak::getId).collect(Collectors.toList());
                    List<Line> lineList = new ArrayList<>();
                    if(CollectionUtil.isNotEmpty(lineIds)){
                        LambdaQueryWrapper<Line> devLambda = new LambdaQueryWrapper<>();
                        devLambda.in(Line::getId, lineIds)
                                .orderByAsc(Line::getCreateTime)
                                .eq(Line::getState, DataStateEnum.ENABLE.getCode());
                        lineList = lineMapper.selectList(devLambda);
                    }
                    if (CollectionUtil.isEmpty(lineBaks) || CollectionUtil.isEmpty(lineList)) {
                        temp = assembleLine(lineName, LineBaseEnum.LINE_LEVEL.getCode(), pids.get(LineBaseEnum.SUB_V_LEVEL.getCode()), pids);
                        this.baseMapper.insert(temp);
                        LineDetail lineDetail = new LineDetail();
                        BeanUtils.copyProperties(oracleTerminalExcel, lineDetail);
                        lineDetail.setId(temp.getId());
                        //判断监测点号是否已被占用
                        List<LineDetail> lineDetails = lineDetailMapper.getLineDetail(pids.get(LineBaseEnum.DEVICE_LEVEL.getCode()), Stream.of(oracleTerminalExcel.getLineNum()).collect(Collectors.toList()));
                        if (CollectionUtil.isNotEmpty(lineDetails)) {
                            LineDetail lineDetail1 = lineDetails.get(0);
                            if (lineDetail1.getId().equalsIgnoreCase(temp.getId())) {
                                oracleTerminalExcelMsg.add(assembleMsg(oracleTerminalExcel, "监测点线路号：" + oracleTerminalExcel.getLineNum() + "已存在"));
                                //删除刚刚新增装置信息
                                this.baseMapper.deleteById(temp.getId());
                                continue;
                            }
                        }
                        //获取该监测点的限值数据
//                    List<OverLimitExcel> overLimitList = overLimitExcels.stream()
//                            .filter(overLimitExcel -> overLimitExcel.getId().equals(oracleTerminalExcel.getId()))
//                            .collect(Collectors.toList());
//                    if (CollectionUtil.isEmpty(overLimitList)) {
//                        oracleTerminalExcelMsg.add(assembleMsg(oracleTerminalExcel, "没有找到该监测点的限值数据"));
//                        //删除刚刚新增装置信息
//                        this.baseMapper.deleteById(temp.getId());
//                        continue;
//                    }
                        lineDetail.setNum(oracleTerminalExcel.getLineNum());
                        //干扰源类型
                        DictData loadTypeDicData = dicDataFeignClient.getDicDataByNameAndTypeName(DicDataTypeEnum.INTERFERENCE_SOURCE_TYPE.getName(),oracleTerminalExcel.getLoadType()).getData();
                        if (Objects.isNull(loadTypeDicData)) {
                            //在电压等级内新增一条记录
                            loadTypeDicData = dicDataFeignClient.addDicData(DicDataTypeEnum.INTERFERENCE_SOURCE_TYPE.getName(), oracleTerminalExcel.getLoadType()).getData();
                        }
                        lineDetail.setLoadType(loadTypeDicData.getId());
                        //行业类型
                        DictData businessDicData = dicDataFeignClient.getDicDataByNameAndTypeName(DicDataTypeEnum.BUSINESS_TYPE.getName(),oracleTerminalExcel.getBusinessType()).getData();
                        if (Objects.isNull(businessDicData)) {
                            //在电压等级内新增一条记录
                            businessDicData = dicDataFeignClient.addDicData(DicDataTypeEnum.BUSINESS_TYPE.getName(), oracleTerminalExcel.getBusinessType()).getData();
                        }
                        lineDetail.setBusinessType(businessDicData.getId());
                        if (StringUtils.isBlank(oracleTerminalExcel.getMonitorId())) {
                            lineDetail.setMonitorFlag(0);
                        } else {
                            lineDetail.setMonitorFlag(1);
                        }
                        //终端等级,为空不处理，可以为空
                        if (StringUtils.isNotBlank(oracleTerminalExcel.getLineGrade())) {
                            DictData lineGradeDicData = dicDataFeignClient.getDicDataByNameAndTypeName(DicDataTypeEnum.DEV_LEVEL.getName(),oracleTerminalExcel.getLineGrade()).getData();
                            if (Objects.isNull(lineGradeDicData)) {
                                //在电压等级内新增一条记录
                                lineGradeDicData = dicDataFeignClient.addDicData(DicDataTypeEnum.DEV_LEVEL.getName(), oracleTerminalExcel.getLineGrade()).getData();
                            }
                            lineDetail.setLineGrade(lineGradeDicData.getId());
                        }

                        lineDetailMapper.insert(lineDetail);
                        LineBak lineBak = new LineBak();
                        lineBak.setId(temp.getId());
                        lineBak.setLineId(oracleTerminalExcel.getId());
                        lineBakService.save(lineBak);
//                    OverLimitExcel overLimitExcel = overLimitList.get(0);
//                    Overlimit overlimit = new Overlimit();
//                    BeanUtils.copyProperties(overLimitExcel, overlimit);
//                    overlimit.setId(temp.getId());
//                    overlimitMapper.insert(overlimit);
                    } else {
                        if (CollectionUtil.isNotEmpty(lineList)) {
                            //仅保留最早创建的记录
                            List<String> ids = new ArrayList<>();
                            if (lineList.size() > 2) {
                                for (int i = 1; i < lineList.size(); i++) {
                                    ids.add(lineList.get(i).getId());
                                }
                                //删除错误关系和错误数据，避免丢失influx数据，保留最早的终端记录
                                lineMapper.deleteBatchIds(ids);
                                lineDetailMapper.deleteBatchIds(ids);
                                LambdaQueryWrapper<LineBak> lineBakLambdaQueryWrapper1 = new LambdaQueryWrapper<>();
                                lineBakLambdaQueryWrapper1.in(LineBak::getId, ids);
                                lineBakService.remove(lineBakLambdaQueryWrapper1);
                            }
                        }
                    }
                }
            }
        }
        //错误信息不为空，则以excel的形式输出到前台
        this.updatePqOverLimit();
        if (CollectionUtil.isNotEmpty(oracleTerminalExcelMsg)) {
            ExcelUtil.exportExcel("失败列表.xlsx", OracleTerminalExcel.OracleTerminalExcelMsg.class, oracleTerminalExcelMsg);
            return null;
        }
        return CommonResponseEnum.SUCCESS.getMessage();
    }


    /**
     * 终端台账批量导入
     *
     * @author cdf
     * @date 2022/5/18
     */
    private void saveTerminalBase(List<TerminalBaseExcel> terminalBaseExcels) {
        List<TerminalBaseExcel.TerminalBaseExcelMsg> terminalBaseExcelMsgs = new ArrayList<>();
        //任意集合数据为空，不处理
        if (CollectionUtil.isNotEmpty(terminalBaseExcels)) {
            Line temp;
            List<String> pids = new ArrayList<>();
            for (TerminalBaseExcel terminalBaseExcel : terminalBaseExcels) {
                //清空父id集合
                pids.clear();
                LambdaQueryWrapper<Line> lineLambdaQueryWrapper = new LambdaQueryWrapper<>();
                /*
                 * 处理项目,判断数据库中是否已存在，存在则保留其索引，不存在则插入新纪录
                 */
                String projectName = terminalBaseExcel.getProjectName();
                temp = queryLine(lineLambdaQueryWrapper, projectName, "0", LineBaseEnum.PROJECT_LEVEL.getCode(), DataStateEnum.ENABLE.getCode());
                if (Objects.isNull(temp)) {
                    temp = assembleLine(projectName, LineBaseEnum.PROJECT_LEVEL.getCode(), "0", Stream.of("0").collect(Collectors.toList()));
                    this.baseMapper.insert(temp);
                }
                //添加项目索引
                pids.add(temp.getId());
                /*
                 * 处理省会
                 * 1、根据省会名称从sys_area中查询对应的id
                 * 2、再根据省会id去pq_line中查询是否存在省会记录
                 * 注：如果sys_ara不存在该省会，记录到oracleTerminalExcelMsg中，稍后导出给用户查看
                 */
                Area area = areaFeignClient.selectAreaByName(terminalBaseExcel.getProvinceName()).getData();
                if (Objects.isNull(area)) {
                    terminalBaseExcelMsgs.add(assembleBaseMsg(terminalBaseExcel, "省会名称不存在，请联系管理员"));
                    continue;
                }
                temp = queryLine(lineLambdaQueryWrapper, area.getId(), pids.get(LineBaseEnum.PROJECT_LEVEL.getCode()), LineBaseEnum.PROVINCE_LEVEL.getCode(), DataStateEnum.ENABLE.getCode());
                if (Objects.isNull(temp)) {
                    temp = assembleLine(area.getId(), LineBaseEnum.PROVINCE_LEVEL.getCode(), pids.get(LineBaseEnum.PROJECT_LEVEL.getCode()), pids);
                    this.baseMapper.insert(temp);
                }
                //添加省会索引
                pids.add(temp.getId());
                /*
                 * 处理供电公司,判断数据库中是否已存在，存在则保留其索引，不存在则插入新纪录
                 */
                String gdName = terminalBaseExcel.getGdName();
                temp = queryLine(lineLambdaQueryWrapper, gdName, pids.get(LineBaseEnum.PROVINCE_LEVEL.getCode()), LineBaseEnum.GD_LEVEL.getCode(), DataStateEnum.ENABLE.getCode());
                if (Objects.isNull(temp)) {
                    temp = assembleLine(gdName, LineBaseEnum.GD_LEVEL.getCode(), pids.get(LineBaseEnum.PROVINCE_LEVEL.getCode()), pids);
                    this.baseMapper.insert(temp);
                }
                //添加供电公司索引
                pids.add(temp.getId());
                /*
                 * 处理变电站
                 * 1、判断是否存在，不存在则插入
                 */
                String substationName = terminalBaseExcel.getSubstationName();
                temp = queryLine(lineLambdaQueryWrapper, substationName, pids.get(LineBaseEnum.GD_LEVEL.getCode()), LineBaseEnum.SUB_LEVEL.getCode(), DataStateEnum.ENABLE.getCode());
                if (Objects.isNull(temp)) {
                    temp = assembleLine(substationName, LineBaseEnum.SUB_LEVEL.getCode(), pids.get(LineBaseEnum.GD_LEVEL.getCode()), pids);
                    //处理电压等级字典表
                    DictData substationScale = dicDataFeignClient.getDicDataByNameAndType(terminalBaseExcel.getSubStationScale(), DicDataTypeEnum.DEV_VOLTAGE_STAND.getName()).getData();
                    if (Objects.isNull(substationScale)) {
                        terminalBaseExcelMsgs.add(assembleBaseMsg(terminalBaseExcel, "字典电压等级不存在"));
                        continue;
                    }
                    this.baseMapper.insert(temp);
                    Substation substation = new Substation();
                    substation.setId(temp.getId());
                    substation.setScale(substationScale.getId());
                    substation.setLng(terminalBaseExcel.getLng());
                    substation.setLat(terminalBaseExcel.getLat());
                    substationMapper.insert(substation);
                }
                //添加变电站索引
                pids.add(temp.getId());
                /*
                 * 处理装置
                 * 1、判断是否存在，不存在则插入
                 * 2、终端厂家字典表中如果不存在，则自动录入
                 * 3、终端类型字典表中如果不存在，则自动录入
                 * 4、通讯类型需要截取，再做判断 CLD MMS PQDIF
                 * 5、当前变电站下的终端ip地址需要保持唯一，因为需要先插入终端，如果ip不唯一，需要删除插入的数据，并收集到错误信息列表中
                 */
                String deviceName = terminalBaseExcel.getDeviceName();
                temp = queryLine(lineLambdaQueryWrapper, deviceName, pids.get(LineBaseEnum.SUB_LEVEL.getCode()), LineBaseEnum.DEVICE_LEVEL.getCode(), DataStateEnum.ENABLE.getCode());
                if (Objects.isNull(temp)) {
                    temp = assembleLine(deviceName, LineBaseEnum.DEVICE_LEVEL.getCode(), pids.get(LineBaseEnum.SUB_LEVEL.getCode()), pids);

                    List<Device> existIp = lineMapper.getDeviceBySubId(pids.get(LineBaseEnum.SUB_LEVEL.getCode()), Stream.of(terminalBaseExcel.getIp()).collect(Collectors.toList()));
                    if (CollectionUtil.isNotEmpty(existIp)) {
                        Device device = existIp.get(0);
                        if (!device.getId().equalsIgnoreCase(temp.getId())) {
                            terminalBaseExcelMsgs.add(assembleBaseMsg(terminalBaseExcel, "IP地址：" + terminalBaseExcel.getIp() + "已存在"));
                            continue;
                        }
                    }
                    //处理终端厂家
                    DictData manufacturer = dicDataFeignClient.getDicDataByName(terminalBaseExcel.getManufacturer()).getData();
                    if (Objects.isNull(manufacturer)) {
                        terminalBaseExcelMsgs.add(assembleBaseMsg(terminalBaseExcel, "终端厂家：" + terminalBaseExcel.getManufacturer() + "不存在"));
                        continue;
                    }
                    //处理前置ID
                    Node node = nodeService.getNodeByNodeName(terminalBaseExcel.getNodeName());
                    if (Objects.isNull(node)) {
                        terminalBaseExcelMsgs.add(assembleBaseMsg(terminalBaseExcel, "前置名：" + terminalBaseExcel.getNodeName() + "不存在"));
                        continue;
                    }
                    //处理前置类型
                    DictData frontTypeDicData = dicDataFeignClient.getDicDataByNameAndTypeName(DicDataTypeEnum.FRONT_TYPE.getName(), terminalBaseExcel.getFrontType()).getData();
                    if (Objects.isNull(frontTypeDicData)) {
                        terminalBaseExcelMsgs.add(assembleBaseMsg(terminalBaseExcel, "前置类型不存在"));
                        continue;
                    }
                    //处理终端类型
                    DictData devTypeDicData = dicDataFeignClient.getDicDataByName(terminalBaseExcel.getDevType()).getData();
                    if (Objects.isNull(devTypeDicData)) {
                        terminalBaseExcelMsgs.add(assembleBaseMsg(terminalBaseExcel, "字典装置型号不存在"));
                        continue;
                    }
                    this.baseMapper.insert(temp);
                    Device device = new Device();
                    BeanUtils.copyProperties(terminalBaseExcel, device);
                    device.setId(temp.getId());
                    device.setManufacturer(manufacturer.getId());
                    device.setIp(terminalBaseExcel.getIp());
                    device.setNodeId(node.getId());
                    device.setFrontType(frontTypeDicData.getId());
                    device.setDevType(devTypeDicData.getId());
                    device.setComFlag(0);
                    device.setCheckFlag(1);
                    device.setLoginTime(LocalDate.now());
                    device.setThisTimeCheck(LocalDate.now());
                    device.setNextTimeCheck(LocalDate.now().plusYears(3));
                    device.setUpdateTime(LocalDateTime.now());
                    device.setElectroplate(0);
                    device.setOnTime(1);
                    deviceMapper.insert(device);
                }
                //添加终端索引
                pids.add(temp.getId());
                /*
                 * 处理母线
                 * 1、判断是否存在，不存在则插入
                 * 2、判断线路号是否已被占用，被占用，返回错误信息
                 * 3、处理母线电压等级
                 */
                String subvName = terminalBaseExcel.getSubvName();
                temp = queryLine(lineLambdaQueryWrapper, subvName, pids.get(LineBaseEnum.DEVICE_LEVEL.getCode()), LineBaseEnum.SUB_V_LEVEL.getCode(), DataStateEnum.ENABLE.getCode());
                if (Objects.isNull(temp)) {
                    temp = assembleLine(subvName, LineBaseEnum.SUB_V_LEVEL.getCode(), pids.get(LineBaseEnum.DEVICE_LEVEL.getCode()), pids);

                    //判断线路号
                    Integer subvNum = terminalBaseExcel.getSubvNum();
                    List<Voltage> voltages = voltageMapper.getVoltageByNum(pids.get(LineBaseEnum.DEVICE_LEVEL.getCode()), Stream.of(subvNum).collect(Collectors.toList()));
                    if (CollectionUtil.isNotEmpty(voltages)) {
                        Voltage voltage = voltages.get(0);
                        if (!voltage.getId().equalsIgnoreCase(temp.getId())) {
                            terminalBaseExcelMsgs.add(assembleBaseMsg(terminalBaseExcel, "母线线路号：" + subvNum + "已存在"));
                            continue;
                        }
                    }
                    //处理电压等级字典表
                    DictData subvScale = dicDataFeignClient.getDicDataByNameAndType(terminalBaseExcel.getSubvScale(), DicDataTypeEnum.DEV_VOLTAGE_STAND.getName()).getData();
                    if (Objects.isNull(subvScale)) {
                        terminalBaseExcelMsgs.add(assembleBaseMsg(terminalBaseExcel, "字典电压等级：" + terminalBaseExcel.getSubStationScale() + "不存在"));
                        continue;
                    }
                    this.baseMapper.insert(temp);
                    Voltage voltage = new Voltage();
                    voltage.setNum(subvNum);
                    voltage.setId(temp.getId());
                    voltage.setModel(terminalBaseExcel.getSubvModel());
                    voltage.setScale(subvScale.getId());
                    voltageMapper.insert(voltage);
                }
                //添加母线索引
                pids.add(temp.getId());
                /*
                 * 处理监测点
                 * 1、判断是否存在，不存在则插入
                 * 2、监测点线路号排重
                 * 3、干扰源类型字典判断
                 * 4、行业类型字典判断
                 * 5、终端等级字典判断
                 */
                String lineName = terminalBaseExcel.getLineName();
                temp = queryLine(lineLambdaQueryWrapper, lineName, pids.get(LineBaseEnum.SUB_V_LEVEL.getCode()), LineBaseEnum.LINE_LEVEL.getCode(), DataStateEnum.ENABLE.getCode());
                if (Objects.nonNull(temp)) {
                    terminalBaseExcelMsgs.add(assembleBaseMsg(terminalBaseExcel, "监测点名称重复，请联系管理员"));
                } else {
                    //判断监测点号是否已被占用
                    List<LineDetail> lineDetails = lineDetailMapper.getLineDetail(pids.get(LineBaseEnum.DEVICE_LEVEL.getCode()), Stream.of(terminalBaseExcel.getLineNum()).collect(Collectors.toList()));
                    if (CollectionUtil.isNotEmpty(lineDetails)) {
                        LineDetail lineDetail1 = lineDetails.get(0);
                        if (lineDetail1.getId().equalsIgnoreCase(temp.getId())) {
                            terminalBaseExcelMsgs.add(assembleBaseMsg(terminalBaseExcel, "监测点线路号：" + terminalBaseExcel.getLineNum() + "已存在"));
                            continue;
                        }
                    }
                    temp = assembleLine(lineName, LineBaseEnum.LINE_LEVEL.getCode(), pids.get(LineBaseEnum.SUB_V_LEVEL.getCode()), pids);
                    this.baseMapper.insert(temp);
                    LineDetail lineDetail = new LineDetail();
                    BeanUtils.copyProperties(terminalBaseExcel, lineDetail);
                    //干扰源类型
                    DictData loadTypeDicData = dicDataFeignClient.getDicDataByName(terminalBaseExcel.getLoadType()).getData();
                    if (Objects.isNull(loadTypeDicData)) {
                        terminalBaseExcelMsgs.add(assembleBaseMsg(terminalBaseExcel, "字典干扰源类型：" + terminalBaseExcel.getLoadType() + "不存在"));
                        continue;
                    }
                    //行业类型
                    DictData businessDicData = dicDataFeignClient.getDicDataByName(terminalBaseExcel.getBusinessType()).getData();
                    if (Objects.isNull(businessDicData)) {
                        terminalBaseExcelMsgs.add(assembleBaseMsg(terminalBaseExcel, "字典行业类型：" + terminalBaseExcel.getBusinessType() + "不存在"));
                        continue;
                    }
                    //终端等级,为空不处理，可以为空
                    if (StringUtils.isNotBlank(terminalBaseExcel.getLineGrade())) {
                        DictData lineGradeDicData = dicDataFeignClient.getDicDataByName(terminalBaseExcel.getLineGrade()).getData();
                        if (Objects.isNull(lineGradeDicData)) {
                            terminalBaseExcelMsgs.add(assembleBaseMsg(terminalBaseExcel, "字典终端等级：" + terminalBaseExcel.getLineGrade() + "不存在"));
                            continue;
                        }
                        lineDetail.setLineGrade(lineGradeDicData.getId());
                    }

                    lineDetail.setId(temp.getId());
                    lineDetail.setNum(terminalBaseExcel.getLineNum());
                    lineDetail.setLoadType(loadTypeDicData.getId());
                    lineDetail.setBusinessType(businessDicData.getId());
                    if (StringUtils.isBlank(terminalBaseExcel.getMonitorId())) {
                        lineDetail.setMonitorFlag(0);
                    } else {
                        lineDetail.setMonitorFlag(1);
                    }
                    String[] pt = terminalBaseExcel.getPt().split("/");
                    String[] ct = terminalBaseExcel.getCt().split("/");
                    lineDetail.setPt1(Float.valueOf(pt[0]));
                    lineDetail.setPt2(Float.valueOf(pt[1]));
                    lineDetail.setCt1(Float.valueOf(ct[0]));
                    lineDetail.setCt2(Float.valueOf(ct[1]));

                    DictData dictData = dicDataFeignClient.getDicDataByNameAndTypeName(terminalBaseExcel.getSubvScale(), DicDataTypeEnum.DEV_VOLTAGE_STAND.getName()).getData();

                    lineDetailMapper.insert(lineDetail);
                    Overlimit overlimit = new Overlimit(temp.getId(), dictData.getValue(), terminalBaseExcel.getShortCapacity(), terminalBaseExcel.getStandardCapacity(), terminalBaseExcel.getDealCapacity(), terminalBaseExcel.getDevCapacity());
                    overlimit.setId(temp.getId());
                    overlimitMapper.insert(overlimit);
                }
            }
        }
        //错误信息不为空，则以excel的形式输出到前台
        if (CollectionUtil.isNotEmpty(terminalBaseExcelMsgs)) {
            ExcelUtil.exportExcel("失败列表.xlsx", TerminalBaseExcel.TerminalBaseExcelMsg.class, terminalBaseExcelMsgs);
        }
    }


    /**
     * 根据条件查询出台账信息
     *
     * @param name  名称
     * @param pid   父id
     * @param level 层级
     * @param state 状态 0 删除 1 正常
     * @return 终端信息
     */
    private Line queryLine(LambdaQueryWrapper<Line> lineLambdaQueryWrapper, String name, String pid, Integer level, Integer state) {
        lineLambdaQueryWrapper.clear();
        lineLambdaQueryWrapper.eq(Line::getName, name)
                .eq(Line::getPid, pid)
                .eq(Line::getLevel, level)
                .eq(Line::getState, state);
        return this.baseMapper.selectOne(lineLambdaQueryWrapper);
    }

    /**
     * 组装台账信息，稍后入库
     *
     * @param name  名称
     * @param level 等级
     * @param pid   父ID
     * @param pids  上层所有ID
     */
    private Line assembleLine(String name, Integer level, String pid, List<String> pids) {
        Line line = new Line();
        line.setName(name);
        line.setLevel(level);
        line.setPid(pid);
        line.setPids(String.join(",", pids));
        line.setSort(0);
        line.setState(DataStateEnum.ENABLE.getCode());
        return line;
    }

    private Line assembleLine(String name, Integer level, String pid, String pids, Integer sort) {
        Line line = new Line();
        line.setName(name);
        line.setLevel(level);
        line.setPid(pid);
        line.setPids(pids);
        line.setSort(sort);
        line.setState(DataStateEnum.ENABLE.getCode());
        return line;
    }

    /**
     * 组装不能正常插入的记录，稍后导出给用户
     *
     * @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;
    }

    private TerminalBaseExcel.TerminalBaseExcelMsg assembleBaseMsg(TerminalBaseExcel terminalBaseExcel, String msg) {
        TerminalBaseExcel.TerminalBaseExcelMsg terminalBaseExcelMsg = new TerminalBaseExcel.TerminalBaseExcelMsg();
        BeanUtils.copyProperties(terminalBaseExcel, terminalBaseExcelMsg);
        terminalBaseExcelMsg.setMsg(msg);
        return terminalBaseExcelMsg;
    }

    /**
     * 根据oracle中的终端类型获取 通讯类型
     * 目前常见的有：_CLD _MMS _PQDIF
     *
     * @param oracleDevType oracle库中的终端类型
     * @return 通讯类型
     */
    private String getComType(String oracleDevType) {
        if (oracleDevType.contains("_CLD")) {
            return "CLD";
        } else if (oracleDevType.contains("_MMS")) {
            return "MMS";
        } else if (oracleDevType.contains("_PQDIF")) {
            return "PQDIF";
        }
        return "";
    }


    /**
     * 校验参数，检查是否存在相同名称
     * param
     */
    private void checkName(AddTerminalParam addTerminalParam, Integer level, String pid) {
        LambdaQueryWrapper<Line> lineLambdaQueryWrapper = new LambdaQueryWrapper<>();
        LineBaseEnum lineBaseEnum = LineBaseEnum.getLineBaseEnumByCode(level);
        switch (lineBaseEnum) {
            case PROJECT_LEVEL:
                lineLambdaQueryWrapper.eq(Line::getName, addTerminalParam.getProjectParam().getName())
                        .eq(Line::getLevel, lineBaseEnum.getCode());
                break;
            case PROVINCE_LEVEL:
                lineLambdaQueryWrapper
                        .eq(Line::getName, addTerminalParam.getProvinceParam().getName())
                        .eq(Line::getPid, pid);
                break;
            case GD_LEVEL:
                lineLambdaQueryWrapper.eq(Line::getName, addTerminalParam.getGdInformationParam().getName())
                        .eq(Line::getPid, pid);
                break;
            case SUB_LEVEL:
                lineLambdaQueryWrapper.eq(Line::getName, addTerminalParam.getSubStationParam().getName())
                        .eq(Line::getPid, pid);
                break;
            default:
                throw new BusinessException(DeviceResponseEnum.INVALID_LEVEL);
        }

        lineLambdaQueryWrapper.eq(Line::getState, DataStateEnum.ENABLE.getCode());

        int countByAccount = this.count(lineLambdaQueryWrapper);
        //大于等于1个则表示重复
        if (countByAccount >= 1) {
            switch (lineBaseEnum) {
                case PROJECT_LEVEL:
                    throw new BusinessException(DeviceResponseEnum.PROJECT_SAME_NAME);
                case PROVINCE_LEVEL:
                    throw new BusinessException(DeviceResponseEnum.PROVINCE_SAME_NAME);
                case GD_LEVEL:
                    throw new BusinessException(DeviceResponseEnum.GD_SAME_NAME);
                case SUB_LEVEL:
                    throw new BusinessException(DeviceResponseEnum.SUB_SAME_NAME);
                default:
                    throw new BusinessException(DeviceResponseEnum.INVALID_LEVEL);
            }
        }
    }


    /**
     * 校验参数，检查是否存在相同名称
     * param
     */
    private void checkUpdateName(UpdateTerminalParam updateTerminalParam, Integer level, String pid) {
        LambdaQueryWrapper<Line> lineLambdaQueryWrapper = new LambdaQueryWrapper<>();
        LineBaseEnum lineBaseEnum = LineBaseEnum.getLineBaseEnumByCode(level);
        switch (lineBaseEnum) {
            case PROJECT_LEVEL:
                lineLambdaQueryWrapper.eq(Line::getName, updateTerminalParam.getProjectUpdateParam().getName())
                        .eq(Line::getLevel, lineBaseEnum.getCode())
                        .ne(Line::getId, (updateTerminalParam.getProjectUpdateParam()).getProjectIndex());
                break;
            case GD_LEVEL:
                lineLambdaQueryWrapper.eq(Line::getName, updateTerminalParam.getGdInformationUpdateParam().getName())
                        .eq(Line::getPid, pid)
                        .ne(Line::getId, (updateTerminalParam.getGdInformationUpdateParam()).getGdIndex());
                break;
            case SUB_LEVEL:
                lineLambdaQueryWrapper.eq(Line::getName, updateTerminalParam.getSubStationUpdateParam().getName())
                        .eq(Line::getPid, pid)
                        .ne(Line::getId, (updateTerminalParam.getSubStationUpdateParam()).getSubIndex());
                break;
            default:
                throw new BusinessException(DeviceResponseEnum.INVALID_LEVEL);
        }
        lineLambdaQueryWrapper.eq(Line::getState, DataStateEnum.ENABLE.getCode());
        int countByAccount = this.count(lineLambdaQueryWrapper);
        //大于等于1个则表示重复
        if (countByAccount >= 1) {
            switch (lineBaseEnum) {
                case PROJECT_LEVEL:
                    throw new BusinessException(DeviceResponseEnum.PROJECT_SAME_NAME);
                case GD_LEVEL:
                    throw new BusinessException(DeviceResponseEnum.GD_SAME_NAME);
                case SUB_LEVEL:
                    throw new BusinessException(DeviceResponseEnum.SUB_SAME_NAME);
                default:
                    throw new BusinessException(DeviceResponseEnum.INVALID_LEVEL);
            }
        }
    }


    /**
     * 组装台账信息
     *
     * @author cdf
     * @date 2022/2/14
     */
    private TerminalVO commTerminalValue(TerminalVO terminalVO, String subId) {
        if (StrUtil.isBlank(subId) || Objects.isNull(terminalVO)) {
            log.error("赋值出错");
            return null;
        }

        Line subStation = this.getById(subId);
        if (Objects.nonNull(subStation)) {
            assSub(subStation, terminalVO);

            Line gdInformation = this.getById(subStation.getPid());
            assGd(gdInformation, terminalVO);

            Line province = this.getById(gdInformation.getPid());
            assProvince(province, terminalVO);

            Line project = this.getById(province.getPid());
            assProject(project, terminalVO);

            return terminalVO;
        } else {
            throw new BusinessException(DeviceResponseEnum.SUB_NO);
        }

    }

    /**
     * 组装项目
     */
    private void assProject(Line project, TerminalVO terminalVO) {
        ProjectVO projectVO = new ProjectVO();
        projectVO.setProjectIndex(project.getId());
        projectVO.setName(project.getName());
        projectVO.setSort(project.getSort());
        terminalVO.setProjectVO(projectVO);

    }

    /**
     * 组装省份
     */
    private void assProvince(Line province, TerminalVO terminalVO) {
        ProvinceVO provinceVO = new ProvinceVO();
        provinceVO.setProvinceIndex(province.getId());
        provinceVO.setName(province.getName());
        provinceVO.setSort(province.getSort());
        terminalVO.setProvinceVO(provinceVO);
    }

    /**
     * 组装供电公司
     */
    private void assGd(Line gdInformation, TerminalVO terminalVO) {
        GdInformationVO gdInformationVO = new GdInformationVO();
        gdInformationVO.setGdIndex(gdInformation.getId());
        gdInformationVO.setName(gdInformation.getName());
        gdInformationVO.setSort(gdInformation.getSort());
        terminalVO.setGdInformationVO(gdInformationVO);
    }

    /**
     * 组装变电站
     */
    private void assSub(Line subStation, TerminalVO terminalVO) {
        Substation substation = substationMapper.selectById(subStation.getId());
        SubStationVO subStationVO = new SubStationVO();
        subStationVO.setSubIndex(subStation.getId());
        subStationVO.setName(subStation.getName());
        subStationVO.setSort(subStation.getSort());
        BeanUtils.copyProperties(substation, subStationVO);
        terminalVO.setSubStationVO(subStationVO);
    }
}
