package com.njcn.energy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.energy.mapper.DataMouldMapper;
import com.njcn.energy.mapper.DevVersionMapper;
import com.njcn.energy.mapper.NetDevMapper;
import com.njcn.energy.pojo.constant.ApiParam;
import com.njcn.energy.pojo.constant.DataType;
import com.njcn.energy.pojo.constant.ModelState;
import com.njcn.energy.pojo.dto.*;
import com.njcn.energy.pojo.enums.EnergyResponseEnum;
import com.njcn.energy.pojo.param.*;
import com.njcn.energy.pojo.po.*;
import com.njcn.energy.service.*;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 类的介绍：
 *
 * @author xuyang
 * @version 1.0.0
 * @createTime 2022/2/28 15:02
 */
@Service
@AllArgsConstructor
public class ModelServiceImpl implements IModelService {

    private final NetDevMapper netDevMapper;

    private final DevVersionMapper devVersionMapper;

    private final IDevVersionService devVersionService;

    private final IHardwareService hardwareService;

    private final ILogicDeviceLineService logicDeviceLineService;

    private final IEleLineService lineService;

    private final IDevModelService devModelService;

    private final DataMouldMapper dataMouldMapper;

    private final IDataSetService dataSetService;

    private final IDataArrayService dataArrayService;

    private final IEleEpdPqdService eleEpdPqdService;

    private final IEleMdService eleMdService;

    private final IEleEvtService eleEvtService;

    private final IEleEvtParamService eleEvtParamService;

    private final IEleAlmService eleAlmService;

    private final IEleStsService eleStsService;

    private final IEleDiService eleDiService;

    private final IEleDoService eleDoService;

    private final IEleParmService eleParmService;

    private final IEleCtrlService eleCtrlService;

    private final IEleActrlService eleActrlService;

    private final IDataGroupService dataGroupService;

    private final IGroupArrayService groupArrayService;

    private final INetDevService netDevService;

    private final ILogicAccessService logicAccessService;

    private final IEleDictService eleDictService;

    private final IEleTopicService eleTopicService;

    private final IEleInformationService eleInformationService;

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public String deviceRegister(String json){
        Gson gson = new Gson();
        RegisterDTO.RegisterRequest registerDTO = gson.fromJson(json, RegisterDTO.RegisterRequest.class);
        //装置id集合
        List<String> didList = registerDTO.getParam().getDid();
        QueryWrapper<NetDev> netDevQueryWrapper = new QueryWrapper<>();
        netDevQueryWrapper.eq("ele_net_dev.ndid",registerDTO.getParam().getNDid());
        NetDev netDev = netDevMapper.selectOne(netDevQueryWrapper);
        RegisterDTO.RegisterResponse response = new RegisterDTO.RegisterResponse();
        RegisterParamDTO.RegisterParamResponse responseParam = new RegisterParamDTO.RegisterParamResponse();
        BeanUtil.copyProperties(registerDTO,response);
        BeanUtil.copyProperties(response.getParam(),responseParam);
        response.setType(ApiParam.REP_DEV_REGISTER);
        response.setMid(registerDTO.getMid());
        responseParam.setResType(registerDTO.getParam().getType());
        //注册装置有重复
        if (didList.stream().distinct().count() != didList.size()){
            response.setCode(Integer.parseInt(EnergyResponseEnum.REPEAT_ERROR.getCode()));
            response.setMsg(EnergyResponseEnum.REPEAT_ERROR.getMessage());
            responseParam.setRes(ModelState.FAIL);
            response.setParam(responseParam);
            response.setTimestamp(Long.toString(System.currentTimeMillis()/1000));
            return gson.toJson(response);
        }
        //时间戳缺失
        if (StringUtils.isBlank(registerDTO.getTimestamp())){
            response.setCode(Integer.parseInt(EnergyResponseEnum.PARAM_FAIL_TIMESTAMP.getCode()));
            response.setMsg(EnergyResponseEnum.PARAM_FAIL_TIMESTAMP.getMessage());
            responseParam.setRes(ModelState.FAIL);
            response.setParam(responseParam);
            response.setTimestamp(Long.toString(System.currentTimeMillis()/1000));
            return gson.toJson(response);
        }
        //类型缺失
        if (StringUtils.isBlank(registerDTO.getType())){
            response.setCode(Integer.parseInt(EnergyResponseEnum.PARAM_FAIL_TYPE.getCode()));
            response.setMsg(EnergyResponseEnum.PARAM_FAIL_TYPE.getMessage());
            responseParam.setRes(ModelState.FAIL);
            response.setParam(responseParam);
            response.setTimestamp(Long.toString(System.currentTimeMillis()/1000));
            return gson.toJson(response);
        }
        //类型错误
        else if (!Objects.equals(registerDTO.getType(), ApiParam.CMD_DEV_REGISTER)){
            response.setCode(Integer.parseInt(EnergyResponseEnum.TYPE_ERROR.getCode()));
            response.setMsg(EnergyResponseEnum.TYPE_ERROR.getMessage());
            responseParam.setRes(ModelState.FAIL);
            response.setParam(responseParam);
            response.setTimestamp(Long.toString(System.currentTimeMillis()/1000));
            return gson.toJson(response);
        }
        //联网装置不存在
        if (Objects.isNull(netDev)){
            //网关不存在直接返回错误
            response.setCode(Integer.parseInt(EnergyResponseEnum.REGISTER_ERROR.getCode()));
            response.setMsg(EnergyResponseEnum.REGISTER_ERROR.getMessage());
            responseParam.setRes(ModelState.FAIL);
        }else {
            //网关存在，判断是注册还是取消注册
            if (registerDTO.getParam().getType() == 1){
                if (!CollectionUtils.isEmpty(logicAccessService.findAccessDev(registerDTO.getParam().getDid()))){
                    response.setCode(Integer.parseInt(EnergyResponseEnum.EXIST_ERROR.getCode()));
                    response.setMsg(EnergyResponseEnum.EXIST_ERROR.getMessage());
                    responseParam.setRes(ModelState.FAIL);
                    response.setParam(responseParam);
                    response.setTimestamp(Long.toString(System.currentTimeMillis()/1000));
                    return gson.toJson(response);
                }
                //逻辑设备注册表logic_access入库 有之前取消注册过的就修改状态，没有则新增
                didList.forEach(item->{
                    if (!Objects.isNull(logicAccessService.findCancelAccessDev(item))){
                        logicAccessService.accessCancelDev(item);
                    } else {
                        LogicAccess logicAccess = new LogicAccess();
                        logicAccess.setPid(netDevService.findByNdid(registerDTO.getParam().getNDid()).getId());
                        logicAccess.setDid(item);
                        logicAccess.setState(DataStateEnum.ENABLE.getCode());
                        logicAccess.setCreateTime(LocalDateTime.now());
                        logicAccessService.add(logicAccess);
                    }
                });
            } else {
                for (String item:didList) {
                    if (Objects.isNull(logicAccessService.getAccessDev(item))){
                        response.setCode(Integer.parseInt(EnergyResponseEnum.CANCEL_ERROR.getCode()));
                        response.setMsg(EnergyResponseEnum.CANCEL_ERROR.getMessage());
                        responseParam.setRes(ModelState.FAIL);
                        response.setParam(responseParam);
                        response.setTimestamp(Long.toString(System.currentTimeMillis()/1000));
                        return gson.toJson(response);
                    }
                }
                //查询是否有在线的装置，下线之前记录信息
                LocalDateTime offlineTime = LocalDateTime.ofEpochSecond(Long.parseLong(registerDTO.getTimestamp()),0, ZoneOffset.of("+8"));
                List<EleInformation> informationList = new ArrayList<>();
                List<LogicAccess> list = logicAccessService.getLogicAccess(registerDTO.getParam().getNDid(),didList);
                if (!CollectionUtils.isEmpty(list)){
                    list.forEach(item->{
                        EleInformation eleInformation = new EleInformation();
                        eleInformation.setUpdateTime(offlineTime);
                        eleInformation.setDid(item.getDid());
                        eleInformation.setType(ModelState.offline);
                        eleInformation.setDescription("装置下线");
                        informationList.add(eleInformation);
                    });
                    eleInformationService.addInformation(informationList);
                }
                //删除注册的逻辑设备(修改状态)
                logicAccessService.deleteByDid(didList);
            }
            response.setCode(Integer.parseInt(EnergyResponseEnum.SUCCESS.getCode()));
            response.setMsg(EnergyResponseEnum.SUCCESS.getMessage());
            responseParam.setRes(ModelState.SUCCESS);
        }
        response.setParam(responseParam);
        response.setTimestamp(Long.toString(System.currentTimeMillis()/1000));
        return gson.toJson(response);
    }


    @Override
    @Transactional(rollbackFor = {Exception.class})
    public String deviceAccess(String json,String ndid) {
        Set<String> versionSet = new HashSet<>();
        Gson gson = new Gson();
        AccessDTO.AccessRequest access = gson.fromJson(json,AccessDTO.AccessRequest.class);
        AccessDTO.AccessResponse response = new AccessDTO.AccessResponse();
        BeanUtil.copyProperties(access,response);
        response.setParam(null);
        response.setType(ApiParam.REP_LINKUP);
        response.setMid(access.getMid());
        if (StringUtils.isBlank(access.getTimestamp())){
            response.setCode(Integer.parseInt(EnergyResponseEnum.PARAM_FAIL_TIMESTAMP.getCode()));
            response.setMsg(EnergyResponseEnum.PARAM_FAIL_TYPE.getMessage());
            return gson.toJson(response);
        }
        if (StringUtils.isBlank(access.getType())){
            response.setCode(Integer.parseInt(EnergyResponseEnum.PARAM_FAIL_TYPE.getCode()));
            response.setMsg(EnergyResponseEnum.PARAM_FAIL_TYPE.getMessage());
            return gson.toJson(response);
        } else if (!Objects.equals(access.getType(), ApiParam.CMD_LINKUP) && !Objects.equals(access.getType(), ApiParam.CMD_HEARTBEAT)){
            response.setCode(Integer.parseInt(EnergyResponseEnum.TYPE_ERROR.getCode()));
            response.setMsg(EnergyResponseEnum.TYPE_ERROR.getMessage());
            return gson.toJson(response);
        }
        //判断是否是心跳请求
        if (Objects.equals(access.getType(), ApiParam.CMD_HEARTBEAT)){
            //如果有异常的设备，则下线设备
            if (!Objects.isNull(access.getParam())){
                //下线之前记录信息
                LocalDateTime time = LocalDateTime.ofEpochSecond(Long.parseLong(access.getTimestamp()),0, ZoneOffset.of("+8"));
                List<EleInformation> informationList = new ArrayList<>();
                List<LogicAccess> list = logicAccessService.getLogicAccess(ndid,access.getParam().getDid());
                if (!CollectionUtils.isEmpty(list)){
                    list.forEach(item->{
                        EleInformation eleInformation = new EleInformation();
                        eleInformation.setUpdateTime(time);
                        eleInformation.setDid(item.getDid());
                        eleInformation.setType(ModelState.offline);
                        eleInformation.setDescription("装置下线");
                        informationList.add(eleInformation);
                    });
                    eleInformationService.addInformation(informationList);
                }
                //下线
                response.setCode(Integer.parseInt(EnergyResponseEnum.AUTO_OFFLINE.getCode()));
                logicAccessService.offlineByDid(access.getParam().getDid());
            } else {
                response.setCode(Integer.parseInt(EnergyResponseEnum.SUCCESS.getCode()));
                //判断库中是否存在都掉线的装置，都掉线还有心跳就重新上线 1.修改状态 2.记录日志
                List<LogicAccess> onList = logicAccessService.getAllOnlineDevice(ndid);
                List<LogicAccess> offList = logicAccessService.getAllOnlineDevice(ndid);
                if (CollectionUtils.isEmpty(onList) && !CollectionUtils.isEmpty(offList)){
                    List<EleInformation> eleInformationList = new ArrayList<>();
                    offList.forEach(item->{
                        item.setState(2);
                        logicAccessService.accessDev(item);
                        EleInformation eleInformation = new EleInformation();
                        eleInformation.setUpdateTime(LocalDateTime.ofEpochSecond(Long.parseLong(access.getTimestamp()),0, ZoneOffset.of("+8")));
                        eleInformation.setDid(item.getDid());
                        eleInformation.setType(ModelState.online);
                        eleInformation.setDescription("装置上线");
                        eleInformationList.add(eleInformation);
                    });
                    eleInformationService.addInformation(eleInformationList);
                }
            }
            response.setTimestamp(Long.toString(System.currentTimeMillis()/1000));
            response.setType(ApiParam.REP_HEARTBEAT);
            return gson.toJson(response);
        }
        //判断当前网关是否存在主题
        if (CollectionUtils.isEmpty(eleTopicService.list(ndid))){
            response.setCode(Integer.parseInt(EnergyResponseEnum.MISSING_TOPIC.getCode()));
            response.setMsg(EnergyResponseEnum.MISSING_TOPIC.getMessage());
            return gson.toJson(response);
        }
        //判断注册接入
        List<String> didList = access.getParam().getDid();
        for (String item:didList) {
            if (Objects.isNull(logicAccessService.getAccessDev(item))){
                response.setCode(Integer.parseInt(EnergyResponseEnum.NO_DID_FIND.getCode()));
                response.setMsg(EnergyResponseEnum.NO_DID_FIND.getMessage());
                return gson.toJson(response);
            }
        }
        List<TpListDTO> tpList = access.getParam().getTpList();
        tpList.forEach(item->{
            versionSet.add(item.getName() + "+" +item.getVersion() + "+" + item.getTime());
        });
        for (String item: versionSet) {
            QueryWrapper<DataMould> dataMouldQueryWrapper = new QueryWrapper<>();
            dataMouldQueryWrapper.eq("Name",item.split("\\+")[0]).eq("Version", item.split("\\+")[1]).eq("Time", item.split("\\+")[2]);
            DataMould dataMould = dataMouldMapper.selectOne(dataMouldQueryWrapper);
            if (Objects.isNull(dataMould)) {
                response.setCode(Integer.parseInt(EnergyResponseEnum.NO_MODEL_FIND.getCode()));
                response.setMsg(EnergyResponseEnum.NO_MODEL_FIND.getMessage());
                return gson.toJson(response);
            }
        }
        //将接入的装置添加模板装置id
        List<LogicDev> logicDevList = logicDeviceLineService.getLogicDev(didList);
        List<String> logicDevDidList = logicDevList.stream().map(LogicDev::getDid).collect(Collectors.toList());
        //匹配模板装置的id，如果没有匹配上就说明模板缺失，需要请求模板的数据;都能匹配上就赋予接入装置的模板装置id，将装置状态置为接入状态
        for (String s : didList) {
            if (!logicDevDidList.contains(s)){
                response.setCode(Integer.parseInt(EnergyResponseEnum.MISSING_MODEL.getCode()));
                response.setMsg(EnergyResponseEnum.MISSING_MODEL.getMessage());
                return gson.toJson(response);
            }
        }
        //修改网关的状态
        netDevService.onlineNetDev(ndid);
        //下线在线的装置
        List<String> offOnlineList = logicAccessService.getOnlineByList(didList).stream().map(LogicAccess::getDid).collect(Collectors.toList());
        //记录掉线库
        List<EleInformation> informationList = new ArrayList<>();
        offOnlineList.forEach(item->{
            EleInformation eleInformation = new EleInformation();
            eleInformation.setUpdateTime(LocalDateTime.ofEpochSecond(Long.parseLong(Long.toString(System.currentTimeMillis()/1000)),0, ZoneOffset.of("+8")));
            eleInformation.setDid(item);
            eleInformation.setType(ModelState.offline);
            eleInformation.setDescription("装置下线");
            informationList.add(eleInformation);
        });
        eleInformationService.addInformation(informationList);
        List<EleInformation> eleInformationList = new ArrayList<>();
        for (String s : didList) {
            LogicAccess logicAccess = logicAccessService.getAccessDev(s);
            logicAccess.setState(2);
            logicAccessService.accessDev(logicAccess);
            //记录上线时间
            EleInformation eleInformation = new EleInformation();
            eleInformation.setUpdateTime(LocalDateTime.ofEpochSecond(Long.parseLong(access.getTimestamp()),0, ZoneOffset.of("+8")));
            eleInformation.setDid(s);
            eleInformation.setType(ModelState.online);
            eleInformation.setDescription("装置上线");
            eleInformationList.add(eleInformation);
        }
        eleInformationService.addInformation(eleInformationList);
        response.setCode(Integer.parseInt(EnergyResponseEnum.SUCCESS.getCode()));
        response.setMsg(EnergyResponseEnum.SUCCESS.getMessage());
        return gson.toJson(response);
    }


    @Override
    @Transactional(rollbackFor = {Exception.class})
    public String deviceData(String json) {
        Gson gson = new Gson();
        AskDataDTO.AskDataResponse response = gson.fromJson(json,AskDataDTO.AskDataResponse.class);
        if (Objects.equals(response.getCode(),Integer.parseInt(EnergyResponseEnum.SUCCESS.getCode()))){
            /**
             * 解析联网(网关)模板
             */
            NetDevDTO netDevDTO = response.getParam().getDataArray().get(0).getTemplate().getNetDev();
            //获取联网设备信息
            QueryWrapper<NetDev> netDevQueryWrapper = new QueryWrapper<>();
            netDevQueryWrapper.eq("NDID",netDevDTO.getNDid()).eq("State",DataStateEnum.ENABLE.getCode());
            NetDev netDev = netDevMapper.selectOne(netDevQueryWrapper);
            if(Objects.isNull(netDev)){
                throw new BusinessException(EnergyResponseEnum.NET_DEV_MODEL_ERROR);
            }
            //根据网关的versionId判断，如果存在，更新的时候就先根据id删除版本表记录，重新生成一个，再给网关赋予这个id;如果不存在id，就直接生成一个，再赋予网关
            if (StringUtils.isNotBlank(netDev.getVersionId())){
                devVersionService.deleteDevVersion(netDev.getVersionId());
            }
            //新增系统版本表
            DevVersionParam devVersionParam = new DevVersionParam();
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            devVersionParam.setNdid(netDevDTO.getNDid());
            devVersionParam.setType(ModelState.NET_DEV);
            devVersionParam.setVersion(netDevDTO.getVersion());
            devVersionParam.setTime(LocalDateTime.parse(netDevDTO.getTime(),df));
            devVersionParam.setCreateTime(LocalDateTime.now());
            DevVersion netDevVersion = devVersionService.addDevVersion(devVersionParam);
            //更新网关设备表
            netDev.setVersionId(netDevVersion.getId());
            netDev.setNetType(netDevDTO.getNetType());
            netDev.setUid(netDevDTO.getUid());
            netDev.setComFlag(DataStateEnum.ENABLE.getCode());
            if (!CollectionUtils.isEmpty(netDevDTO.getCUid())){
                netDev.setCuid(netDevDTO.getCUid().stream().map(String::valueOf).collect(Collectors.joining(",")));
            }
            netDevMapper.updateById(netDev);
            //删除网关硬件表，重新录入
            List<String> netDevList = Stream.of(netDev.getId()).collect(Collectors.toList());
            hardwareService.deleteHardware(netDevList);
            HardwareParam hardwareParam = new HardwareParam();
            hardwareParam.setId(netDev.getId());
            BeanUtil.copyProperties(netDevDTO.getDevInfoDTO(),hardwareParam);
            BeanUtil.copyProperties(netDevDTO.getCpuInfoDTO(),hardwareParam);
            BeanUtil.copyProperties(netDevDTO.getMemInfoDTO(),hardwareParam);
            BeanUtil.copyProperties(netDevDTO.getDiskInfoDTO(),hardwareParam);
            BeanUtil.copyProperties(netDevDTO.getSoftInfoDTO(),hardwareParam);
            hardwareParam.setType(ModelState.NET_DEV);
            hardwareService.addHardware(hardwareParam);

            /**
             * 解析装置模板
             */
            List<DevDTO> devList = response.getParam().getDataArray().get(0).getTemplate().getDev();
            Map<String,String> map = analyzeDev(devList);
            /**
             * 解析逻辑模板
             */
            DevCfgDTO devCfgDTO = response.getParam().getDataArray().get(0).getTemplate().getDevCfg();
            //获取当前网关下的逻辑设备版本信息
            QueryWrapper<DevVersion> devVersionQueryWrapper = new QueryWrapper<>();
            devVersionQueryWrapper.eq("NDID",netDevDTO.getNDid()).eq("Type",ModelState.LOGIC_DEV).eq("State",DataStateEnum.ENABLE.getCode());
            DevVersion devCfgVersion = devVersionMapper.selectOne(devVersionQueryWrapper);
            //如果版本信息为空，直接写入；如果不为空，就先删除之前的数据，然后重新录入信息
            if (!Objects.isNull(devCfgVersion)){
                List<String> logicList = logicDeviceLineService.getLogicDevByVersionId(devCfgVersion.getId()).stream().map(LogicDev::getId).collect(Collectors.toList());
                //删除逻辑设备信息
                logicDeviceLineService.deleteByVersionId(devCfgVersion.getId());
                //删除逻辑设备版本信息
                devVersionService.deleteDevVersion(devCfgVersion.getId());
                //删除监测点信息
                lineService.deleteByList(logicList);
                //删除硬件信息
                hardwareService.deleteHardware(logicList);
            }
            DevVersionParam devCfgVersionParam = new DevVersionParam();
            BeanUtil.copyProperties(devCfgDTO,devCfgVersionParam);
            devCfgVersionParam.setType(ModelState.LOGIC_DEV);
            devCfgVersionParam.setCreateTime(LocalDateTime.now());
            devCfgVersionParam.setNdid(netDevDTO.getNDid());
            //逻辑设备入库->设备版本信息表
            DevVersion devVersion = devVersionService.addDevVersion(devCfgVersionParam);
            List<DeviceDTO> list = devCfgDTO.getCfg();
            if (!CollectionUtils.isEmpty(list)){
                list.forEach(item->{
                    //入库->逻辑设备表logic_dev
                    DevCfgParam devCfgParam = new DevCfgParam();
                    BeanUtil.copyProperties(item,devCfgParam);
                    devCfgParam.setPid(netDev.getId());
                    if (!Objects.isNull(logicDeviceLineService.getLogicDev(item.getId()))){
                        throw new BusinessException(EnergyResponseEnum.SAME_DEV_ERROR);
                    }
                    devCfgParam.setDid(item.getId());
                    devCfgParam.setVersionId(devVersion.getId());
                    if (Objects.isNull(map.get(item.getName() + item.getVersion() + item.getTime()))){
                        throw new BusinessException(EnergyResponseEnum.MODEL_ERROR);
                    }
                    devCfgParam.setIdx(map.get(item.getName() + item.getVersion() + item.getTime()));
                    devCfgParam.setName(item.getDevInfo().getDevName());
                    LogicDev logicDev = logicDeviceLineService.add(devCfgParam);
                    //逻辑设备入库->硬件信息表
                    HardwareParam hardware = new HardwareParam();
                    hardware.setId(logicDev.getId());
                    BeanUtil.copyProperties(netDevDTO.getDevInfoDTO(),hardware);
                    BeanUtil.copyProperties(netDevDTO.getCpuInfoDTO(),hardware);
                    BeanUtil.copyProperties(netDevDTO.getMemInfoDTO(),hardware);
                    BeanUtil.copyProperties(netDevDTO.getDiskInfoDTO(),hardware);
                    BeanUtil.copyProperties(netDevDTO.getSoftInfoDTO(),hardware);
                    hardware.setType(ModelState.LOGIC_DEV);
                    hardwareService.addHardware(hardware);
                    //入库->监测点信息表
                    if (!CollectionUtils.isEmpty(item.getLineInfo())){
                        List<LineDTO> line =  item.getLineInfo();
                        List<String> lineList = line.stream().map(LineDTO::getLineId).collect(Collectors.toList());
                        //查找库里数据
                        if (!CollectionUtils.isEmpty(lineService.getLineInfo(lineList))){
                            throw new BusinessException(EnergyResponseEnum.LINE_REPEAT_ERROR);
                        }
                        for (int i=0;i<line.size();i++){
                            LineParam lineParam = new LineParam();
                            lineParam.setPid(logicDev.getId());
                            BeanUtil.copyProperties(line.get(i),lineParam);
                            lineParam.setIdx(i);
                            lineService.add(lineParam);
                        }
                    }
                });
            }
        } else {
            System.out.println("获取数据失败");
        }
        AccessDTO.AccessResponse result = new AccessDTO.AccessResponse();
        result.setCode(Integer.parseInt(EnergyResponseEnum.SUCCESS.getCode()));
        return gson.toJson(result);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void subscribeTopic(String json, String ndid) {
        Gson gson = new Gson();
        TopicParamDTO topic = gson.fromJson(json, TopicParamDTO.class);
        if (!CollectionUtils.isEmpty(eleTopicService.list(ndid))){
            eleTopicService.delete(ndid);
        }
        List<String> list = topic.getParam().getTopic();
        list.forEach(item->{
            EleTopic eleTopic = new EleTopic();
            eleTopic.setNdid(ndid);
            eleTopic.setTopic(item);
            if (item.contains("/platform/devcmd")){
                eleTopic.setType(0);
            }
            else if(item.contains("/platform/devqcmd")){
                eleTopic.setType(0);
            }
            else if(item.contains("/platform/devack")){
                eleTopic.setType(1);
            }
            else if(item.contains("/platform/appcmd")){
                eleTopic.setType(2);
            }
            else if(item.contains("/platform/appack")){
                eleTopic.setType(1);
            }
            else if(item.contains("/app/devcmd")){
                eleTopic.setType(0);
            }
            else if(item.contains("/app/devack")){
                eleTopic.setType(2);
            }
            else if(item.contains("/app/pltcmd")){
                eleTopic.setType(1);
            }
            else if(item.contains("/app/pltack")){
                eleTopic.setType(2);
            }
            else if(item.contains("/device/pltrep")){
                eleTopic.setType(1);
            }
            else if(item.contains("/device/data")){
                eleTopic.setType(4);
            }
            else if(item.contains("/device/qdata")){
                eleTopic.setType(4);
            }
            else if(item.contains("/platform/devfileack")){
                eleTopic.setType(1);
            }
            else if(item.contains("/platform/devfilecmd")){
                eleTopic.setType(0);
            }
            else if(item.contains("/app/devfileack")){
                eleTopic.setType(2);
            }
            else if(item.contains("/app/devfilecmd")){
                eleTopic.setType(0);
            } else {
                eleTopic.setType(5);
            }
            eleTopicService.addTopic(eleTopic);
        });
        //发送装置接入和取消注册的主题
        EleTopic eleTopic = new EleTopic();
        eleTopic.setNdid(ndid);
        eleTopic.setTopic("/device/operate");
        eleTopic.setType(4);
        eleTopicService.addTopic(eleTopic);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public List<String> monitorHeartbeat(String ndid, String time) {
        List<EleInformation> list = new ArrayList<>();
        List<LogicAccess> onlineList = logicAccessService.getAllOnlineDevice(ndid);
        if (!CollectionUtils.isEmpty(onlineList)) {
            LocalDateTime offlineTime = LocalDateTime.ofEpochSecond(Long.parseLong(time), 0, ZoneOffset.of("+8"));
            onlineList.forEach(item -> {
                EleInformation eleInformation = new EleInformation();
                eleInformation.setUpdateTime(offlineTime);
                eleInformation.setDid(item.getDid());
                eleInformation.setType(ModelState.offline);
                eleInformation.setDescription("装置下线");
                list.add(eleInformation);
            });
            //记录所有下线装置信息
            eleInformationService.addInformation(list);
            //所有在线装置下线
            logicAccessService.offAllDevice(ndid);
            return list.stream().map(EleInformation::getDid).collect(Collectors.toList());
        }
        return null;
    }


    /**
     * 解析设备模板
     */
    public Map<String,String> analyzeDev(List<DevDTO> devList){
        Map<String,String> map = new HashMap<>();
        devList.forEach(item->{
            //先将数据类型入库
            addDataType(item);
            QueryWrapper<DataMould> dataMouldQueryWrapper = new QueryWrapper<>();
            dataMouldQueryWrapper.eq("Name",item.getName()).eq("Version",item.getVersion()).eq("Time",item.getTime()).eq("State",DataStateEnum.ENABLE.getCode());
            DataMould mould = dataMouldMapper.selectOne(dataMouldQueryWrapper);
            if (!Objects.isNull(mould)){
                //数据集集合
                List<String> dataSetList = dataSetService.findSetById(mould.getId()).stream().map(DataSet::getId).collect(Collectors.toList());
                //组集合
                List<String> dataGroupList = dataGroupService.findGroupById(dataSetList).stream().map(DataGroup::getId).collect(Collectors.toList());
                //删除组和详细数据关系
                groupArrayService.deleteGroupArray(dataGroupList);
                //删除组数据
                dataGroupService.deleteDataGroup(dataSetList);
                //删除详细数据
                dataArrayService.deleteDataArray(dataSetList);
                //删除数据集
                dataSetService.delete(mould.getId());
                //删除当前模板
                devModelService.deleteById(mould.getId());
            }
            //入库->ele_data_mould
            DataModelParam dataModelParam = new DataModelParam();
            BeanUtil.copyProperties(item,dataModelParam);
            dataModelParam.setCreateTime(LocalDateTime.now());
            DataMould dataMould = devModelService.addDataMould(dataModelParam);
            //更新装置的模板信息(id)
            if (!Objects.isNull(mould)){
                logicDeviceLineService.updateLogicDevice(mould.getId(),dataMould.getId());
            }
            String tmp = item.getName() + item.getVersion() + item.getTime();
            map.put(tmp,dataMould.getId());
            //入库->ele_data_set
            if (!CollectionUtils.isEmpty(item.getDataSet())){
                item.getDataSet().forEach(dataSetDTO -> {
                    DataSetParam dataSetParam = new DataSetParam();
                    BeanUtil.copyProperties(dataSetDTO,dataSetParam);
                    dataSetParam.setPid(dataMould.getId());
                    dataSetParam.setName(dataSetDTO.getName());
                    switch (dataSetDTO.getName()) {
                        case "Ds$Stat$MD":
                            dataSetParam.setAnotherName("测量数据");
                            break;
                        case "Ds$Stat$EPD":
                            dataSetParam.setAnotherName("电能量数据");
                            break;
                        case "Ds$Stat$STS":
                            dataSetParam.setAnotherName("状态量数据");
                            break;
                        case "Controller":
                            dataSetParam.setAnotherName("空调控制数据");
                            break;
                        case "Ds$Rt$MD":
                            dataSetParam.setAnotherName("实时测量数据");
                            break;
                        case "Ds$Rt$EPD":
                            dataSetParam.setAnotherName("实时电能量数据");
                            break;
                        default:
                            dataSetParam.setAnotherName(dataSetDTO.getName());
                            break;
                    }
                    DataSet dataSet = dataSetService.add(dataSetParam);
                    //入库->ele_data_array
                    if (!CollectionUtils.isEmpty(dataSetDTO.getDataArray())){
                        int sort = 0;
                        List<DataArrayDTO> list = dataSetDTO.getDataArray();
                        for (int i=0;i<list.size();i++){
                            DataGroupParam dataGroupParam = new DataGroupParam();
                            dataGroupParam.setPid(dataSet.getId());
                            DataArrayParam dataArrayParam = new DataArrayParam();
                            BeanUtil.copyProperties(list.get(i),dataArrayParam);
                            dataArrayParam.setPid(dataSet.getId());
                            dataArrayParam.setSort(list.get(i).getIdx());
                            switch (list.get(i).getType()) {
                                case DataType.EPD:
                                    EleEpdPqd epd = eleEpdPqdService.findByName(item.getEpd().get(list.get(i).getIdx()).getName(),item.getEpd().get(list.get(i).getIdx()).getPhase());
                                    dataArrayParam.setClassName("ele_epd_pqd");
                                    dataArrayParam.setDataId(epd.getId());
                                    if (StringUtils.isBlank(epd.getStatMethod())){
                                        if (!Objects.isNull(epd.getHarmStart()) && !Objects.isNull(epd.getHarmEnd())){
                                            for (int j=epd.getHarmStart(); j<=epd.getHarmEnd(); j++){
                                                BeanUtil.copyProperties(epd,dataArrayParam);
                                                dataArrayParam.setName(epd.getName() + j);
                                                dataArrayParam.setAnotherName(j + "次" + epd.getAnotherName());
                                                dataGroupParam.setName(j + "次" + epd.getAnotherName());
                                                dataArrayParam.setIdx(i);
                                                dataArrayParam.setStatMethod("avg");
                                                dataArrayParam.setSort(sort++);
                                                DataArray dataArray = dataArrayService.addDataArray(dataArrayParam);
                                                //入库->分组表
                                                dataGroupParam.setSort(i);
                                                dataGroupParam.setStatMethod("avg");
                                                dataGroupParam.setPhase(epd.getPhase());
                                                DataGroup dataGroup = dataGroupService.addDataGroup(dataGroupParam);
                                                //入库->group和dataArray关系
                                                groupArrayService.groupArrayRelation(dataGroup.getId(),dataArray.getId());
                                            }
                                        } else {
                                            BeanUtil.copyProperties(epd,dataArrayParam);
                                            dataGroupParam.setName(epd.getAnotherName());
                                            dataArrayParam.setIdx(i);
                                            dataArrayParam.setStatMethod("avg");
                                            dataArrayParam.setSort(sort++);
                                            DataArray dataArray = dataArrayService.addDataArray(dataArrayParam);
                                            //入库->分组表
                                            dataGroupParam.setSort(i);
                                            dataGroupParam.setStatMethod("avg");
                                            dataGroupParam.setPhase(epd.getPhase());
                                            DataGroup dataGroup = dataGroupService.addDataGroup(dataGroupParam);
                                            //入库->group和dataArray关系
                                            groupArrayService.groupArrayRelation(dataGroup.getId(),dataArray.getId());
                                        }
                                    } else {
                                        String[] type = StringUtils.split(epd.getStatMethod(), ",");
                                        for (String s : type) {
                                            if (!Objects.isNull(epd.getHarmStart()) && !Objects.isNull(epd.getHarmEnd())) {
                                                for (int j = epd.getHarmStart(); j <= epd.getHarmEnd(); j++) {
                                                    BeanUtil.copyProperties(epd, dataArrayParam);
                                                    dataArrayParam.setName(epd.getName() + j);
                                                    dataArrayParam.setAnotherName(j + "次" + epd.getAnotherName());
                                                    dataGroupParam.setName(j + "次" + epd.getAnotherName());
                                                    dataArrayParam.setIdx(i);
                                                    dataArrayParam.setStatMethod(s);
                                                    dataArrayParam.setSort(sort++);
                                                    DataArray dataArray = dataArrayService.addDataArray(dataArrayParam);
                                                    //入库->分组表
                                                    dataGroupParam.setSort(i);
                                                    dataGroupParam.setStatMethod(s);
                                                    dataGroupParam.setPhase(epd.getPhase());
                                                    DataGroup dataGroup = dataGroupService.addDataGroup(dataGroupParam);
                                                    //入库->group和dataArray关系
                                                    groupArrayService.groupArrayRelation(dataGroup.getId(), dataArray.getId());
                                                }
                                            } else {
                                                BeanUtil.copyProperties(epd, dataArrayParam);
                                                dataGroupParam.setName(epd.getAnotherName());
                                                dataArrayParam.setIdx(i);
                                                dataArrayParam.setStatMethod(s);
                                                dataArrayParam.setSort(sort++);
                                                DataArray dataArray = dataArrayService.addDataArray(dataArrayParam);
                                                //入库->分组表
                                                dataGroupParam.setSort(i);
                                                dataGroupParam.setStatMethod(s);
                                                dataGroupParam.setPhase(epd.getPhase());
                                                DataGroup dataGroup = dataGroupService.addDataGroup(dataGroupParam);
                                                //入库->group和dataArray关系
                                                groupArrayService.groupArrayRelation(dataGroup.getId(), dataArray.getId());
                                            }
                                        }
                                    }
                                    break;
                                case DataType.PQD:
                                    EleEpdPqd pqd = eleEpdPqdService.findByName(item.getPqd().get(list.get(i).getIdx()).getName(),item.getPqd().get(list.get(i).getIdx()).getPhase());
                                    dataArrayParam.setClassName("ele_epd_pqd");
                                    dataArrayParam.setDataId(pqd.getId());
                                    if (StringUtils.isBlank(pqd.getStatMethod())){
                                        if (!Objects.isNull(pqd.getHarmStart()) && !Objects.isNull(pqd.getHarmEnd())){
                                            for (int j=pqd.getHarmStart(); j<=pqd.getHarmEnd(); j++){
                                                BeanUtil.copyProperties(pqd,dataArrayParam);
                                                dataArrayParam.setName(pqd.getName() + j);
                                                dataArrayParam.setAnotherName(j + "次" + pqd.getAnotherName());
                                                dataGroupParam.setName(j + "次" + pqd.getAnotherName());
                                                dataArrayParam.setIdx(i);
                                                dataArrayParam.setStatMethod("avg");
                                                dataArrayParam.setSort(sort++);
                                                DataArray dataArray = dataArrayService.addDataArray(dataArrayParam);
                                                //入库->分组表
                                                dataGroupParam.setSort(i);
                                                dataGroupParam.setStatMethod("avg");
                                                dataGroupParam.setPhase(pqd.getPhase());
                                                DataGroup dataGroup = dataGroupService.addDataGroup(dataGroupParam);
                                                //入库->group和dataArray关系
                                                groupArrayService.groupArrayRelation(dataGroup.getId(),dataArray.getId());
                                            }
                                        } else {
                                            BeanUtil.copyProperties(pqd,dataArrayParam);
                                            dataGroupParam.setName(pqd.getAnotherName());
                                            dataArrayParam.setIdx(i);
                                            dataArrayParam.setStatMethod("avg");
                                            dataArrayParam.setSort(sort++);
                                            DataArray dataArray = dataArrayService.addDataArray(dataArrayParam);
                                            //入库->分组表
                                            dataGroupParam.setSort(i);
                                            dataGroupParam.setStatMethod("avg");
                                            dataGroupParam.setPhase(pqd.getPhase());
                                            DataGroup dataGroup = dataGroupService.addDataGroup(dataGroupParam);
                                            //入库->group和dataArray关系
                                            groupArrayService.groupArrayRelation(dataGroup.getId(),dataArray.getId());
                                        }
                                    } else {
                                        String[] type = StringUtils.split(pqd.getStatMethod(), ",");
                                        for (String s : type) {
                                            if (!Objects.isNull(pqd.getHarmStart()) && !Objects.isNull(pqd.getHarmEnd())) {
                                                for (int j = pqd.getHarmStart(); j <= pqd.getHarmEnd(); j++) {
                                                    BeanUtil.copyProperties(pqd, dataArrayParam);
                                                    dataArrayParam.setName(pqd.getName() + j);
                                                    dataArrayParam.setAnotherName(j + "次" + pqd.getAnotherName());
                                                    dataGroupParam.setName(j + "次" + pqd.getAnotherName());
                                                    dataArrayParam.setIdx(i);
                                                    dataArrayParam.setStatMethod(s);
                                                    dataArrayParam.setSort(sort++);
                                                    DataArray dataArray = dataArrayService.addDataArray(dataArrayParam);
                                                    //入库->分组表
                                                    dataGroupParam.setSort(i);
                                                    dataGroupParam.setStatMethod(s);
                                                    dataGroupParam.setPhase(pqd.getPhase());
                                                    DataGroup dataGroup = dataGroupService.addDataGroup(dataGroupParam);
                                                    //入库->group和dataArray关系
                                                    groupArrayService.groupArrayRelation(dataGroup.getId(), dataArray.getId());
                                                }
                                            } else {
                                                BeanUtil.copyProperties(pqd, dataArrayParam);
                                                dataGroupParam.setName(pqd.getAnotherName());
                                                dataArrayParam.setIdx(i);
                                                dataArrayParam.setStatMethod(s);
                                                dataArrayParam.setSort(sort++);
                                                DataArray dataArray = dataArrayService.addDataArray(dataArrayParam);
                                                //入库->分组表
                                                dataGroupParam.setSort(i);
                                                dataGroupParam.setStatMethod(s);
                                                dataGroupParam.setPhase(pqd.getPhase());
                                                DataGroup dataGroup = dataGroupService.addDataGroup(dataGroupParam);
                                                //入库->group和dataArray关系
                                                groupArrayService.groupArrayRelation(dataGroup.getId(), dataArray.getId());
                                            }
                                        }
                                    }
                                    break;
                                case DataType.MD:
                                    EleMd md = eleMdService.findByName(item.getMd().get(list.get(i).getIdx()).getName(),item.getMd().get(list.get(i).getIdx()).getPhase());
                                    if (StringUtils.isBlank(md.getStatMethod())){
                                        dataArrayParam.setClassName("ele_md");
                                        dataArrayParam.setDataId(md.getId());
                                        BeanUtil.copyProperties(md,dataArrayParam);
                                        dataArrayParam.setIdx(i);
                                        dataArrayParam.setStatMethod("avg");
                                        DataArray dataArray = dataArrayService.addDataArray(dataArrayParam);
                                        //入库->分组表
                                        dataGroupParam.setSort(i);
                                        dataGroupParam.setName(md.getAnotherName());
                                        DataGroup dataGroup = dataGroupService.addDataGroup(dataGroupParam);
                                        //入库->group和dataArray关系
                                        groupArrayService.groupArrayRelation(dataGroup.getId(),dataArray.getId());
                                    } else {
                                        String[] type = StringUtils.split(md.getStatMethod(), ",");
                                        for (String s : type) {
                                            dataArrayParam.setClassName("ele_md");
                                            dataArrayParam.setDataId(md.getId());
                                            BeanUtil.copyProperties(md, dataArrayParam);
                                            dataGroupParam.setName(md.getAnotherName());
                                            dataArrayParam.setIdx(i);
                                            dataArrayParam.setStatMethod(s);
                                            DataArray dataArray = dataArrayService.addDataArray(dataArrayParam);
                                            //入库->分组表
                                            dataGroupParam.setSort(i);
                                            DataGroup dataGroup = dataGroupService.addDataGroup(dataGroupParam);
                                            //入库->group和dataArray关系
                                            groupArrayService.groupArrayRelation(dataGroup.getId(), dataArray.getId());
                                        }
                                    }
                                    break;
                                case DataType.EVT:
                                    EleEvt evt = eleEvtService.findByName(item.getEvt().get(list.get(i).getIdx()).getName());
                                    dataArrayParam.setClassName("ele_evt");
                                    dataArrayParam.setDataId(evt.getId());
                                    dataArrayParam.setStatMethod("avg");
                                    dataArrayParam.setPhase("M");
                                    BeanUtil.copyProperties(evt,dataArrayParam);
                                    dataGroupParam.setName(evt.getAnotherName());
                                    break;
                                case DataType.ALM:
                                    EleALM alm = eleAlmService.findByName(item.getAlm().get(list.get(i).getIdx()).getName());
                                    dataArrayParam.setClassName("ele_alm");
                                    dataArrayParam.setDataId(alm.getId());
                                    dataArrayParam.setStatMethod("avg");
                                    dataArrayParam.setPhase("M");
                                    BeanUtil.copyProperties(alm,dataArrayParam);
                                    dataGroupParam.setName(alm.getAnotherName());
                                    break;
                                case DataType.STS:
                                    EleSts sts = eleStsService.findByName(item.getSts().get(list.get(i).getIdx()).getName());
                                    dataArrayParam.setClassName("ele_sts");
                                    dataArrayParam.setDataId(sts.getId());
                                    dataArrayParam.setStatMethod("avg");
                                    dataArrayParam.setPhase("M");
                                    dataArrayParam.setType("bool");
                                    BeanUtil.copyProperties(sts,dataArrayParam);
                                    dataGroupParam.setName(sts.getAnotherName());
                                    break;
                                case DataType.DI:
                                    EleDi di = eleDiService.findByName(item.getDi().get(list.get(i).getIdx()).getName());
                                    dataArrayParam.setClassName("ele_di");
                                    dataArrayParam.setDataId(di.getId());
                                    dataArrayParam.setStatMethod("avg");
                                    dataArrayParam.setPhase("M");
                                    dataArrayParam.setType("bool");
                                    BeanUtil.copyProperties(di,dataArrayParam);
                                    dataGroupParam.setName(di.getAnotherName());
                                    break;
                                case DataType.DO:
                                    EleDo eleDo = eleDoService.findByName(item.getDoDTO().get(list.get(i).getIdx()).getName());
                                    dataArrayParam.setClassName("ele_do");
                                    dataArrayParam.setDataId(eleDo.getId());
                                    dataArrayParam.setStatMethod("avg");
                                    dataArrayParam.setPhase("M");
                                    dataArrayParam.setType("bool");
                                    BeanUtil.copyProperties(eleDo,dataArrayParam);
                                    dataGroupParam.setName(eleDo.getAnotherName());
                                    break;
                                case DataType.PARM:
                                    EleParm parm = eleParmService.findByName(item.getParam().get(list.get(i).getIdx()).getName());
                                    dataArrayParam.setClassName("ele_parm");
                                    dataArrayParam.setDataId(parm.getId());
                                    dataArrayParam.setStatMethod("avg");
                                    dataArrayParam.setPhase("M");
                                    BeanUtil.copyProperties(parm,dataArrayParam);
                                    dataGroupParam.setName(parm.getAnotherName());
                                    break;
                                case DataType.CTRL:
                                    EleCtrl ctrl = eleCtrlService.findByName(item.getCtrl().get(list.get(i).getIdx()).getName());
                                    dataArrayParam.setClassName("ele_ctrl");
                                    dataArrayParam.setDataId(ctrl.getId());
                                    dataArrayParam.setStatMethod("avg");
                                    dataArrayParam.setPhase("M");
                                    BeanUtil.copyProperties(ctrl,dataArrayParam);
                                    dataGroupParam.setName(ctrl.getAnotherName());
                                    break;
                                case DataType.ACTRL:
                                    EleActrl actrl = eleActrlService.findByName(item.getACtrl().get(list.get(i).getIdx()).getName());
                                    dataArrayParam.setClassName("ele_actrl");
                                    dataArrayParam.setDataId(actrl.getId());
                                    dataArrayParam.setStatMethod("avg");
                                    dataArrayParam.setPhase("M");
                                    BeanUtil.copyProperties(actrl,dataArrayParam);
                                    dataGroupParam.setName(actrl.getAnotherName());
                                    break;
                                default:
                                    break;
                            }
                            if (!Objects.equals(list.get(i).getType(),DataType.EPD) && !Objects.equals(list.get(i).getType(),DataType.PQD) && !Objects.equals(list.get(i).getType(),DataType.MD)){
                                dataArrayParam.setIdx(i);
                                DataArray dataArray = dataArrayService.addDataArray(dataArrayParam);
                                //入库->分组表
                                dataGroupParam.setSort(i);
                                dataGroupParam.setStatMethod("avg");
                                dataGroupParam.setPhase("M");
                                DataGroup dataGroup = dataGroupService.addDataGroup(dataGroupParam);
                                //入库->group和dataArray关系
                                groupArrayService.groupArrayRelation(dataGroup.getId(),dataArray.getId());
                            }
                        }
                    }
                });
            }
        });
        return map;
    }


    /**
     * 新增字典模板数据
     */
    public void addDataType(DevDTO item){
        //epd、pqd字典数据录入
        List<EpdPqdDTO> epdList = item.getEpd();
        List<EpdPqdDTO> pqdList = item.getPqd();
        List<EpdPqdDTO> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(epdList) && CollectionUtils.isEmpty(pqdList)){
            list = epdList;
        } else if (CollectionUtils.isEmpty(epdList) && !CollectionUtils.isEmpty(pqdList)){
            list = pqdList;
        } else if (!CollectionUtils.isEmpty(epdList) && !CollectionUtils.isEmpty(pqdList)){
            list = Stream.of(epdList, pqdList).flatMap(Collection::stream).collect(Collectors.toList());
        }
        if (!CollectionUtils.isEmpty(list)){
            list.forEach(it->{
                if (Objects.isNull(it.getPhase())){
                    it.setPhase("M");
                }
                EleEpdPqd eleEpdPqd = eleEpdPqdService.findByName(it.getName(),it.getPhase());
                EleDict eleDict = eleDictService.findDictByName(it.getName());
                if (Objects.isNull(eleEpdPqd)){
                    EleEpdPqd epd = new EleEpdPqd();
                    BeanUtil.copyProperties(it,epd);
                    if (Objects.isNull(eleDict)){
                        epd.setAnotherName(it.getName());
                    } else {
                        epd.setAnotherName(eleDict.getAnotherName());
                    }
                    epd.setClassId(eleDictService.findTableName(it.getName()).getName());
                    if (!CollectionUtils.isEmpty(it.getStatMethod())){
                        epd.setStatMethod(it.getStatMethod().stream().map(String::valueOf).collect(Collectors.joining(",")));
                    }
                    eleEpdPqdService.addEpd(epd);
                } else {
                    BeanUtil.copyProperties(it,eleEpdPqd);
                    if (Objects.isNull(eleDict)){
                        eleEpdPqd.setAnotherName(it.getName());
                    } else {
                        eleEpdPqd.setAnotherName(eleDict.getAnotherName());
                    }
                    eleEpdPqd.setClassId(eleDictService.findTableName(it.getName()).getName());
                    if (!CollectionUtils.isEmpty(it.getStatMethod())){
                        eleEpdPqd.setStatMethod(it.getStatMethod().stream().map(String::valueOf).collect(Collectors.joining(",")));
                    }
                    eleEpdPqdService.updateEpd(eleEpdPqd);
                }
            });
        }
        //md字典数据录入
        List<MdDTO> mdList = item.getMd();
        if (!CollectionUtils.isEmpty(mdList)){
            mdList.forEach(it->{
                if (Objects.isNull(it.getPhase())){
                    it.setPhase("M");
                }
                EleMd eleMd = eleMdService.findByName(it.getName(),it.getPhase());
                EleDict eleDict = eleDictService.findDictByName(it.getName());
                if (Objects.isNull(eleMd)){
                    EleMd pojo = new EleMd();
                    BeanUtil.copyProperties(it,pojo);
                    if (Objects.isNull(eleDict)){
                        pojo.setAnotherName(it.getName());
                    } else {
                        pojo.setAnotherName(eleDict.getAnotherName());
                    }
                    pojo.setClassId(eleDictService.findTableName(it.getName()).getName());
                    if (!CollectionUtils.isEmpty(it.getStatMethod())){
                        pojo.setStatMethod(it.getStatMethod().stream().map(String::valueOf).collect(Collectors.joining(",")));
                    }
                    eleMdService.addMd(pojo);
                } else {
                    BeanUtil.copyProperties(it,eleMd);
                    if (Objects.isNull(eleDict)){
                        eleMd.setAnotherName(it.getName());
                    } else {
                        eleMd.setAnotherName(eleDict.getAnotherName());
                    }
                    eleMd.setClassId(eleDictService.findTableName(it.getName()).getName());
                    if (!CollectionUtils.isEmpty(it.getStatMethod())){
                        eleMd.setStatMethod(it.getStatMethod().stream().map(String::valueOf).collect(Collectors.joining(",")));
                    }
                    eleMdService.updateMd(eleMd);
                }
            });
        }
        //evt字典数据录入
        List<EvtDTO> evtList = item.getEvt();
        if (!CollectionUtils.isEmpty(evtList)){
            evtList.forEach(it->{
                EleEvt eleEvt = eleEvtService.findByName(it.getName());
                EleDict eleDict = eleDictService.findDictByName(it.getName());
                if (Objects.isNull(eleEvt)){
                    EleEvt pojo = new EleEvt();
                    BeanUtil.copyProperties(it,pojo);
                    if (Objects.isNull(eleDict)){
                        pojo.setAnotherName(it.getName());
                    } else {
                        pojo.setAnotherName(eleDict.getAnotherName());
                    }
                    EleEvt result = eleEvtService.addEvt(pojo);
                    addEvtParam(it.getParam(),result.getId());
                } else {
                    BeanUtil.copyProperties(it,eleEvt);
                    if (Objects.isNull(eleDict)){
                        eleEvt.setAnotherName(it.getName());
                    } else {
                        eleEvt.setAnotherName(eleDict.getAnotherName());
                    }
                    eleEvtService.updateEvt(eleEvt);
                    eleEvtParamService.deleteById(eleEvt.getId());
                    addEvtParam(it.getParam(),eleEvt.getId());
                }
            });
        }
        //alm字典数据录入
        List<AlmDTO> almList = item.getAlm();
        if (!CollectionUtils.isEmpty(almList)){
            almList.forEach(it->{
                EleALM eleAlM = eleAlmService.findByName(it.getName());
                EleDict eleDict = eleDictService.findDictByName(it.getName());
                if (Objects.isNull(eleAlM)){
                    EleALM pojo = new EleALM();
                    BeanUtil.copyProperties(it,pojo);
                    if (Objects.isNull(eleDict)){
                        pojo.setAnotherName(it.getName());
                    } else {
                        pojo.setAnotherName(eleDict.getAnotherName());
                    }
                    eleAlmService.addAlm(pojo);
                } else {
                    BeanUtil.copyProperties(it,eleAlM);
                    if (Objects.isNull(eleDict)){
                        eleAlM.setAnotherName(it.getName());
                    } else {
                        eleAlM.setAnotherName(eleDict.getAnotherName());
                    }
                    eleAlmService.updateAlm(eleAlM);
                }
            });
        }
        //sts字典数据录入
        List<StsDTO> stsList = item.getSts();
        if (!CollectionUtils.isEmpty(stsList)){
            stsList.forEach(it->{
                EleSts eleSts = eleStsService.findByName(it.getName());
                EleDict eleDict = eleDictService.findDictByName(it.getName());
                if (Objects.isNull(eleSts)){
                    EleSts pojo = new EleSts();
                    BeanUtil.copyProperties(it,pojo);
                    if (Objects.isNull(eleDict)){
                        pojo.setAnotherName(it.getName());
                    } else {
                        pojo.setAnotherName(eleDict.getAnotherName());
                    }
                    pojo.setClassId(eleDictService.findTableName(it.getName()).getName());
                    eleStsService.addSts(pojo);
                } else {
                    BeanUtil.copyProperties(it,eleSts);
                    if (Objects.isNull(eleDict)){
                        eleSts.setAnotherName(it.getName());
                    } else {
                        eleSts.setAnotherName(eleDict.getAnotherName());
                    }
                    eleSts.setClassId(eleDictService.findTableName(it.getName()).getName());
                    eleStsService.updateSts(eleSts);
                }
            });
        }
        //di字典数据录入
        List<DiDTO> diList = item.getDi();
        if (!CollectionUtils.isEmpty(diList)){
            diList.forEach(it->{
                EleDi eleDi = eleDiService.findByName(it.getName());
                EleDict eleDict = eleDictService.findDictByName(it.getName());
                if (Objects.isNull(eleDi)){
                    EleDi pojo = new EleDi();
                    BeanUtil.copyProperties(it,pojo);
                    if (Objects.isNull(eleDict)){
                        pojo.setAnotherName(it.getName());
                    } else {
                        pojo.setAnotherName(eleDict.getAnotherName());
                    }
                    eleDiService.addDi(pojo);
                } else {
                    BeanUtil.copyProperties(it,eleDi);
                    if (Objects.isNull(eleDict)){
                        eleDi.setAnotherName(it.getName());
                    } else {
                        eleDi.setAnotherName(eleDict.getAnotherName());
                    }
                    eleDiService.updateDi(eleDi);
                }
            });
        }
        //do字典数据录入
        List<DoDTO> doList = item.getDoDTO();
        if (!CollectionUtils.isEmpty(doList)){
            doList.forEach(it->{
                EleDo eleDo = eleDoService.findByName(it.getName());
                EleDict eleDict = eleDictService.findDictByName(it.getName());
                if (Objects.isNull(eleDo)){
                    EleDo pojo = new EleDo();
                    BeanUtil.copyProperties(it,pojo);
                    if (Objects.isNull(eleDict)){
                        pojo.setAnotherName(it.getName());
                    } else {
                        pojo.setAnotherName(eleDict.getAnotherName());
                    }
                    eleDoService.addDo(pojo);
                } else {
                    BeanUtil.copyProperties(it,eleDo);
                    if (Objects.isNull(eleDict)){
                        eleDo.setAnotherName(it.getName());
                    } else {
                        eleDo.setAnotherName(eleDict.getAnotherName());
                    }
                    eleDoService.updateDo(eleDo);
                }
            });
        }
        //parm字典数据录入
        List<ParamDTO> parmList = item.getParam();
        if (!CollectionUtils.isEmpty(parmList)){
            parmList.forEach(it->{
                EleParm eleParm = eleParmService.findByName(it.getName());
                EleDict eleDict = eleDictService.findDictByName(it.getName());
                if (Objects.isNull(eleParm)){
                    EleParm pojo = new EleParm();
                    BeanUtil.copyProperties(it,pojo);
                    if (Objects.isNull(eleDict)){
                        pojo.setAnotherName(it.getName());
                    } else {
                        pojo.setAnotherName(eleDict.getAnotherName());
                    }
                    if (!CollectionUtils.isEmpty(it.getSetValue())){
                        pojo.setSetValue(it.getSetValue().stream().map(String::valueOf).collect(Collectors.joining(",")));
                    }
                    eleParmService.addParm(pojo);
                } else {
                    BeanUtil.copyProperties(it,eleParm);
                    if (Objects.isNull(eleDict)){
                        eleParm.setAnotherName(it.getName());
                    } else {
                        eleParm.setAnotherName(eleDict.getAnotherName());
                    }
                    if (!CollectionUtils.isEmpty(it.getSetValue())){
                        eleParm.setSetValue(it.getSetValue().stream().map(String::valueOf).collect(Collectors.joining(",")));
                    }
                    eleParmService.updateParm(eleParm);
                }
            });
        }
        //ctrl字典数据录入
        List<CtrlDTO> ctrlList = item.getCtrl();
        if (!CollectionUtils.isEmpty(ctrlList)){
            ctrlList.forEach(it->{
                EleCtrl eleCtrl = eleCtrlService.findByName(it.getName());
                EleDict eleDict = eleDictService.findDictByName(it.getName());
                if (Objects.isNull(eleCtrl)){
                    EleCtrl pojo = new EleCtrl();
                    BeanUtil.copyProperties(it,pojo);
                    if (Objects.isNull(eleDict)){
                        pojo.setAnotherName(it.getName());
                    } else {
                        pojo.setAnotherName(eleDict.getAnotherName());
                    }
                    pojo.setClassId(eleDictService.findTableName(it.getName()).getName());
                    if (!CollectionUtils.isEmpty(it.getCtlValue())){
                        pojo.setCtlValue(it.getCtlValue().stream().map(String::valueOf).collect(Collectors.joining(",")));
                    }
                    eleCtrlService.addCtrl(pojo);
                } else {
                    BeanUtil.copyProperties(it,eleCtrl);
                    if (Objects.isNull(eleDict)){
                        eleCtrl.setAnotherName(it.getName());
                    } else {
                        eleCtrl.setAnotherName(eleDict.getAnotherName());
                    }
                    eleCtrl.setClassId(eleDictService.findTableName(it.getName()).getName());
                    if (!CollectionUtils.isEmpty(it.getCtlValue())){
                        eleCtrl.setCtlValue(it.getCtlValue().stream().map(String::valueOf).collect(Collectors.joining(",")));
                    }
                    eleCtrlService.updateCtrl(eleCtrl);
                }
            });
        }
        //actrl字典数据录入
        List<ACtrlDTO> aCtrlList = item.getACtrl();
        if (!CollectionUtils.isEmpty(aCtrlList)){
            aCtrlList.forEach(it->{
                EleActrl eleActrl = eleActrlService.findByName(it.getName());
                EleDict eleDict = eleDictService.findDictByName(it.getName());
                if (Objects.isNull(eleActrl)){
                    EleActrl pojo = new EleActrl();
                    BeanUtil.copyProperties(it,pojo);
                    if (Objects.isNull(eleDict)){
                        pojo.setAnotherName(it.getName());
                    } else {
                        pojo.setAnotherName(eleDict.getAnotherName());
                    }
                    if (!CollectionUtils.isEmpty(it.getCondition())){
                        pojo.setCondition(it.getCondition().stream().map(String::valueOf).collect(Collectors.joining(",")));
                    }
                    if (!CollectionUtils.isEmpty(it.getOutRes())){
                        pojo.setOutRes(it.getOutRes().stream().map(String::valueOf).collect(Collectors.joining(",")));
                    }
                    eleActrlService.addActrl(pojo);
                } else {
                    BeanUtil.copyProperties(it,eleActrl);
                    if (Objects.isNull(eleDict)){
                        eleActrl.setAnotherName(it.getName());
                    } else {
                        eleActrl.setAnotherName(eleDict.getAnotherName());
                    }
                    if (!CollectionUtils.isEmpty(it.getCondition())){
                        eleActrl.setCondition(it.getCondition().stream().map(String::valueOf).collect(Collectors.joining(",")));
                    }
                    if (!CollectionUtils.isEmpty(it.getOutRes())){
                        eleActrl.setOutRes(it.getOutRes().stream().map(String::valueOf).collect(Collectors.joining(",")));
                    }
                    eleActrlService.updateActrl(eleActrl);
                }
            });
        }
    }

    /**
     * 新增单个设备事件数据
     */
    public void addEvtParam( List<EvtParam> list,String id) {
        if (!CollectionUtils.isEmpty(list)){
            list.forEach(param->{
                EleEvtParm eleEvtParm = new EleEvtParm();
                BeanUtil.copyProperties(param,eleEvtParm);
                eleEvtParm.setPid(id);
                eleEvtParamService.addEleEvtParam(eleEvtParm);
            });
        }
    }

}
