package com.yfd.platform.component.nettyclient;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yfd.platform.component.WebSocketServer;
import com.yfd.platform.config.AlgorithmServerConfig;
import com.yfd.platform.config.HttpServerConfig;
import com.yfd.platform.config.ParentConfig;
import com.yfd.platform.constant.Constant;
import com.yfd.platform.constant.SystemCode;
import com.yfd.platform.modules.basedata.domain.AlgorithmManufacturerVersion;
import com.yfd.platform.modules.basedata.domain.AlgorithmModel;
import com.yfd.platform.modules.basedata.domain.Substation;
import com.yfd.platform.modules.basedata.domain.SubstationPatroldevice;
import com.yfd.platform.modules.basedata.service.*;
import com.yfd.platform.modules.patroltask.domain.ExaminePlan;
import com.yfd.platform.modules.patroltask.domain.Task;
import com.yfd.platform.modules.patroltask.domain.TaskTodo;
import com.yfd.platform.modules.patroltask.service.IExaminePlanService;
import com.yfd.platform.modules.patroltask.service.ITaskService;
import com.yfd.platform.modules.patroltask.service.ITaskTodoService;
import com.yfd.platform.modules.patroltask.service.impl.QuartzMultiTaskManage;
import com.yfd.platform.modules.robotapi.domain.PlatformParentSystem;
import com.yfd.platform.modules.robotapi.service.IPlatformParentSystemService;
import com.yfd.platform.modules.robotapi.service.IStationRobotService;
import com.yfd.platform.utils.FtpClient;
import com.yfd.platform.utils.HttpRESTfulUtils;
import com.yfd.platform.utils.SpringContextHolder;
import com.yfd.platform.utils.TLSFTPUtils;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * I/O数据读写处理类
 */
@ChannelHandler.Sharable
public class BootNettyChannelInboundHandlerAdapter extends ChannelInboundHandlerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(BootNettyChannelInboundHandlerAdapter.class);
    /**
     * 从服务端收到新的数据时，这个方法会在收到消息时被调用
     */
    // 获取spring bean
    IExaminePlanService examinePlanService = SpringContextHolder.getBean(IExaminePlanService.class);
    IStationRobotService stationRobotService = SpringContextHolder.getBean(IStationRobotService.class);
    ITaskTodoService taskTodoService = SpringContextHolder.getBean(ITaskTodoService.class);
    ITaskService taskService = SpringContextHolder.getBean(ITaskService.class);
    ISubstationService substationService = SpringContextHolder.getBean(ISubstationService.class);
    QuartzMultiTaskManage quartztaskManage = SpringContextHolder.getBean(QuartzMultiTaskManage.class);
    HttpServerConfig httpServerConfig = SpringContextHolder.getBean(HttpServerConfig.class);
    ParentConfig parentConfig = SpringContextHolder.getBean(ParentConfig.class);
    FtpClient ftpClient = SpringContextHolder.getBean(FtpClient.class);
    IAlgorithmModelService algorithmModelService = SpringContextHolder.getBean(IAlgorithmModelService.class);
    IAlgorithmManufacturerVersionService algorithmManufacturerVersionService =
            SpringContextHolder.getBean(IAlgorithmManufacturerVersionService.class);
    HeartBeatTask heartBeatTask = SpringContextHolder.getBean(HeartBeatTask.class);
    AlgorithmServerConfig algorithmServerConfig = SpringContextHolder.getBean(AlgorithmServerConfig.class);
    ISubstationPatroldeviceService substationPatroldeviceService =
            SpringContextHolder.getBean(ISubstationPatroldeviceService.class);
    IPlatformParentSystemService platformParentSystemService =
            SpringContextHolder.getBean(IPlatformParentSystemService.class);
    StringRedisTemplate redisTemplate = SpringContextHolder.getBean(StringRedisTemplate.class);
    TLSFTPUtils tlsftpUtils = SpringContextHolder.getBean(TLSFTPUtils.class);
    HttpRESTfulUtils httpRESTfulUtils = SpringContextHolder.getBean(HttpRESTfulUtils.class);
    EventManager eventManager = SpringContextHolder.getBean(EventManager.class);
    ISubstationDeviceService substationDeviceService =
            SpringContextHolder.getBean(ISubstationDeviceService.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg == null || Constant.SYSTEM_MESSAGE_SUCCESS.equals(msg.toString())) {
            return;
        }
        MyMessageProtocol receivedmsg = (MyMessageProtocol) msg;
        byte[] xmlcontent = receivedmsg.getXmlcontent();
        if (xmlcontent == null) {
            return;
        }
        String content = new String(xmlcontent);
        Map<String, Object> map = MyXmlUtil.xmlToMap(content);
        String Type = map.get("Type").toString();
        String Command = map.get("Command").toString();
        String Code = map.get("Code").toString();
        long receiverSerialNo = receivedmsg.getReceiverSerialNo();
        if (SystemCode.TYPE_SYSTEM_MESSAGE_CODE.getCode().equals(Type) && SystemCode.COMMAND_ITEM_RESPONSE_CODE.getCode().equals(Command)) {
            String xmlContent = redisTemplate.opsForValue().get(Constant.CLOUD_SEND_CODE + receiverSerialNo);
            //上级系统返回注册成功信息
            List<Map<String, String>> items = (List<Map<String, String>>) map.get("Items");
            String ReceiveCode = map.get("ReceiveCode").toString();
            logger.info("-------------ReceiveCode------------------" + ReceiveCode);
            if (StrUtil.isBlank(xmlContent)) {
                return;
            }
            logger.info(xmlContent);
            if (xmlContent.startsWith("\"") && xmlContent.endsWith("\"")) {
                xmlContent = xmlContent.substring(1, xmlContent.length() - 1);
            }
            xmlContent = xmlContent.replace("\\n", "").replace("\\", "");
            Map<String, Object> xmlMap = MyXmlUtil.xmlToMap(xmlContent);
            // 发送的指令
            String responseType = xmlMap.get("Type").toString();
            List<Map<String, String>> xmlItems = (List<Map<String, String>>) xmlMap.get("Items");

            if (SystemCode.TYPE_SYSTEM_MESSAGE_CODE.getCode().equals(responseType)) {
                // 上级心跳响应
                parentHeartbeatResponse(items, xmlMap, ReceiveCode, Code);
            }

            if (SystemCode.TYPE_ALGORITHM_PARAM_CODE.getCode().equals(responseType) && xmlItems.size() > 0) {
                // 获取当前该区域某站点的运行算法参数
                getRunAlgorithmParams(xmlItems, items);
                return;
            }
            if (SystemCode.TYPE_ALGORITHM_VERSION_CODE.getCode().equals(responseType)) {
                getAlgorithmVersion(items);
                return;
            }
            if (SystemCode.TYPE_ALGORITHM_UPDATE_CODE.getCode().equals(responseType) && true) {
                // 算法版本更新
                updateAlgorithmVersion(xmlItems, items);
                return;
            }
        } else if (SystemCode.TYPE_SYSTEM_MESSAGE_CODE.getCode().equals(Type) && SystemCode.COMMAND_RESPONSE_CODE.getCode().equals(Command)) {
            //上级系统返回心跳保成功
            logger.info("上级系统返回心跳保持成功!");
        } else if (SystemCode.TYPE_TASK_CONTROL_CODE.getCode().equals(Type)) {
            // 上级系统发起任务操作 1：启用 2：暂停 3：恢复 4：停止
            // 如果Command为1，Code为任务id,否则为任务执行id
            logger.info(content);
            taskControl(ctx, receivedmsg, map, Type, Command, Code);

        } else if (SystemCode.TYPE_TASK_ISSUED_CODE.getCode().equals(Type) && SystemCode.COMMAND_TASK_CONFIG_CODE.getCode().equals(Command)) {
            logger.info(content);
            // 上级发送任务
            loadTaskDistribution(ctx, receivedmsg, map, Type, Command, Code);
        } else if (SystemCode.TYPE_EXAMINE_ISSUED_CODE.getCode().equals(Type) && SystemCode.COMMAND_EXAMINE_CONFIG_CODE.getCode().equals(Command)) {
            // 上级发送检修区域
            examineAreaCommand(ctx, receivedmsg, map, Code);
        } else if (SystemCode.TYPE_MODEL_SYNC_CODE.getCode().equals(Type)) {
            //上级发送模型同步
            modelSyncCommand(ctx, msg, map, Command);
        } else if (SystemCode.TYPE_TASK_COUNT_CODE.getCode().equals(Type)) {
            logger.info("===========================" + content);
            // 巡视结果统计查询
            patrolResultCount(ctx, msg, map, Code, Command);
        } else if (SystemCode.TYPE_SOLIDITY_INDEX_CODE.getCode().equals(Type)) {
            //可靠性指标统计查询
            getSolidityIndex(ctx, msg, map, Code, Command);
        } else {
            // 其他上级控制方法
            otherControlMethod(ctx, receivedmsg, map, Type, Command, Code);
        }

        BootNettyClientChannel bootNettyClientChannel = BootNettyClientChannelCache.get(ctx.channel().id().toString());
        if (bootNettyClientChannel != null) {
            bootNettyClientChannel.setLast_data(msg.toString());
        }
    }

    /***********************************
    * 用途说明: 上级心跳响应
    * 参数说明 items 上级上级心跳参数
    * 参数说明 xmlMap 发送参数
    * 参数说明 ReceiveCode 接收编号
    * 参数说明 Code 编号
    * 返回值说明: void
    ***********************************/
    private void parentHeartbeatResponse(List<Map<String, String>> items, Map<String, Object> xmlMap,
                                         String ReceiveCode, String Code) {
        String responseCommand = ObjectUtil.isEmpty(xmlMap.get("Command")) ? "" :
                xmlMap.get("Command").toString();
        if ("1".equals(responseCommand)) {
            for (Map<String, String> item : items) {
                for (String key : item.keySet()) {
                    if ("heart_beat_interval".equals(key)) {
                        parentConfig.setHeartBeatInterval(item.get(key));
                    }
                    if ("patroldevice_run_interval".equals(key)) {
                        parentConfig.setPatroldeviceRunInterval(item.get(key));
                    }
                    if ("nest_run_interval".equals(key)) {
                        parentConfig.setNestRunInterval(item.get(key));
                    }
                    if ("weather_interval".equals(key)) {
                        parentConfig.setWeatherInterval(item.get(key));
                    }
                }
            }
            LambdaUpdateWrapper<PlatformParentSystem> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(PlatformParentSystem::getChildCode, ReceiveCode).set(PlatformParentSystem::getIsFlag, "1");
            platformParentSystemService.update(updateWrapper);
            LambdaQueryWrapper<PlatformParentSystem> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(PlatformParentSystem::getChildCode, ReceiveCode);
            List<PlatformParentSystem> list = platformParentSystemService.list(queryWrapper);
            if (list.size() > 0) {
                PlatformParentSystem platformParentSystem = list.get(0);
                int time = Integer.parseInt(parentConfig.getHeartBeatInterval());
                ParentConfig parentConfig = new ParentConfig();
                parentConfig.setParentId(platformParentSystem.getParentCode());
                parentConfig.setServerId(platformParentSystem.getChildCode());
                parentConfig.setTcpPort(platformParentSystem.getServerPort());
                parentConfig.setParentIp(platformParentSystem.getServerIp());
                logger.info("time" + time + "==============================ParentConfig========================" + parentConfig.toString());
                heartBeatTask.startCron("HeartBeatTask", new HeartBeatJob(parentConfig), time * 1000);
                logger.info("上级系统返回注册成功信息!" + Code);
            }
        }
    }

    /***********************************
     * 用途说明: 获取当前该区域某站点的运行算法参数
     * 参数说明 xmlItems 控制缓存
     * 参数说明 items 上级控制数据
     * 返回值说明: void
     ***********************************/
    private void getRunAlgorithmParams(List<Map<String, String>> xmlItems, List<Map<String, String>> items) {
        Map<String, String> responseMap = xmlItems.get(0);
        String type = responseMap.get("type");
        for (Map<String, String> item : items) {
            AlgorithmModel algorithmModel = BeanUtil.copyProperties(item, AlgorithmModel.class);
            algorithmModel.setLastmodifier("admin");
            algorithmModel.setAlgorithmmanufacturer(item.get("algorithm_manufacturer"));
            algorithmModel.setRunstate(item.get("run_state"));
            algorithmModel.setMidversionnum(NumberUtil.parseInt(item.get("mid_version_num")));
            algorithmModel.setLastmodifydate(LocalDateTime.now());
            algorithmModel.setModelType(type);
            LambdaQueryWrapper<AlgorithmModel> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AlgorithmModel::getStationId, algorithmModel.getStationId()).eq(AlgorithmModel::getModelType, algorithmModel.getModelType());
            int count = algorithmModelService.count(queryWrapper);
            String dateStr = DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");
            algorithmModel.setModelCode(dateStr);
            algorithmModel.setModelName(dateStr);
            if (count > 0) {
                LambdaUpdateWrapper<AlgorithmModel> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(AlgorithmModel::getStationId, algorithmModel.getStationId()).eq(AlgorithmModel::getModelType, algorithmModel.getModelType());
                algorithmModelService.update(algorithmModel, updateWrapper);
            } else {
                algorithmModel.setIsnew("1");
                algorithmModelService.save(algorithmModel);
            }
        }
    }

    /***********************************
     * 用途说明: 算法版本获取
     * 参数说明 xmlItems 控制缓存
     * 参数说明 items 上级控制数据
     * 返回值说明: void
     ***********************************/
    private void getAlgorithmVersion(List<Map<String, String>> items) {
        for (Map<String, String> item : items) {
            AlgorithmManufacturerVersion algorithmModel = BeanUtil.copyProperties(item,
                    AlgorithmManufacturerVersion.class);
            LambdaQueryWrapper<AlgorithmManufacturerVersion> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AlgorithmManufacturerVersion::getAlgorithmManufacturer,
                    algorithmModel.getAlgorithmManufacturer()).eq(AlgorithmManufacturerVersion::getVersion,
                    algorithmModel.getVersion());
            int count = algorithmManufacturerVersionService.count(queryWrapper);
            if (count <= 0) {
                algorithmManufacturerVersionService.save(algorithmModel);
            }

        }
    }

    /***********************************
     * 用途说明: 算法版本更新
     * 参数说明 xmlItems 控制缓存
     * 参数说明 items 上级控制数据
     * 返回值说明: void
     ***********************************/
    private void updateAlgorithmVersion(List<Map<String, String>> xmlItems, List<Map<String, String>> items) {
        Map<String, String> responseMap = xmlItems.get(0);
        String type = responseMap.get("type");
        for (Map<String, String> item : items) {
            AlgorithmModel algorithmModel = BeanUtil.copyProperties(item, AlgorithmModel.class);
            algorithmModel.setStationId(responseMap.get("station_id"));
            algorithmModel.setSectionId(responseMap.get("section_id"));
            algorithmModel.setModelType(type);
            String algorithm_path = item.get("algorithm_path");
            String path = StrUtil.subAfter(algorithm_path, "/", true);
            algorithmModel.setModelFile(path);
            logger.info("=======item========" + item.toString());
            LambdaQueryWrapper<AlgorithmModel> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AlgorithmModel::getStationId, algorithmModel.getStationId()).eq(AlgorithmModel::getModelType, algorithmModel.getModelType());
            List<AlgorithmModel> list = algorithmModelService.list(queryWrapper);
            List<PlatformParentSystem> list1 =
                    platformParentSystemService.list(new LambdaQueryWrapper<PlatformParentSystem>().eq(PlatformParentSystem::getIsEnable, "1"));
            if (list.size() > 0 && list1.size() > 0) {
                LambdaUpdateWrapper<AlgorithmModel> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(AlgorithmModel::getStationId, algorithmModel.getStationId()).eq(AlgorithmModel::getModelType, algorithmModel.getModelType());
                AlgorithmModel algorithmModel1 = list.get(0);
                PlatformParentSystem platformParentSystem = list1.get(0);
                new Thread(() -> {
                    try {
                        if (tlsftpUtils.isConnected()) {
                            tlsftpUtils.disconnect();
                        }
                        tlsftpUtils.connect(platformParentSystem.getFtpIp()
                                , platformParentSystem.getFtpUser(),
                                platformParentSystem.getFtpPassword(),
                                NumberUtil.parseInt(platformParentSystem.getFtpPort()));
                        logger.info("==============algorithmModel.getModelFile==============" + algorithmModel
                                .getModelFile());
                        tlsftpUtils.download(httpServerConfig.getModelPath
                                (), algorithmModel.getModelFile());
                        tlsftpUtils.disconnect();
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.putOnce("requestHostIp", httpServerConfig.getPatrolIp());
                        jsonObject.putOnce("requestHostPort", httpServerConfig.getPatrolPort());
                        jsonObject.putOnce("requestId", algorithmModel1.getId());
                        jsonObject.putOnce("type", type);
                        String ftpUrl =
                                "ftp://" + algorithmServerConfig.getFtpUsername() + ":" + algorithmServerConfig.getFtpPassword() + "@" + algorithmServerConfig.getServerIp() + ":" + algorithmServerConfig.getFtpPort() + "/" + algorithmModel.getModelFile();
                        jsonObject.putOnce("algorithmPath", ftpUrl);
                        logger.info(jsonObject.toString());
                        com.alibaba.fastjson.JSONObject jsonObject1 = httpRESTfulUtils.sendHttpPost("json",
                                httpServerConfig.getAnalyseIp(), httpServerConfig.getAnalysePort13(), "",
                                "algorithmUpdate", jsonObject, null);
                        if (SystemCode.SUCCESS_STATUS_CODE.getCode().equals(jsonObject1.getString("code"))) {
                            algorithmModelService.update(algorithmModel, updateWrapper);
                        }
                    } catch (Exception e) {
                        tlsftpUtils.disconnect();
                        logger.error(e.getMessage());
                        throw new RuntimeException("更新算法报错", e);
                    }
                }).start();

            }
        }
    }

    /***********************************
     * 用途说明: 任务控制
     * 参数说明 ctx 上级通道处理程序
     * 参数说明 receivedmsg 上级发送数据对象
     * 参数说明 map 提取后的上级参数
     * 参数说明 Type 上级控制类型
     * 参数说明 Command 上级控制命令
     * 参数说明 Code 编号
     * 返回值说明: void
     ***********************************/
    private void taskControl(ChannelHandlerContext ctx, MyMessageProtocol receivedmsg,
                             Map<String, Object> map, String Type, String Command, String Code) throws InterruptedException {
        JSONArray taskArray = new JSONArray();
        if (SystemCode.COMMAND_TASK_START_CODE.getCode().equals(Command)) {
            runNow(Code, Type, Command, ctx, receivedmsg);
        }

        if (SystemCode.COMMAND_TASK_PAUSE_CODE.getCode().equals(Command)) {
            // 暂停任务
            pauseTask(Code, Type, Command, ctx, receivedmsg);
        }

        if (SystemCode.COMMAND_TASK_RESUME_CODE.getCode().equals(Command)) {
            // 恢复任务
            resumeTask(Code, Type, Command, ctx, receivedmsg);
        }

        if (SystemCode.COMMAND_TASK_STOP_CODE.getCode().equals(Command)) {
            // 停止任务
            stopTask(Code, Type, Command, ctx, receivedmsg);
        }

    }

    /***********************************
     * 用途说明: 任务下发
     * 参数说明 ctx 上级通道处理程序
     * 参数说明 receivedmsg 上级发送数据对象
     * 参数说明 map 提取后的上级参数
     * 参数说明 Type 上级控制类型
     * 参数说明 Command 上级控制命令
     * 参数说明 Code 编号
     * 返回值说明: void
     ***********************************/
    private void loadTaskDistribution(ChannelHandlerContext ctx, MyMessageProtocol receivedmsg,
                                      Map<String, Object> map, String Type, String Command, String Code) throws ParseException {
        // 上级发送任务
        List<Map<String, String>> items = (List<Map<String, String>>) map.get("Items");
        String robotCode = "";
        for (Map<String, String> item : items) {
            Task task = BeanUtil.toBean(item, Task.class);
            Substation substation =
                    substationService.getOne(new LambdaQueryWrapper<Substation>().eq(Substation::getStationCode,
                            Code));
            task.setDatastatus("2");
            task.setTaskId(IdUtil.fastSimpleUUID());
            robotCode = task.getRobotCode();
            task.setStationCode(Code);
            String fixedStartTime = task.getFixedStartTime();
            if (StrUtil.isNotBlank(fixedStartTime)) {
                task.setTaskTodoType("2");
            }
            task.setTaskType("1");
            task.setStationName(substation.getStationName());
            task.setLastmodifier("上级系统");
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            task.setLastmodifydate(timestamp);
            task.setCreateTime(new SimpleDateFormat("yyy-MM-dd HH:mm:ss").format(timestamp));
            taskService.save(task);
            if (StrUtil.isBlank(robotCode)) {
                //摄像头命令
                String taskTodoType = task.getTaskTodoType();
                if ("1".equals(taskTodoType)) {
                    //立即执行
                    TaskTodo taskTodo = taskService.createRunNowTask(task);
                    //立即执行当前任务
                    quartztaskManage.addJob(taskTodo);
                } else {//定期或者周期执行
                    taskService.createTodoTaskList(task);
                }
            }
        }
        if (StrUtil.isNotBlank(robotCode)) {
            List<SubstationPatroldevice> list =
                    substationPatroldeviceService.list(new LambdaQueryWrapper<SubstationPatroldevice>().eq(SubstationPatroldevice::getPatroldeviceCode, robotCode));
            if (list.size() > 0) {
                SubstationPatroldevice substationPatroldevice = list.get(0);
                // 发送任务到机器人
                JSONArray jsonArray = JSONUtil.parseArray(items);
                stationRobotService.sendCommand(substationPatroldevice.getInternationalId(),
                        httpServerConfig.getPatrolServerid(), substationPatroldevice.getInternationalId(), Type, Command,
                        Code, jsonArray.toString());
            }
        }

        // 响应给上级系统
        String reponsexml = MyXmlUtil.getXml(map.get("ReceiveCode").toString(), map.get("SendCode").toString(),
                SystemCode.TYPE_SYSTEM_MESSAGE_CODE.getCode(), SystemCode.COMMAND_RESPONSE_CODE.getCode(),
                SystemCode.SUCCESS_STATUS_CODE.getCode(), null);
        sendResponseData(ctx, receivedmsg, reponsexml);
    }

    /***********************************
     * 用途说明: 上级发送检修区域
     * 参数说明 ctx 上级通道处理程序
     * 参数说明 receivedmsg 上级发送数据对象
     * 参数说明 map 提取后的上级参数
     * 参数说明 Code 编号
     * 返回值说明: void
     ***********************************/
    private void examineAreaCommand(ChannelHandlerContext ctx, MyMessageProtocol receivedmsg, Map<String, Object> map
            , String Code) {
        List<Map<String, String>> items = (List<Map<String, String>>) map.get("Items");
        for (Map<String, String> item : items) {
            LambdaQueryWrapper<Substation> queryWrapper = new LambdaQueryWrapper<>();
            // Code为变电站Code
            queryWrapper.eq(Substation::getStationCode, Code);
            Substation substation = substationService.getOne(queryWrapper);
            ExaminePlan examinePlan = BeanUtil.toBean(item, ExaminePlan.class);
            examinePlan.setStationId(substation.getStationId());
            examinePlan.setStationCode(substation.getStationCode());
            examinePlan.setStationName(substation.getStationName());
            examinePlan.setConfigName("检修" + examinePlan.getConfigCode());
            examinePlan.setDatastatus("1");
            examinePlan.setLastmodifier("上级系统");
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            examinePlan.setLastmodifydate(timestamp);
            examinePlan.setCreator("上级系统");
            examinePlan.setCreateTime(new SimpleDateFormat("yyy-MM-dd HH:mm:ss").format(timestamp));
            examinePlanService.save(examinePlan);
        }
        // 响应给上级系统
        String reponsexml = MyXmlUtil.getXml(map.get("ReceiveCode").toString(), map.get("SendCode").toString(),
                SystemCode.TYPE_SYSTEM_MESSAGE_CODE.getCode(), SystemCode.COMMAND_RESPONSE_CODE.getCode(),
                SystemCode.SUCCESS_STATUS_CODE.getCode(), null);
        sendResponseData(ctx, receivedmsg, reponsexml);
    }

    /***********************************
     * 用途说明: 上级发送模型同步
     * 参数说明 ctx 上级通道处理程序
     * 参数说明 msg 上级发送数据对象
     * 参数说明 map 提取后的上级参数
     * 参数说明 Command 控制编码
     * 返回值说明: void
     ***********************************/
    private void modelSyncCommand(ChannelHandlerContext ctx, Object msg, Map<String, Object> map, String Command) throws Exception {
        String filePath = "";
        JSONObject taskData = new JSONObject();
        // 上级发送检修区域
        filePath = stationRobotService.reportParentById("", Command);
        String filepath = filePath;
        String path = "/home/ftpsuser/" + StrUtil.subBefore(filepath, "/", true);
        if (SystemCode.COMMAND_MODEL_HOST_CODE.getCode().equals(Command)) {
            logger.info("上级系统向区域巡视主机发起同步模型请求!<{}>", "巡视主机模型");
            taskData.putOpt(SystemCode.COMMAND_HOST_FILE_PATH.getCode(), filepath);
        } else if (SystemCode.COMMAND_MODEL_ROBOT_CODE.getCode().equals(Command)) {
            logger.info("上级系统向区域巡视主机发起同步模型请求!<{}>", "机器人模型");
            taskData.putOpt(SystemCode.COMMAND_ROBOT_FILE_PATH.getCode(), filepath);
        } else if (SystemCode.COMMAND_MODEL_CAMERA_CODE.getCode().equals(Command)) {
            logger.info("上级系统向区域巡视主机发起同步模型请求!<{}>", "摄像机模型");
            taskData.putOpt(SystemCode.COMMAND_VIDEO_FILE_PATH.getCode(), filepath);
        } else if (SystemCode.COMMAND_MODEL_DEVICE_CODE.getCode().equals(Command)) {
            logger.info("上级系统向区域巡视主机发起同步模型请求!<{}>", "点位模型");
            taskData.putOpt(SystemCode.COMMAND_DEVICE_FILE_PATH.getCode(), filepath);
        } else if (SystemCode.COMMAND_MODEL_DRONE_CODE.getCode().equals(Command)) {
            logger.info("上级系统向区域巡视主机发起同步模型请求!<{}>", "无人机模型");
            taskData.putOpt(SystemCode.COMMAND_DRONE_FILE_PATH.getCode(), filepath);
        } else if (SystemCode.COMMAND_MODEL_VOICE_CODE.getCode().equals(Command)) {
            logger.info("上级系统向区域巡视主机发起同步模型请求!<{}>", "声纹模型");
            taskData.putOpt(SystemCode.COMMAND_VOICE_FILE_PATH.getCode(), filepath);
        } else if (SystemCode.COMMAND_MODEL_TASK_CODE.getCode().equals(Command)) {
            logger.info("上级系统向区域巡视主机发起同步模型请求!<{}>", "任务文件");
            taskData.putOpt(SystemCode.COMMAND_TASK_FILE_PATH.getCode(), filepath);
        } else if (SystemCode.COMMAND_MODEL_EXAMINE_CODE.getCode().equals(Command)) {
            logger.info("上级系统向区域巡视主机发起同步模型请求!<{}>", "检修区域配置文件");
            taskData.putOpt("overhaularea_file_path", filepath);
        } else if (SystemCode.COMMAND_MODEL_MAP_CODE.getCode().equals(Command)) {
            logger.info("上级系统向区域巡视主机发起同步模型请求!<{}>", "地图文件");
            taskData.putOpt(SystemCode.COMMAND_MAP_FILE_PATH.getCode(), filepath);
        }
        List<PlatformParentSystem> list =
                platformParentSystemService.list(new LambdaQueryWrapper<PlatformParentSystem>().eq(PlatformParentSystem::getIsEnable, "1"));
        if (list.size() > 0) {
            PlatformParentSystem platformParentSystem = list.get(0);
            if (tlsftpUtils.isConnected()) {
                tlsftpUtils.disconnect();
            }
            tlsftpUtils.connect(platformParentSystem.getFtpIp(), platformParentSystem.getFtpUser(),
                    platformParentSystem.getFtpPassword(), NumberUtil.parseInt(platformParentSystem.getFtpPort()));
            logger.info("====platformParentSystem===" + platformParentSystem.toString());
            //                String path =
            tlsftpUtils.upload(path, new File(httpServerConfig.getModelPath() + filePath));
            tlsftpUtils.disconnect();
        }
        logger.info("==================taskData====================" + taskData.toString());
        this.responseMessage(ctx, map, msg, SystemCode.TYPE_SYSTEM_MESSAGE_CODE.getCode(),
                SystemCode.COMMAND_ITEM_RESPONSE_CODE.getCode(), taskData.toString());
    }

    /***********************************
     * 用途说明: 巡视结果统计查询
     * 参数说明 ctx 上级通道处理程序
     * 参数说明 msg 上级发送数据对象
     * 参数说明 map 提取后的上级参数
     * 参数说明 Code 编号
     * 参数说明 Command 控制编码
     * 返回值说明: void
     ***********************************/
    private void patrolResultCount(ChannelHandlerContext ctx, Object msg, Map<String, Object> map, String Code,
                                   String Command) {
        List<Map<String, String>> items = (List<Map<String, String>>) map.get("Items");
        for (Map<String, String> jsonObject : items) {
            String beginTime = jsonObject.get(SystemCode.ITEM_BEGIN_TIME.getCode());
            String endTime = jsonObject.get(SystemCode.ITEM_END_TIME.getCode());
            List<Map<String, Object>> taskDataStat = taskTodoService.getTaskDataStat(Code, "1", beginTime, endTime);
            long count1 = 0;
            long sum1 = 0;
            JSONObject jsonObject1 = new JSONObject();
            if (SystemCode.COMMAND_CLOSE_LOOP_CODE.getCode().equals(Command)) {
                for (Map<String, Object> stringObjectMap : taskDataStat) {
                    if (ObjectUtil.isNotEmpty(stringObjectMap.get("count2"))) {
                        count1 += Integer.parseInt(stringObjectMap.get("count2").toString());
                    }
                    if (ObjectUtil.isNotEmpty(stringObjectMap.get("sum2"))) {
                        sum1 += Integer.parseInt(stringObjectMap.get("sum2").toString());
                    }
                }
            } else if (SystemCode.COMMAND_ALARM_COMPLETE_CODE.getCode().equals(Command)) {
                for (Map<String, Object> stringObjectMap : taskDataStat) {
                    if (ObjectUtil.isNotEmpty(stringObjectMap.get("count5"))) {
                        count1 += Integer.parseInt(stringObjectMap.get("count5").toString());
                    }
                    if (ObjectUtil.isNotEmpty(stringObjectMap.get("sum5"))) {
                        sum1 += Integer.parseInt(stringObjectMap.get("sum5").toString());
                    }
                }
            } else if (SystemCode.COMMAND_ALARM_ACCURATE_CODE.getCode().equals(Command)) {
                for (Map<String, Object> stringObjectMap : taskDataStat) {
                    if (ObjectUtil.isNotEmpty(stringObjectMap.get("count3"))) {
                        count1 += Integer.parseInt(stringObjectMap.get("count3").toString());
                    }
                    if (ObjectUtil.isNotEmpty(stringObjectMap.get("sum3"))) {
                        sum1 += Integer.parseInt(stringObjectMap.get("sum3").toString());
                    }
                }
            } else if (SystemCode.COMMAND_PERSON_EXAMINE_CODE.getCode().equals(Command)) {
                for (Map<String, Object> stringObjectMap : taskDataStat) {
                    if (ObjectUtil.isNotEmpty(stringObjectMap.get("count4"))) {
                        count1 += Integer.parseInt(stringObjectMap.get("count4").toString());
                    }
                    if (ObjectUtil.isNotEmpty(stringObjectMap.get("sum4"))) {
                        sum1 += Integer.parseInt(stringObjectMap.get("sum4").toString());
                    }
                }
            } else if (SystemCode.COMMAND_MISS_CHECK_CODE.getCode().equals(Command)) {
                for (Map<String, Object> stringObjectMap : taskDataStat) {
                    if (ObjectUtil.isNotEmpty(stringObjectMap.get("count1"))) {
                        count1 += Integer.parseInt(stringObjectMap.get("count1").toString());
                    }
                    if (ObjectUtil.isNotEmpty(stringObjectMap.get("sum1"))) {
                        sum1 += Integer.parseInt(stringObjectMap.get("sum1").toString());
                    }
                }

            }
            jsonObject1.putOnce(SystemCode.ITEM_TOTAL_NUM.getCode(), sum1);
            jsonObject1.putOnce(SystemCode.ITEM_VALID_NUM.getCode(), count1);
            String num;
            if (sum1 == 0) {
                num = "0";
            } else {
                num = String.format("%.3f", ((float) sum1 * 100 / count1));
            }
            jsonObject1.putOnce(SystemCode.ITEM_PERCENT.getCode(), num);
            logger.info("============responseMessage===============" + jsonObject1.toString());
            this.responseMessage(ctx, map, msg, SystemCode.TYPE_SYSTEM_MESSAGE_CODE.getCode(),
                    SystemCode.COMMAND_ITEM_RESPONSE_CODE.getCode(), jsonObject1.toString());
        }
    }

    /***********************************
     * 用途说明: 可靠性指标统计查询
     * 参数说明 ctx 上级通道处理程序
     * 参数说明 msg 上级发送数据对象
     * 参数说明 map 提取后的上级参数
     * 参数说明 Code 编号
     * 参数说明 Command 控制编码
     * 返回值说明: void
     ***********************************/
    private void getSolidityIndex(ChannelHandlerContext ctx, Object msg, Map<String, Object> map, String Code,
                                  String Command) {
        List<Map<String, String>> items = (List<Map<String, String>>) map.get("Items");
        for (Map<String, String> jsonObject : items) {
            String beginTime = jsonObject.get(SystemCode.ITEM_BEGIN_TIME.getCode());
            String endTime = jsonObject.get(SystemCode.ITEM_END_TIME.getCode());
            List<Map<String, Object>> taskDataStat = taskTodoService.getTaskDataStat(Code, "1", beginTime, endTime);
            long count1 = 0;
            long sum1 = 0;
            JSONObject jsonObject1 = new JSONObject();
            if (SystemCode.COMMAND_ALARM_EXACT_CODE.getCode().equals(Command)) {
                // 巡视告警准确率
                for (Map<String, Object> stringObjectMap : taskDataStat) {
                    if (ObjectUtil.isNotEmpty(stringObjectMap.get("count3"))) {
                        count1 += Integer.parseInt(stringObjectMap.get("count3").toString());
                    }
                    if (ObjectUtil.isNotEmpty(stringObjectMap.get("sum3"))) {
                        sum1 += Integer.parseInt(stringObjectMap.get("sum3").toString());
                    }
                }
            } else if (SystemCode.COMMAND_ALGORITHM_EXACT_CODE.getCode().equals(Command)) {
                // 算法标签对应准确率
                jsonObject1.putOpt("tag_type", "sly_bjbmyw");
            }
            jsonObject1.putOnce(SystemCode.ITEM_TOTAL_NUM.getCode(), sum1);
            jsonObject1.putOnce(SystemCode.ITEM_VALID_NUM.getCode(), count1);
            String num;
            if (sum1 == 0) {
                num = "0";
            } else {
                num = String.format("%.3f", ((float) sum1 * 100 / count1));
            }
            jsonObject1.putOnce(SystemCode.ITEM_PERCENT.getCode(), num);
            this.responseMessage(ctx, map, msg, SystemCode.TYPE_SYSTEM_MESSAGE_CODE.getCode(),
                    SystemCode.COMMAND_ITEM_RESPONSE_CODE.getCode(), jsonObject1.toString());
        }
    }

    /***********************************
     * 用途说明: 其他上级控制指令
     * 参数说明 ctx 上级通道处理程序
     * 参数说明 receivedmsg 上级发送数据对象
     * 参数说明 map 提取后的上级参数
     * 参数说明 Type 上级控制类型
     * 参数说明 Command 上级控制命令
     * 参数说明 Code 编号
     * 返回值说明: void
     ***********************************/
    private void otherControlMethod(ChannelHandlerContext ctx, MyMessageProtocol receivedmsg, Map<String, Object> map
            , String Type, String Command, String Code) {
        logger.info("上级系统发送命令!type{},command{}", Type, Command);
        stationRobotService.sendCommand("", httpServerConfig.getPatrolServerid(), "", Type, Command, Code, null);
        String reponsexml = MyXmlUtil.getXml(map.get("ReceiveCode").toString(), map.get("SendCode").toString(),
                SystemCode.TYPE_SYSTEM_MESSAGE_CODE.getCode(), SystemCode.COMMAND_RESPONSE_CODE.getCode(),
                SystemCode.SUCCESS_STATUS_CODE.getCode(), null);
        sendResponseData(ctx, receivedmsg, reponsexml);
    }

    /**
     * 从服务端收到新的数据、读取完成时调用
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws IOException {
        logger.info("channelReadComplete");
        ctx.flush();
    }

    /**
     * 当出现 Throwable 对象才会被调用，即当 Netty 由于 IO 错误或者处理器在处理事件时抛出的异常时
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws IOException {
        logger.info("exceptionCaught");
        logger.error(cause.getMessage());
        ctx.close();//抛出异常，断开与客户端的连接
    }

    /**
     * 客户端与服务端第一次建立连接时 执行
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        InetSocketAddress inSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIp = inSocket.getAddress().getHostAddress();
        logger.info(clientIp);
    }

    /**
     * 客户端与服务端 断连时 执行
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        InetSocketAddress inSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIp = inSocket.getAddress().getHostAddress();
        platformParentSystemService.update(new LambdaUpdateWrapper<PlatformParentSystem>().eq(PlatformParentSystem::getServerIp, clientIp).set(PlatformParentSystem::getIsFlag, "0"));
        List<PlatformParentSystem> list =
                platformParentSystemService.list(new LambdaQueryWrapper<PlatformParentSystem>().eq(PlatformParentSystem::getServerIp, clientIp));
//        heartBeatTask.stop("HeartBeatTask");
        if (list.size() > 0) {
            PlatformParentSystem platformParentSystem = list.get(0);
            BootNettyClientChannel bootNettyClientChannel =
                    BootNettyClientChannelCache.channelMapCache.get(platformParentSystem.getChildCode());
            if (bootNettyClientChannel != null) {
                bootNettyClientChannel.getChannel().close();
                BootNettyClientChannelCache.channelMapCache.remove(platformParentSystem.getChildCode());
            }
        }
        logger.error("上级系统与区域巡视主机服务器断开连接了！" + clientIp);
    }

    /**********************************
     * 用途说明: 发送响应数据
     * 参数说明 ctx
     * 参数说明 msg
     * 参数说明 reponsexml
     * 返回值说明: void
     ***********************************/
    public void sendResponseData(ChannelHandlerContext ctx, MyMessageProtocol msg, String reponsexml) {
        WebSocketServer.sendInfo("robotinfo", reponsexml);
        MyMessageProtocol messageProtocol = new MyMessageProtocol();
        messageProtocol.setSenderSerialNo(BootSessionCache.getResponseSessionID());
        messageProtocol.setReceiverSerialNo(msg.getSenderSerialNo());
        messageProtocol.setSessionflag(1);
        messageProtocol.setXmllen(reponsexml.getBytes(CharsetUtil.UTF_8).length);
        messageProtocol.setXmlcontent(reponsexml.getBytes(CharsetUtil.UTF_8));
        ctx.write(messageProtocol);
        ctx.flush();
    }

    public void responseMessage(ChannelHandlerContext ctx, Map<String, Object> map, Object msg, String Type,
                                String Command, String Items) {
        MyMessageProtocol receivedmsg = (MyMessageProtocol) msg;
        String reponsexml = MyXmlUtil.getXml(map.get("ReceiveCode").toString(), map.get("SendCode").toString(), Type,
                Command, SystemCode.SUCCESS_STATUS_CODE.getCode(), Items);
        boolean open = ctx.channel().isOpen();
        logger.info("===============open==============" + open);
        WebSocketServer.sendInfo("robotinfo", reponsexml);
        MyMessageProtocol messageProtocol = new MyMessageProtocol();
        messageProtocol.setSenderSerialNo(BootSessionCache.getResponseSessionID());
        messageProtocol.setReceiverSerialNo(receivedmsg.getSenderSerialNo());
        messageProtocol.setSessionflag(1);
        messageProtocol.setXmllen(reponsexml.getBytes(CharsetUtil.UTF_8).length);
        messageProtocol.setXmlcontent(reponsexml.getBytes(CharsetUtil.UTF_8));
        ctx.write(messageProtocol);
        ctx.flush();
    }

    private void pauseTask(String Code, String Type, String Command, ChannelHandlerContext ctx,
                           MyMessageProtocol receivedmsg) {
        LambdaUpdateWrapper<Task> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Task::getTaskCode, Code).set(Task::getDatastatus, "2").set(Task::getIsenable, "0");
        taskService.update(updateWrapper);
        TaskTodo taskTodo = taskTodoService.getById(Code);
        String stationCode = taskTodo.getStationCode();
        // 发送任务到边缘节点
        List<Substation> substations =
                substationService.list(new LambdaQueryWrapper<Substation>().eq(Substation::getStationCode,
                        stationCode));
        if (substations.size() > 0) {
            Substation substation = substations.get(0);
            if ("1".equals(substation.getIsStationFlag())) {
                stationRobotService.sendCommand(substation.getNodeId(),
                        httpServerConfig.getPatrolServerid(), substation.getNodeId(), Type, Command,
                        Code, null);
                // 创建事件并注册
                Event event = new Event(taskTodo.getTaskTodoId(), response -> {
                    // 回调逻辑：调用 sendResponseData 方法回复上级服务
                    String responseXml = (String) response;
                    sendResponseData(ctx, receivedmsg, responseXml);
                });
                eventManager.registerEvent(taskTodo.getTaskTodoId(), event);
            } else {
                String taskId = taskTodo.getTaskId();
                Task task = taskService.getById(taskId);
                String deviceList = task.getDeviceList();
                List<String> deviceIds = StrUtil.split(deviceList, ",");
                List<Map<String, Object>> robotMapList = substationDeviceService.getRobotCodeByDeviceId(deviceIds);
                if (robotMapList != null && robotMapList.size() > 0) {
                    for (Map<String, Object> robotMap : robotMapList) {
                        String robotCode = ObjectUtil.isEmpty(robotMap.get("deviceCode")) ? "" : robotMap.get(
                                "deviceCode").toString();
                        String deviceIdList = ObjectUtil.isEmpty(robotMap.get("deviceIds")) ? "" : robotMap.get(
                                "deviceIds").toString();
                        if (StrUtil.isBlank(robotCode) || StrUtil.isBlank(deviceIdList)) {
                            logger.error("机器人或点位集合是空的");
                            return;
                        }
                        List<SubstationPatroldevice> list =
                                substationPatroldeviceService.list(new LambdaQueryWrapper<SubstationPatroldevice>().eq(SubstationPatroldevice::getInternationalId, robotCode));
                        if (list.size() <= 0) {
                            return;
                        }
                        SubstationPatroldevice substationPatroldevice = list.get(0);
                        String patroldeviceType = substationPatroldevice.getType();
                        if ("1".equals(patroldeviceType) || "2".equals(patroldeviceType) || "3".equals(patroldeviceType) || "13".equals(patroldeviceType) || "14".equals(patroldeviceType)) {
                            // 机器人系统编码
                            String internationalId = substationPatroldevice.getInternationalId();
                            // 机器人任务
                            stationRobotService.sendCommand(substationPatroldevice.getInternationalId(),
                                    httpServerConfig.getPatrolServerid(), internationalId, Type, Command, Code, null);
                            // 创建事件并注册
                            Event event = new Event(taskTodo.getTaskTodoId(), response -> {
                                // 回调逻辑：调用 sendResponseData 方法回复上级服务
                                String responseXml = (String) response; // 假设响应数据是 XML 字符串
                                sendResponseData(ctx, receivedmsg, responseXml);
                            });
                            eventManager.registerEvent(taskTodo.getTaskTodoId(), event);
                        }

                    }
                }
            }
        }
    }

    private void stopTask(String Code, String Type, String Command, ChannelHandlerContext ctx,
                          MyMessageProtocol receivedmsg) {
        LambdaUpdateWrapper<Task> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Task::getTaskCode, Code).set(Task::getDatastatus, "2").set(Task::getIsenable, "0");
        taskService.update(updateWrapper);
        TaskTodo taskTodo = taskTodoService.getById(Code);
        String stationCode = taskTodo.getStationCode();
        // 发送任务到边缘节点
        List<Substation> substations =
                substationService.list(new LambdaQueryWrapper<Substation>().eq(Substation::getStationCode,
                        stationCode));
        if (substations.size() > 0) {
            Substation substation = substations.get(0);
            if ("1".equals(substation.getIsStationFlag())) {
                stationRobotService.sendCommand(substation.getNodeId(),
                        httpServerConfig.getPatrolServerid(), substation.getNodeId(), Type, Command,
                        Code, null);
                // 创建事件并注册
                Event event = new Event(taskTodo.getTaskTodoId(), response -> {
                    // 回调逻辑：调用 sendResponseData 方法回复上级服务
                    String responseXml = (String) response;
                    sendResponseData(ctx, receivedmsg, responseXml);
                });
                eventManager.registerEvent(taskTodo.getTaskTodoId(), event);
            }else{
                String taskId = taskTodo.getTaskId();
                Task task = taskService.getById(taskId);
                String deviceList = task.getDeviceList();
                List<String> deviceIds = StrUtil.split(deviceList, ",");
                List<Map<String, Object>> robotMapList = substationDeviceService.getRobotCodeByDeviceId(deviceIds);
                if (robotMapList != null && robotMapList.size() > 0) {
                    for (Map<String, Object> robotMap : robotMapList) {
                        String robotCode = ObjectUtil.isEmpty(robotMap.get("deviceCode")) ? "" : robotMap.get(
                                "deviceCode").toString();
                        String deviceIdList = ObjectUtil.isEmpty(robotMap.get("deviceIds")) ? "" : robotMap.get(
                                "deviceIds").toString();
                        if (StrUtil.isBlank(robotCode) || StrUtil.isBlank(deviceIdList)) {
                            logger.error("机器人或点位集合是空的");
                            return;
                        }
                        List<SubstationPatroldevice> list =
                                substationPatroldeviceService.list(new LambdaQueryWrapper<SubstationPatroldevice>().eq(SubstationPatroldevice::getInternationalId, robotCode));
                        if (list.size() <= 0) {
                            return;
                        }
                        SubstationPatroldevice substationPatroldevice = list.get(0);
                        String patroldeviceType = substationPatroldevice.getType();
                        if ("1".equals(patroldeviceType) || "2".equals(patroldeviceType) || "3".equals(patroldeviceType) || "13".equals(patroldeviceType) || "14".equals(patroldeviceType)) {
                            // 机器人系统编码
                            String internationalId = substationPatroldevice.getInternationalId();
                            // 机器人任务
                            stationRobotService.sendCommand(substationPatroldevice.getInternationalId(),
                                    httpServerConfig.getPatrolServerid(), internationalId, Type, Command, Code, null);
                            // 创建事件并注册
                            Event event = new Event(taskTodo.getTaskTodoId(), response -> {
                                // 回调逻辑：调用 sendResponseData 方法回复上级服务
                                String responseXml = (String) response; // 假设响应数据是 XML 字符串
                                sendResponseData(ctx, receivedmsg, responseXml);
                            });
                            eventManager.registerEvent(taskTodo.getTaskTodoId(), event);
                        }

                    }
                }
            }
        }
    }

    private void runNow(String Code, String Type, String Command, ChannelHandlerContext ctx,
                        MyMessageProtocol receivedmsg) {
        // 查询任务
        LambdaQueryWrapper<Task> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Task::getTaskCode, Code);
        Task task = taskService.getOne(queryWrapper);
        String deviceList = task.getDeviceList();
        String nowPriority = task.getPriority();
        String stationCode = task.getStationCode();
        // 发送任务到边缘节点
        List<Substation> substations =
                substationService.list(new LambdaQueryWrapper<Substation>().eq(Substation::getStationCode,
                        stationCode));
        if (substations.size() > 0) {
            Substation substation = substations.get(0);
            if ("1".equals(substation.getIsStationFlag())) {
                // 所有正在执行的任务
                List<TaskTodo> list =
                        taskTodoService.list(new LambdaQueryWrapper<TaskTodo>().lt(TaskTodo::getPriority,
                                nowPriority).eq(TaskTodo::getTaskState, "2").eq(TaskTodo::getStationCode,
                                task.getStationCode()).select(TaskTodo::getTaskTodoId));
                for (TaskTodo taskTodo : list) {
                    stationRobotService.sendCommand(substation.getNodeId(),
                            httpServerConfig.getPatrolServerid(), substation.getNodeId(), Type, "2",
                            taskTodo.getTaskTodoId(), null);
                }
                stationRobotService.sendCommand(substation.getNodeId(),
                        httpServerConfig.getPatrolServerid(), substation.getNodeId(), Type, Command,
                        Code, null);
                // 创建事件并注册
                Event event = new Event(task.getTaskCode(), response -> {
                    // 回调逻辑：调用 sendResponseData 方法回复上级服务
                    String responseXml = (String) response;
                    sendResponseData(ctx, receivedmsg, responseXml);
                });
                eventManager.registerEvent(task.getTaskCode(), event);
            } else {
                List<String> deviceIds = StrUtil.split(deviceList, ",");
                List<Map<String, Object>> robotMapList = substationDeviceService.getRobotCodeByDeviceId(deviceIds);
                if (robotMapList != null && robotMapList.size() > 0) {
                    for (Map<String, Object> robotMap : robotMapList) {
                        String robotCode = ObjectUtil.isEmpty(robotMap.get("deviceCode")) ? "" : robotMap.get(
                                "deviceCode").toString();
                        String deviceIdList = ObjectUtil.isEmpty(robotMap.get("deviceIds")) ? "" : robotMap.get(
                                "deviceIds").toString();
                        if (StrUtil.isBlank(robotCode) || StrUtil.isBlank(deviceIdList)) {
                            System.out.println("机器人或点位集合是空的");
                            return;
                        }
                        List<SubstationPatroldevice> list =
                                substationPatroldeviceService.list(new LambdaQueryWrapper<SubstationPatroldevice>().eq(SubstationPatroldevice::getInternationalId, robotCode));
                        if (list.size() <= 0) {
                            return;
                        }
                        SubstationPatroldevice substationPatroldevice = list.get(0);
                        String patroldeviceType = substationPatroldevice.getType();
                        if ("1".equals(patroldeviceType) || "2".equals(patroldeviceType) || "3".equals(patroldeviceType) || "13".equals(patroldeviceType) || "14".equals(patroldeviceType)) {
                            // 机器人系统编码
                            String internationalId = substationPatroldevice.getInternationalId();
                            // 机器人任务
                            stationRobotService.sendCommand(substationPatroldevice.getInternationalId(),
                                    httpServerConfig.getPatrolServerid(), internationalId, Type, Command, Code, null);
                            // 创建事件并注册
                            Event event = new Event(task.getTaskCode(), response -> {
                                // 回调逻辑：调用 sendResponseData 方法回复上级服务
                                String responseXml = (String) response; // 假设响应数据是 XML 字符串
                                sendResponseData(ctx, receivedmsg, responseXml);
                            });
                            eventManager.registerEvent(task.getTaskCode(), event);

                        }
                    }
                }
            }
        }
        LambdaUpdateWrapper<Task> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Task::getTaskCode, Code).set(Task::getIsenable, "0");
        taskService.update(updateWrapper);

    }

    private void resumeTask(String Code, String Type, String Command, ChannelHandlerContext ctx,
                            MyMessageProtocol receivedmsg) {
        LambdaUpdateWrapper<Task> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Task::getTaskCode, Code).set(Task::getDatastatus, "2").set(Task::getIsenable, "0");
        taskService.update(updateWrapper);
        TaskTodo taskTodo = taskTodoService.getById(Code);
        String stationCode = taskTodo.getStationCode();
        // 发送任务到边缘节点
        List<Substation> substations =
                substationService.list(new LambdaQueryWrapper<Substation>().eq(Substation::getStationCode,
                        stationCode));
        if (substations.size() > 0) {
            Substation substation = substations.get(0);
            if ("1".equals(substation.getIsStationFlag())) {
                stationRobotService.sendCommand(substation.getNodeId(),
                        httpServerConfig.getPatrolServerid(), substation.getNodeId(), Type, Command,
                        Code, null);
                // 创建事件并注册
                Event event = new Event(taskTodo.getTaskTodoId(), response -> {
                    // 回调逻辑：调用 sendResponseData 方法回复上级服务
                    String responseXml = (String) response; // 假设响应数据是 XML 字符串
                    sendResponseData(ctx, receivedmsg, responseXml);
                });
                eventManager.registerEvent(taskTodo.getTaskTodoId(), event);
            } else {
                String taskId = taskTodo.getTaskId();
                Task task = taskService.getById(taskId);
                String deviceList = task.getDeviceList();
                List<String> deviceIds = StrUtil.split(deviceList, ",");
                List<Map<String, Object>> robotMapList = substationDeviceService.getRobotCodeByDeviceId(deviceIds);
                if (robotMapList != null && robotMapList.size() > 0) {
                    for (Map<String, Object> robotMap : robotMapList) {
                        String robotCode = ObjectUtil.isEmpty(robotMap.get("deviceCode")) ? "" : robotMap.get(
                                "deviceCode").toString();
                        String deviceIdList = ObjectUtil.isEmpty(robotMap.get("deviceIds")) ? "" : robotMap.get(
                                "deviceIds").toString();
                        if (StrUtil.isBlank(robotCode) || StrUtil.isBlank(deviceIdList)) {
                            logger.error("机器人或点位集合是空的");
                            return;
                        }
                        List<SubstationPatroldevice> list =
                                substationPatroldeviceService.list(new LambdaQueryWrapper<SubstationPatroldevice>().eq(SubstationPatroldevice::getInternationalId, robotCode));
                        if (list.size() <= 0) {
                            return;
                        }
                        SubstationPatroldevice substationPatroldevice = list.get(0);
                        String patroldeviceType = substationPatroldevice.getType();
                        if ("1".equals(patroldeviceType) || "2".equals(patroldeviceType) || "3".equals(patroldeviceType) || "13".equals(patroldeviceType) || "14".equals(patroldeviceType)) {
                            // 机器人系统编码
                            String internationalId = substationPatroldevice.getInternationalId();
                            // 机器人任务
                            stationRobotService.sendCommand(substationPatroldevice.getInternationalId(),
                                    httpServerConfig.getPatrolServerid(), internationalId, Type, Command, Code, null);
                            // 创建事件并注册
                            Event event = new Event(taskTodo.getTaskTodoId(), response -> {
                                // 回调逻辑：调用 sendResponseData 方法回复上级服务
                                String responseXml = (String) response; // 假设响应数据是 XML 字符串
                                sendResponseData(ctx, receivedmsg, responseXml);
                            });
                            eventManager.registerEvent(taskTodo.getTaskTodoId(), event);
                        }

                    }
                }
            }
        }
    }

}
