package com.yfd.platform.component.nettyserver;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.*;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
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.component.nettyclient.EventManager;
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.*;
import com.yfd.platform.modules.basedata.service.*;
import com.yfd.platform.modules.patroltask.domain.AlarmLog;
import com.yfd.platform.modules.patroltask.domain.Task;
import com.yfd.platform.modules.patroltask.domain.TaskResult;
import com.yfd.platform.modules.patroltask.domain.TaskTodo;
import com.yfd.platform.modules.patroltask.mapper.TaskResultMapper;
import com.yfd.platform.modules.patroltask.service.IAlarmLogService;
import com.yfd.platform.modules.patroltask.service.ITaskService;
import com.yfd.platform.modules.patroltask.service.ITaskTodoService;
import com.yfd.platform.modules.robotapi.domain.PlatformParentSystem;
import com.yfd.platform.modules.robotapi.domain.RobotOfflineLog;
import com.yfd.platform.modules.robotapi.domain.RobotRunLog;
import com.yfd.platform.modules.robotapi.service.IPlatformParentSystemService;
import com.yfd.platform.modules.robotapi.service.IRobotOfflineLogService;
import com.yfd.platform.modules.robotapi.service.IRobotRunLogService;
import com.yfd.platform.modules.robotapi.service.IStationRobotService;
import com.yfd.platform.system.domain.SysDictionaryItems;
import com.yfd.platform.system.domain.SysOrganization;
import com.yfd.platform.system.service.ISysDictionaryItemsService;
import com.yfd.platform.utils.FileUtil;
import com.yfd.platform.utils.FtpClient;
import com.yfd.platform.utils.HttpRESTfulUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.*;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @create 2021/9/9 10:12
 */
@Slf4j
@Component
@Transactional
public class NettyServerHandler extends SimpleChannelInboundHandler<MyMessageProtocol> {

    public static NettyServerHandler nettyServerHandler;

    @Resource
    private IStationRobotService stationRobotService;

    @Resource
    private IWeatherLogService weatherLogService;

    @Resource
    private TaskResultMapper taskResultMapper;

    @Resource
    private ITaskTodoService taskTodoService;

    @Resource
    private ITaskService taskService;

    @Resource
    private ISubstationPatroldeviceService substationPatroldeviceService;

    @Resource
    private ISubstationDeviceService substationDeviceService;

    @Resource
    private ISubstationService substationService;

    @Resource
    private ISubstationAreaService substationAreaService;
    @Resource
    private ISubstationBayService substationBayService;
    @Resource
    private ISubstationMaindeviceService substationMaindeviceService;
    @Resource
    private ISubstationComponentService substationComponentService;
    @Resource
    private IAlarmLogService alarmLogService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private FtpClient ftpClient;
    @Resource
    private HttpServerConfig httpServerConfig;
    @Resource
    private HttpRESTfulUtils httpRESTfulUtils;
    @Resource
    private ParentConfig parentConfig;
    @Resource
    private IRobotRunLogService robotRunLogService;
    @Resource
    private IRobotOfflineLogService robotOfflineLogService;
    @Resource
    private ISysDictionaryItemsService sysDictionaryItemsService;
    @Resource
    private IPlatformParentSystemService platformParentSystemService;

    @Resource
    private IAlarmThresholdService alarmThresholdService;
    private long count = 1;
    // 事件管理器
    @Resource
    private EventManager eventManager;

    @PostConstruct
    public void init() {
        nettyServerHandler = this;
        nettyServerHandler.stationRobotService = this.stationRobotService;
        nettyServerHandler.weatherLogService = this.weatherLogService;
        nettyServerHandler.taskTodoService = this.taskTodoService;
        nettyServerHandler.substationService = this.substationService;
        nettyServerHandler.substationPatroldeviceService = this.substationPatroldeviceService;
        nettyServerHandler.redisTemplate = this.redisTemplate;
        nettyServerHandler.ftpClient = this.ftpClient;
        nettyServerHandler.substationDeviceService = this.substationDeviceService;
        nettyServerHandler.substationAreaService = this.substationAreaService;
        nettyServerHandler.substationBayService = this.substationBayService;
        nettyServerHandler.substationMaindeviceService = this.substationMaindeviceService;
        nettyServerHandler.substationComponentService = this.substationComponentService;
        nettyServerHandler.taskService = this.taskService;
        nettyServerHandler.taskResultMapper = this.taskResultMapper;
        nettyServerHandler.alarmLogService = this.alarmLogService;
        nettyServerHandler.httpServerConfig = this.httpServerConfig;
        nettyServerHandler.httpRESTfulUtils = this.httpRESTfulUtils;
        nettyServerHandler.parentConfig = this.parentConfig;
        nettyServerHandler.robotRunLogService = this.robotRunLogService;
        nettyServerHandler.robotOfflineLogService = this.robotOfflineLogService;
        nettyServerHandler.sysDictionaryItemsService = this.sysDictionaryItemsService;
        nettyServerHandler.platformParentSystemService = this.platformParentSystemService;
        nettyServerHandler.eventManager = this.eventManager;
        nettyServerHandler.alarmThresholdService = this.alarmThresholdService;
    }

    /**
     * 客户端连接会触发
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Constant.now = LocalDateTime.now();
        Channel channel = ctx.channel();
        log.info("机器人{}连接成功!", ctx.pipeline().channel().remoteAddress());
        ctx.write("server connected success");
        ctx.flush();
        String stationNodeIP = ctx.channel().remoteAddress().toString().substring(1).split(":")[0];
        LambdaQueryWrapper<SubstationPatroldevice> queryWrapper = new LambdaQueryWrapper<>();
        //        String robotIp = ctx.channel().remoteAddress().toString().substring(1).split(":")[0];
        queryWrapper.eq(SubstationPatroldevice::getIpaddr, stationNodeIP);
        List<SubstationPatroldevice> list = nettyServerHandler.substationPatroldeviceService.list(queryWrapper);
        if (list.size() > 0) {
            SubstationPatroldevice substationPatroldevice = list.get(0);
            JSONArray jsonArray = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            jsonObject.putOpt("patroldevice_name", substationPatroldevice.getPatroldeviceName());
            jsonObject.putOpt("patroldevice_code", substationPatroldevice.getPatroldeviceCode());
            jsonObject.putOpt("time", DateUtil.now());
            jsonObject.putOpt("type", "301");
            jsonObject.putOpt("value", "0");
            jsonObject.putOpt("unit", "");
            jsonObject.putOpt("value_unit", "正常");
            jsonArray.add(jsonObject);
            WebSocketServer.sendInfo("robot_status_data", jsonArray.toString());
        }
//        ChannelMap.getChannelMap().put(stationNodeIP, ctx.channel());
    }

    /**
     * 客户端发消息会触发
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void channelRead0(ChannelHandlerContext ctx, MyMessageProtocol msg) throws Exception {
        if (msg.getXmlcontent() == null) {
            log.info("客户端发消息会触发消息为空");
            return;
        }
        // 发送状态信息
        LambdaQueryWrapper<SubstationPatroldevice> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        String robotIp = ctx.channel().remoteAddress().toString().substring(1).split(":")[0];
        lambdaQueryWrapper.eq(SubstationPatroldevice::getIpaddr, robotIp);
        List<SubstationPatroldevice> patroldevices = nettyServerHandler.substationPatroldeviceService.list(lambdaQueryWrapper);
        if (patroldevices.size() > 0) {
            SubstationPatroldevice substationPatroldevice = patroldevices.get(0);
            JSONArray jsonArray = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            jsonObject.putOpt("patroldevice_name", substationPatroldevice.getPatroldeviceName());
            jsonObject.putOpt("patroldevice_code", substationPatroldevice.getPatroldeviceCode());
            jsonObject.putOpt("time", DateUtil.now());
            jsonObject.putOpt("type", "301");
            jsonObject.putOpt("value", "0");
            jsonObject.putOpt("unit", "");
            jsonObject.putOpt("value_unit", "正常");
            jsonArray.add(jsonObject);
            WebSocketServer.sendInfo("robot_status_data", jsonArray.toString());
        }

        String xml = new String(msg.getXmlcontent());
        Map<String, Object> map = MyXmlUtil.xmlToMap(xml);
        String Type = map.get("Type").toString();
        String Command = map.get("Command").toString();
        String SendCode = map.get("SendCode").toString();
        String Code = "";
        if (ObjectUtil.isNotEmpty(map.get("Code"))) {
            Code = map.get("Code").toString();
        }
        // 序列号
        long receiverSerialNo = msg.getReceiverSerialNo();
        if (SystemCode.TYPE_SYSTEM_MESSAGE_CODE.getCode().equals(Type) && SystemCode.COMMAND_REGISTER_CODE.getCode().equals(Command)) {
            //机器人注册成功
            JSONObject jsonObject = new JSONObject();
            if (StrUtil.isNotBlank(nettyServerHandler.parentConfig.getHeartBeatInterval())) {
                jsonObject.putOnce("heart_beat_interval", nettyServerHandler.parentConfig.getHeartBeatInterval());
            }

            if (StrUtil.isNotBlank(nettyServerHandler.parentConfig.getPatroldeviceRunInterval())) {
                jsonObject.putOnce("patroldevice_run_interval",
                        nettyServerHandler.parentConfig.getPatroldeviceRunInterval());
            }

            if (StrUtil.isNotBlank(nettyServerHandler.parentConfig.getWeatherInterval())) {
                jsonObject.putOnce("env_interval", nettyServerHandler.parentConfig.getWeatherInterval());
            }
            String reponsexml = MyXmlUtil.getXml(map.get("ReceiveCode").toString(), map.get("SendCode").toString(),
                    SystemCode.TYPE_SYSTEM_MESSAGE_CODE.getCode(), SystemCode.COMMAND_ITEM_RESPONSE_CODE.getCode(),
                    SystemCode.SUCCESS_STATUS_CODE.getCode(), jsonObject.toString());
            log.info("响应信息" + reponsexml);
            sendResponseData(ctx, msg, reponsexml);
            ChannelMap.getChannelMap().put(SendCode, ctx.channel());
            log.info("机器人/无人机注册成功！{}", map.get("SendCode").toString());
        }
        if (SystemCode.TYPE_SYSTEM_MESSAGE_CODE.getCode().equals(Type) && SystemCode.COMMAND_HEARTBEAT_CODE.getCode().equals(Command)) {
            String sendCode = map.get("SendCode").toString();
            String receiveCode = map.get("ReceiveCode").toString();
            //机器人发送心跳信息
            String reponsexml = MyXmlUtil.getXml(receiveCode, sendCode, SystemCode.TYPE_SYSTEM_MESSAGE_CODE.getCode()
                    , SystemCode.COMMAND_RESPONSE_CODE.getCode(), SystemCode.SUCCESS_STATUS_CODE.getCode(), null);
            sendResponseData(ctx, msg, reponsexml);
            nettyServerHandler.stationRobotService.updateRobotOnline(robotIp, SystemCode.ONLINE_CODE.getCode());
            RobotRunLog robotRunLog = new RobotRunLog();
            robotRunLog.setCode(Code);
            robotRunLog.setCommand(Command);
            LocalDateTime now = LocalDateTime.now();
            robotRunLog.setReportTime(now);
            robotRunLog.setType(Type);
            robotRunLog.setXmlContent(xml);
            robotRunLog.setRobotCode(sendCode);
            robotRunLog.setPatrolServerCode(receiveCode);
            List<RobotRunLog> list =
                    nettyServerHandler.robotRunLogService.list(new LambdaQueryWrapper<RobotRunLog>().eq(RobotRunLog::getPatrolServerCode, receiveCode).eq(RobotRunLog::getRobotCode, sendCode).orderByDesc(RobotRunLog::getReportTime).last("LIMIT 1"));
            if (list.size() > 0) {
                // 最后一次心跳
                RobotRunLog lastRobotRunLog = list.get(0);
                // 最后一次时间
                LocalDateTime lastReportTime = lastRobotRunLog.getReportTime();
                Duration duration = Duration.between(lastReportTime, now);
                if (duration.getSeconds() > 4 * 60 * 60) {
                    List<RobotOfflineLog> robotOfflineLogs =
                            nettyServerHandler.robotOfflineLogService.list(new LambdaQueryWrapper<RobotOfflineLog>().eq(RobotOfflineLog::getPatrolServerCode, receiveCode).eq(RobotOfflineLog::getRobotCode, sendCode).orderByDesc(RobotOfflineLog::getOfflineEndTime).last("LIMIT 1"));
                    long sum = 1;
                    if (robotOfflineLogs.size() > 0) {
                        RobotOfflineLog robotOfflineLog = robotOfflineLogs.get(0);
                        sum = NumberUtil.parseLong(robotOfflineLog.getOfflineSum()) + 1;
                    }
                    //时间差大于4小时,插入一条离线记录
                    RobotOfflineLog robotOfflineLog = new RobotOfflineLog();
                    robotOfflineLog.setOfflineEndTime(now.minusSeconds(1));
                    robotOfflineLog.setOfflineStartTime(lastReportTime);
                    robotOfflineLog.setOfflineSum(sum + "");
                    robotOfflineLog.setPatrolServerCode(receiveCode);
                    robotOfflineLog.setRobotCode(sendCode);
                    nettyServerHandler.robotOfflineLogService.save(robotOfflineLog);
                }
            }
            nettyServerHandler.robotRunLogService.save(robotRunLog);
            log.info("机器人/无人机心跳保持！{} ，{}", map.get("SendCode").toString(), DateUtil.now());
        }

        if (SystemCode.TYPE_SYSTEM_MESSAGE_CODE.getCode().equals(Type) && SystemCode.COMMAND_RESPONSE_CODE.getCode().equals(Command)) {
            String xmlContent =
                    nettyServerHandler.redisTemplate.opsForValue().get(Constant.ROBOT_SEND_CODE + receiverSerialNo);
            Map<String, Object> xmlMap = MyXmlUtil.xmlToMap(xmlContent);
            // 发送的指令
            String responseType = xmlMap.get("Type").toString();
            String responseCommand = xmlMap.get("Command").toString();
            // 检修区域下发
            if (SystemCode.TYPE_EXAMINE_ISSUED_CODE.getCode().equals(responseType) && SystemCode.COMMAND_EXAMINE_CONFIG_CODE.getCode().equals(responseCommand)) {
                log.info("检修区域下发！{}", map.toString());
            }
            if (SystemCode.TYPE_TASK_ISSUED_CODE.getCode().equals(responseType) && SystemCode.COMMAND_TASK_CONFIG_CODE.getCode().equals(responseCommand)) {
                log.info("任务配置响应！{}-{}", map.toString(), DateUtil.now());
            }
        }

        if (SystemCode.TYPE_SYSTEM_MESSAGE_CODE.getCode().equals(Type) && SystemCode.COMMAND_ITEM_RESPONSE_CODE.getCode().equals(Command)) {
            log.info("序列号展示" + msg.getReceiverSerialNo());
            String xmlContent =
                    nettyServerHandler.redisTemplate.opsForValue().get(Constant.ROBOT_SEND_CODE + receiverSerialNo);
            if (StrUtil.isBlank(xmlContent)) {
                return;
            }
            xmlContent = StrUtil.strip(xmlContent, "\"");
            xmlContent = xmlContent.replace("\\n", "").replace("\\", "");
            Map<String, Object> xmlMap = MyXmlUtil.xmlToMap(xmlContent);
            // 发送的指令
            String responseType = xmlMap.get("Type").toString();
            String responseCommand = xmlMap.get("Command").toString();
            String responseCode = ObjectUtil.isEmpty(xmlMap.get("Code")) ? "" : xmlMap.get("Code").toString();
            List<Map<String, String>> items = (List<Map<String, String>>) map.get("Items");

            // 任务启动响应
            if (SystemCode.TYPE_TASK_CONTROL_CODE.getCode().equals(responseType) && SystemCode.COMMAND_TASK_START_CODE.getCode().equals(responseCommand)) {
                log.info("任务控制-任务启动响应！{}", map.toString());
                if (StrUtil.isNotBlank(responseCode)) {
                    JSONArray jsonArray = JSONUtil.parseArray(items);
                    nettyServerHandler.eventManager.triggerEvent(responseCode, jsonArray.toString());
                    if (SystemCode.SUCCESS_STATUS_CODE.getCode().equals(Code)) {
                        for (Map<String, String> item : items) {
                            String taskPatrolledId = item.get("task_patrolled_id");
                            int count =
                                    nettyServerHandler.taskTodoService.count(new LambdaQueryWrapper<TaskTodo>().eq(TaskTodo::getTaskTodoId, taskPatrolledId));
                            if (count <= 0) {
                                TaskTodo taskTodo = new TaskTodo();
                                taskTodo.setTaskTodoId(taskPatrolledId);
                                taskTodo.setDatastatus("1");
                                taskTodo.setTaskState("2");
                                taskTodo.setTaskCode(responseCode);
                                Task task =
                                        nettyServerHandler.taskService.getOne(new LambdaQueryWrapper<Task>().eq(Task::getTaskCode, responseCode));
                                if (task != null) {
                                    taskTodo.setTaskId(task.getTaskId());
                                    taskTodo.setTaskType(task.getTaskType());
                                    taskTodo.setTaskState("2");
                                    taskTodo.setTaskName(task.getTaskName());
                                    taskTodo.setPriority(task.getPriority());
                                    taskTodo.setTaskClass(task.getTaskClass());
                                    taskTodo.setDeviceUnusualnum(0);
                                    taskTodo.setDeviceDeforeNum(0);
                                    taskTodo.setDeviceFailureNum(0);
                                    taskTodo.setStationCode(task.getStationCode());
                                    String deviceList = task.getDeviceList();
                                    List<String> split = StrUtil.split(deviceList, ",");
                                    taskTodo.setDeviceSumnum(split.size());
                                    taskTodo.setPlanStartTime(task.getFixedStartTime());
                                    taskTodo.setStartTime(DateUtil.now());
                                    taskTodo.setTaskProgress("0");
                                    taskTodo.setExamineFlag("0");
                                    taskTodo.setType(task.getType());
                                }
                                taskTodo.setLastmodifier("机器人系统");
                                taskTodo.setLastmodifydate(new Timestamp(System.currentTimeMillis()));
                                // 新增任务执行数据
                                nettyServerHandler.taskTodoService.saveOrUpdate(taskTodo);
                            }
                        }
                    }
                }

            }
            // 任务暂停响应
            if (SystemCode.TYPE_TASK_CONTROL_CODE.getCode().equals(responseType) && SystemCode.COMMAND_TASK_PAUSE_CODE.getCode().equals(responseCommand)) {
                if (StrUtil.isNotBlank(responseCode)) {
                    JSONArray jsonArray = JSONUtil.parseArray(items);
                    nettyServerHandler.eventManager.triggerEvent(responseCode, jsonArray.toString());
                    if (SystemCode.SUCCESS_STATUS_CODE.getCode().equals(Code)) {
                        LambdaUpdateWrapper<TaskTodo> updateWrapper = new LambdaUpdateWrapper<>();
                        updateWrapper.eq(TaskTodo::getTaskTodoId, responseCode).set(TaskTodo::getTaskState, "3");
                        nettyServerHandler.taskTodoService.update(updateWrapper);
                    }
                }

                log.info("任务控制-任务暂停响应！{}", map.toString());
            }
            // 任务继续响应
            if (SystemCode.TYPE_TASK_CONTROL_CODE.getCode().equals(responseType) && SystemCode.COMMAND_TASK_RESUME_CODE.getCode().equals(responseCommand)) {
                if (StrUtil.isNotBlank(responseCode)) {
                    JSONArray jsonArray = JSONUtil.parseArray(items);
                    nettyServerHandler.eventManager.triggerEvent(responseCode, jsonArray.toString());
                    if (SystemCode.SUCCESS_STATUS_CODE.getCode().equals(Code)) {
                        LambdaUpdateWrapper<TaskTodo> updateWrapper = new LambdaUpdateWrapper<>();
                        updateWrapper.eq(TaskTodo::getTaskTodoId, responseCode).set(TaskTodo::getTaskState, "2");
                        nettyServerHandler.taskTodoService.update(updateWrapper);
                    }
                }

                log.info("任务控制-任务继续响应！{}", map.toString());
            }
            // 任务停止响应
            if (SystemCode.TYPE_TASK_CONTROL_CODE.getCode().equals(responseType) && SystemCode.COMMAND_TASK_STOP_CODE.getCode().equals(responseCommand)) {
                if (StrUtil.isNotBlank(responseCode)) {
                    JSONArray jsonArray = JSONUtil.parseArray(items);
                    nettyServerHandler.eventManager.triggerEvent(responseCode, jsonArray.toString());
                    if (SystemCode.SUCCESS_STATUS_CODE.getCode().equals(Code)) {
                        LambdaUpdateWrapper<TaskTodo> updateWrapper = new LambdaUpdateWrapper<>();
                        updateWrapper.eq(TaskTodo::getTaskTodoId, responseCode).set(TaskTodo::getTaskState, "2");
                        nettyServerHandler.taskTodoService.update(updateWrapper);
                    }
                }
                LambdaUpdateWrapper<TaskTodo> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(TaskTodo::getTaskTodoId, responseCode).set(TaskTodo::getTaskState, "4");
                nettyServerHandler.taskTodoService.update(updateWrapper);
                log.info("任务控制-任务停止响应！{}", map.toString());
            }
            // 模型同步
            if (SystemCode.TYPE_MODEL_SYNC_CODE.getCode().equals(responseType) && SystemCode.COMMAND_MODEL_HOST_CODE.getCode().equals(responseCommand)) {
                log.info("进入模型同步方法");
                for (Map<String, String> item : items) {

                    if (!item.containsKey(SystemCode.COMMAND_DEVICE_FILE_PATH.getCode())) {
                        continue;
                    }
                    String deviceFilePath = item.get(SystemCode.COMMAND_DEVICE_FILE_PATH.getCode());
                    String path = nettyServerHandler.httpServerConfig.getModelPath() + deviceFilePath;
                    log.info("文件路径" + path);
                    StringBuilder content = new StringBuilder();
                    try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
                        String line;
                        while ((line = reader.readLine()) != null) {
                            content.append(line).append("\n");
                        }
                    } catch (IOException e) {
                        log.error(e.getMessage());;
                    }
                    //                    String xmlContent = content.toString();
                    Map<String, Object> modelMap = MyXmlUtil.xmlModelToMap(content.toString());
                    List<Map<String, String>> deviceList = (List<Map<String, String>>) modelMap.get("Device_Model");
                    for (Map<String, String> device : deviceList) {
                        // 模型数据解析成点位对象
                        SubstationDevice substationDevice = BeanUtil.toBean(device, SubstationDevice.class);
                        String stationCode = substationDevice.getStationCode();
                        LambdaQueryWrapper<Substation> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(Substation::getStationCode, stationCode);
                        Substation substation = nettyServerHandler.substationService.getOne(queryWrapper);
                        String stationId = substation.getStationId();
                        substationDevice.setStationId(stationId);
                        substationDevice.setDatastatus("1");
                        substationDevice.setLastmodifier("机器人系统");
                        substationDevice.setLastmodifydate(LocalDateTime.now());
                        substationDevice.setDeviceCode(substationDevice.getDeviceId());

                        // 新增或者修改区域
                        String areaId = substationDevice.getAreaId();
                        String areaName = substationDevice.getAreaName();
                        SubstationArea substationArea = new SubstationArea();
                        substationArea.setAreaId(areaId);
                        substationArea.setAreaName(areaName);
                        substationArea.setStationCode(stationCode);
                        substationArea.setStationName(substation.getStationName());
                        substationArea.setDatastatus("1");
                        substationArea.setLastmodifier("机器人系统");
                        substationArea.setLastmodifydate(LocalDateTime.now());
                        nettyServerHandler.substationAreaService.saveOrUpdate(substationArea);
                        // 新增或者修改间隔
                        String bayId = substationDevice.getBayId();
                        String bayName = substationDevice.getBayName();
                        SubstationBay substationBay = new SubstationBay();
                        substationBay.setAreaId(areaId);
                        substationBay.setAreaName(areaName);
                        substationBay.setBayId(bayId);
                        substationBay.setBayName(bayName);
                        substationBay.setStationCode(stationCode);
                        substationBay.setStationName(substation.getStationName());
                        substationBay.setDatastatus("1");
                        substationBay.setLastmodifier("机器人系统");
                        substationBay.setLastmodifydate(LocalDateTime.now());
                        nettyServerHandler.substationBayService.saveOrUpdate(substationBay);
                        // 新增或修改主设备
                        String mainDeviceId = substationDevice.getMainDeviceId();
                        String mainDeviceName = substationDevice.getMainDeviceName();
                        SubstationMaindevice substationMaindevice = new SubstationMaindevice();
                        substationMaindevice.setMainDeviceId(mainDeviceId);
                        substationMaindevice.setMainDeviceName(mainDeviceName);
                        substationMaindevice.setDeviceType(substationDevice.getDeviceType());
                        substationMaindevice.setStationCode(stationCode);
                        substationMaindevice.setStationName(substation.getStationName());
                        substationMaindevice.setAreaId(areaId);
                        substationMaindevice.setAreaName(areaName);
                        substationMaindevice.setBayId(bayId);
                        substationMaindevice.setBayName(bayName);
                        substationMaindevice.setDatastatus("1");
                        substationMaindevice.setLastmodifier("机器人系统");
                        substationMaindevice.setLastmodifydate(LocalDateTime.now());
                        nettyServerHandler.substationMaindeviceService.saveOrUpdate(substationMaindevice);
                        // 新增或修改部件
                        String componentId = substationDevice.getComponentId();
                        String componentName = substationDevice.getComponentName();
                        SubstationComponent substationComponent = new SubstationComponent();
                        substationComponent.setComponentId(componentId);
                        substationComponent.setComponentName(componentName);
                        substationComponent.setMainDeviceId(mainDeviceId);
                        substationComponent.setMainDeviceName(mainDeviceName);
                        substationComponent.setDeviceType(substationDevice.getDeviceType());
                        substationComponent.setStationCode(stationCode);
                        substationComponent.setStationName(substation.getStationName());
                        substationComponent.setAreaId(areaId);
                        substationComponent.setAreaName(areaName);
                        substationComponent.setBayId(bayId);
                        substationComponent.setBayName(bayName);
                        substationComponent.setDatastatus("1");
                        substationComponent.setLastmodifier("机器人系统");
                        substationComponent.setLastmodifydate(LocalDateTime.now());
                        nettyServerHandler.substationComponentService.saveOrUpdate(substationComponent);
                        // 新增或修改点位
                        nettyServerHandler.substationDeviceService.saveOrUpdate(substationDevice);
                    }
                }
                log.info("模型同步！{}", map.toString());
            }
            // 检修区域下发
            if (SystemCode.TYPE_EXAMINE_ISSUED_CODE.getCode().equals(responseType) && SystemCode.COMMAND_EXAMINE_CONFIG_CODE.getCode().equals(responseCommand)) {
                log.info("检修区域下发！{}", map.toString());
            }
            // 联动任务下发
            if (SystemCode.TYPE_LINKAGE_TASK_ISSUED_CODE.getCode().equals(responseType) && SystemCode.COMMAND_TASK_CONFIG_CODE.getCode().equals(responseCommand)) {
                log.info("联动任务下发！{}", map.toString());
            }
            nettyServerHandler.redisTemplate.delete(Constant.ROBOT_SEND_CODE + receiverSerialNo);
        }
        List<PlatformParentSystem> list = nettyServerHandler.platformParentSystemService.list(new LambdaQueryWrapper<PlatformParentSystem>().eq(PlatformParentSystem::getIsEnable, "1"));
        String parentCode = "";
        if (list.size() > 0) {
            PlatformParentSystem platformParentSystem = list.get(0);
            parentCode = platformParentSystem.getParentCode();
        }
        // 机器人或无人机发送状态
        if (SystemCode.TYPE_DEVICE_STATUS_CODE.getCode().equals(Type)) {
            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, msg, reponsexml);
            List<Map<String, String>> items = (List<Map<String, String>>) map.get("Items");
            JSONArray jsonArray = JSONUtil.parseArray(items);
            WebSocketServer.sendInfo("robot_status_data", jsonArray.toString());
            if (StrUtil.isNotBlank(parentCode)) {
                nettyServerHandler.stationRobotService.sendParentData(map.get("ReceiveCode").toString(), parentCode, Type, Command, Code, jsonArray.toString());
            }
            log.info("机器人主动发送自身状态！状态{}", Type);
        }

        // 机器人或无人机发送运行数据
        if (SystemCode.TYPE_DEVICE_RUN_CODE.getCode().equals(Type)) {
            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, msg, reponsexml);
            List<Map<String, String>> items = (List<Map<String, String>>) map.get("Items");
            JSONArray jsonArray = JSONUtil.parseArray(items);
            WebSocketServer.sendInfo("robot_run_data", jsonArray.toString());
            //            nettyServerHandler.stationRobotService.sendParentData(map.get("ReceiveCode").toString(),
            //                    nettyServerHandler.parentConfig.getParentId(), Type, Command, Code, jsonArray.toString());
            if (StrUtil.isNotBlank(parentCode)) {
                nettyServerHandler.stationRobotService.sendParentData(map.get("ReceiveCode").toString(), parentCode, Type, Command, Code, jsonArray.toString());
            }
            log.info("机器人主动发送运行数据！状态{}", Type);
        }


        // 巡视设备坐标
        if (SystemCode.TYPE_DEVICE_COORDINATE_CODE.getCode().equals(Type)) {
            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, msg, reponsexml);
            List<Map<String, String>> items = (List<Map<String, String>>) map.get("Items");
            JSONArray jsonArray = JSONUtil.parseArray(items);
            WebSocketServer.sendInfo("robot_status_data", jsonArray.toString());
            //            nettyServerHandler.stationRobotService.sendParentData(map.get("ReceiveCode").toString(),
            //                    nettyServerHandler.parentConfig.getParentId(), Type, Command, Code, jsonArray.toString());
            log.info("机器人或无人机发送设备坐标！状态{}", Type);
            if (StrUtil.isNotBlank(parentCode)) {
                nettyServerHandler.stationRobotService.sendParentData(map.get("ReceiveCode").toString(), parentCode, Type, Command, Code, jsonArray.toString());
            }
        }

        // 巡视路线
        if (SystemCode.TYPE_PATROL_ROUTE_CODE.getCode().equals(Type)) {
            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, msg, reponsexml);
            List<Map<String, String>> items = (List<Map<String, String>>) map.get("Items");
            JSONArray jsonArray = JSONUtil.parseArray(items);
            //            nettyServerHandler.stationRobotService.sendParentData(map.get("ReceiveCode").toString(),
            //                    nettyServerHandler.parentConfig.getParentId(), Type, Command, Code, jsonArray.toString());
//            if (StrUtil.isNotBlank(parentCode)) {
//                nettyServerHandler.stationRobotService.sendParentData(map.get("ReceiveCode").toString(), parentCode, Type, Command, Code, jsonArray.toString());
//            }
            log.info("机器人或无人机发送巡视路线！状态{}", Type);
        }

        // 告警信息
        if (SystemCode.TYPE_ABNORMAL_ALARM_CODE.getCode().equals(Type)) {
            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, msg, reponsexml);
            List<Map<String, String>> items = (List<Map<String, String>>) map.get("Items");
            for (Map<String, String> item : items) {
                AlarmLog alarmLog = BeanUtil.toBean(item, AlarmLog.class);
                alarmLog.setAlarmSourceType("1");
                String patroldeviceCode = alarmLog.getPatroldeviceCode();
                List<SubstationPatroldevice> substationPatroldevices =
                        nettyServerHandler.substationPatroldeviceService.list(new LambdaQueryWrapper<SubstationPatroldevice>().eq(SubstationPatroldevice::getPatroldeviceCode, patroldeviceCode));
                if (substationPatroldevices.size() > 0) {
                    SubstationPatroldevice substationPatroldevice = substationPatroldevices.get(0);
                    alarmLog.setStationId(substationPatroldevice.getStationId());
                    alarmLog.setStationCode(substationPatroldevice.getStationCode());
                    alarmLog.setStationName(substationPatroldevice.getStationName());
                    alarmLog.setAreaId(substationPatroldevice.getAreaId());
                    alarmLog.setAreaName(substationPatroldevice.getAreaName());
                    alarmLog.setTaskAlarmType("3");
                    alarmLog.setDatastatus("1");
                    alarmLog.setLastmodifier("机器人系统");
                    alarmLog.setLastmodifydate(new Timestamp(System.currentTimeMillis()));
                    JSONObject jsonObject = JSONUtil.parseObj(substationPatroldevice);
                    WebSocketServer.sendInfo(alarmLog.getStationId(), jsonObject.toString());

                }
                alarmLog.setAlarmDate(item.get("time"));
            }
            JSONArray jsonArray = JSONUtil.parseArray(items);
            if (StrUtil.isNotBlank(parentCode)) {
                nettyServerHandler.stationRobotService.sendParentData(map.get("ReceiveCode").toString(), parentCode, Type, Command, Code, jsonArray.toString());
            }
            //            nettyServerHandler.stationRobotService.sendParentData(map.get("ReceiveCode").toString(),
//                    nettyServerHandler.parentConfig.getParentId(), Type, Command, Code, jsonArray.toString());
            log.info("机器人或无人机发送告警信息！状态{}", Type);
        }

        // 机器人或无人机主动发送环境信息
        if (SystemCode.TYPE_ENVIRONMENT_CODE.getCode().equals(Type)) {
            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, msg, reponsexml);
            List<Map<String, String>> items = (List<Map<String, String>>) map.get("Items");
            JSONArray jsonArray = JSONUtil.parseArray(items);
            //                        nettyServerHandler.stationRobotService.sendParentData(map.get("ReceiveCode")
            //                        .toString(),
            //                                nettyServerHandler.parentConfig.getParentId(), Type, Command, Code,
            //                                jsonArray
            //                                .toString());
            for (Map<String, String> item : items) {
                JSONObject jsonObject = JSONUtil.parseObj(item);
                WeatherLog weatherLog = JSONUtil.toBean(jsonObject, WeatherLog.class);
                String patroldeviceCode = weatherLog.getPatroldeviceCode();
                SubstationPatroldevice substationPatroldevice =
                        nettyServerHandler.substationPatroldeviceService.getOne(new
                                LambdaQueryWrapper<SubstationPatroldevice>().eq
                                (SubstationPatroldevice::getPatroldeviceCode, patroldeviceCode));
                if (substationPatroldevice != null) {
                    // 设备id
                    weatherLog.setPatroldeviceId(substationPatroldevice.getPatroldeviceId());
                    // 变电站id
                    weatherLog.setStationId(substationPatroldevice.getStationId());
                    // 变电站编码
                    weatherLog.setStationCode(substationPatroldevice.getStationCode());
                    // 变电站名称
                    weatherLog.setStationName(substationPatroldevice.getStationName());
                    weatherLog.setDatastatus("1");
                    weatherLog.setLastmodifier(substationPatroldevice.getPatroldeviceName());
                    weatherLog.setLastmodifydate(LocalDateTime.now());
                    // 同步最新环境数据
                    LambdaUpdateWrapper<WeatherLog> updateWrapper = new LambdaUpdateWrapper<>();
                    updateWrapper.eq(WeatherLog::getType, weatherLog.getType()).set
                            (WeatherLog::getDatastatus, 0);
                    nettyServerHandler.weatherLogService.update(updateWrapper);
                    nettyServerHandler.weatherLogService.save(weatherLog);

                    WebSocketServer.sendInfo("vibe_run_data", jsonObject.toString());
                }

            }
            //            nettyServerHandler.stationRobotService.sendParentData(map.get("ReceiveCode").toString(),
            //                    nettyServerHandler.parentConfig.getParentId(), Type, Command, Code, jsonArray
            //                    .toString());
//            if (StrUtil.isNotBlank(parentCode)) {
//                nettyServerHandler.stationRobotService.sendParentData(map.get("ReceiveCode").toString(), parentCode, Type, Command, Code, jsonArray.toString());
//            }
            log.info("机器人主动发送环境信息！状态{}", Type);
        }

        // 任务进度
        if (SystemCode.TYPE_TASK_STATUS_CODE.getCode().equals(Type) && StrUtil.isBlank(Command)) {
            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, msg, reponsexml);
            List<Map<String, String>> items = (List<Map<String, String>>) map.get("Items");
            for (Map<String, String> item : items) {
                TaskTodo taskTodo = BeanUtil.toBean(item, TaskTodo.class);
                // 如果用分析主机，加上这个判断
                String taskTodoId = item.get("task_patrolled_id");
                taskTodo.setTaskTodoId(taskTodoId);
                String taskCode = taskTodo.getTaskCode();
                Task task = nettyServerHandler.taskService.getOne(new LambdaQueryWrapper<Task>().eq(Task::getTaskCode, taskCode));
                if (task == null) {
//                    Task task1 = new Task();
//                    String id = UUID.randomUUID().toString();
//                    task1.setTaskId(id);
//                    task1.setTaskCode(taskTodo.getTaskCode());
//                    task1.setTaskName(taskTodo.getTaskName());
//                    task1.setTaskClass("2");
//                    task1.setFixedStartTime(taskTodo.getPlanStartTime());
//                    task1.setTaskType("1");
//                    task1.setTaskTodoType("2");
//                    task1.setType("1");
//                    task1.setLastmodifydate(new Timestamp(System.currentTimeMillis()));
//                    task1.setLastmodifier("机器人系统");
//                    task1.setIsenable("1");
                    continue;
                }
                taskTodo.setTaskId(task.getTaskId());
                taskTodo.setStationCode(task.getStationCode());
                taskTodo.setTaskType(task.getTaskType());
                taskTodo.setType(task.getType());
                taskTodo.setPriority(task.getPriority());
                taskTodo.setRobotCode(task.getRobotCode());
                if ("100".equals(taskTodo.getTaskProgress())) {
                    taskTodo.setEndTime(DateUtil.now());
                }
                String deviceList = task.getDeviceList();
                //                String[] split = deviceList.split(",");
                List<String> idList = StrUtil.split(deviceList, ",");
                int count =
                        nettyServerHandler.substationDeviceService.count(new LambdaQueryWrapper<SubstationDevice>().in(SubstationDevice::getDeviceId, idList).ne(SubstationDevice::getRecognitionTypeList, "t_100"));
                taskTodo.setDeviceSumnum(count);
                taskTodo.setDatastatus("1");
                taskTodo.setLastmodifier("机器人系统");
                taskTodo.setLastmodifydate(new Timestamp(System.currentTimeMillis()));
                nettyServerHandler.taskTodoService.saveOrUpdate(taskTodo);
                //                // 判断数据库中存在于此相同的任务，但不是同一时间的，不操作到数据库
                //                String compare = StrUtil.sub(taskTodoId, 0, taskTodoId.length() - 6);
                //                LambdaQueryWrapper<TaskTodo> queryWrapper = new LambdaQueryWrapper<>();
                //                queryWrapper.like(TaskTodo::getTaskTodoId, compare);
                //                List<TaskTodo> taskTodoList = nettyServerHandler.taskTodoService.list(queryWrapper);
                //                if (taskTodoList.size() == 1) {
//                    TaskTodo taskTodo1 = taskTodoList.get(0);
//                    if (!taskTodoId.equals(taskTodo1.getTaskId())) {
//                        return;
//                    }
//                }
//                taskTodo.setTaskTodoId(taskTodoId);
//                List<Task> list =
//                        nettyServerHandler.taskService.list(new LambdaQueryWrapper<Task>().eq(Task::getTaskCode,
//                                taskTodo.getTaskCode()));
//                // 获取任务信息
//                if (list.size() > 0) {
//                    Task task = list.get(0);
//                    String deviceList = task.getDeviceList();
//                    String[] split = deviceList.split(",");
//                    taskTodo.setDeviceSumnum(split.length);
//                    taskTodo.setStationCode(task.getStationCode());
//                    taskTodo.setTaskId(task.getTaskId());
//                    taskTodo.setTaskCode(task.getTaskCode());
//                    taskTodo.setTaskName(task.getTaskName());
//                    taskTodo.setTaskType(task.getTaskType());
//                    taskTodo.setType(task.getType());
//                    taskTodo.setPriority(task.getPriority());
//                    taskTodo.setRobotCode(task.getRobotCode());
//                }
//                taskTodo.setDatastatus("1");
//                taskTodo.setLastmodifier("机器人系统");
//                taskTodo.setLastmodifydate(new Timestamp(System.currentTimeMillis()));
//                String callAnalyse = nettyServerHandler.httpServerConfig.getCallAnalyse();
//                // 判断是否调用分析
//                if ("false".equals(callAnalyse)) {
//                    nettyServerHandler.taskTodoService.saveOrUpdate(taskTodo);
//                }
//                if ("true".equals(callAnalyse) && "0".equals(taskTodo.getTaskProgress())) {
//                    nettyServerHandler.taskTodoService.saveOrUpdate(taskTodo);
//                }
                WebSocketServer.sendInfo("taskresult_" + taskTodo.getStationCode(), "msg");

            }
            JSONArray jsonArray = JSONUtil.parseArray(items);
            // 向上级发送
//            nettyServerHandler.stationRobotService.sendParentData(map.get("ReceiveCode").toString(),
//                    nettyServerHandler.parentConfig.getParentId(), Type, Command, Code, jsonArray.toString());
//            if (StrUtil.isNotBlank(parentCode)) {
//                nettyServerHandler.stationRobotService.sendParentData(map.get("ReceiveCode").toString(), parentCode, Type, Command, Code, jsonArray.toString());
//            }
            log.info("机器人或无人机发送任务进度！状态{}", Type);
        }

//        if ("41".equals(Type) && "4".equals(Command)) {
//            String loginfo = String.format("巡视主机向机器人[%s]下发了控制巡视任务控制指令！", robotIp);
//            //暂停、  恢复 、终止 修改数据库状态；
//            //刷新一下界面SSE
//            WebSocketServer.sendInfo("taskresult_" + map.get("SendCode").toString(), "msg");
//        }

        // 巡视结果
        if (SystemCode.TYPE_TASK_RESULT_CODE.getCode().equals(Type)) {
            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, msg, reponsexml);
            List<Map<String, String>> items = (List<Map<String, String>>) map.get("Items");
            for (Map<String, String> item : items) {
                TaskResult taskResult = BeanUtil.toBean(item, TaskResult.class);
                String taskTodoId = item.get("task_patrolled_id");
                TaskTodo taskTodo = nettyServerHandler.taskTodoService.getById(taskTodoId);
                if (taskTodo == null) {
                    continue;
                }
                String deviceId = taskResult.getDeviceId();
                // 获取点位
                SubstationDevice substationDevice = nettyServerHandler.substationDeviceService.getById(deviceId);
                taskResult.setStationCode(substationDevice.getStationCode());
                taskResult.setAreaId(substationDevice.getAreaId());

                String resultId = taskResult.getResultId();
                if (StrUtil.isBlank(resultId)) {
                    taskResult.setResultId(IdUtil.simpleUUID());
                }
                taskResult.setAreaName(substationDevice.getAreaName());
                taskResult.setBayId(substationDevice.getBayId());
                taskResult.setBayName(substationDevice.getBayName());
                taskResult.setMainDeviceId(substationDevice.getMainDeviceId());
                taskResult.setIsAlarm(substationDevice.getIsAlarm());
                taskResult.setRobotCode(taskTodo.getRobotCode());
                taskResult.setMainDeviceName(substationDevice.getMainDeviceName());
                taskResult.setComponentId(substationDevice.getComponentId());
                taskResult.setComponentName(substationDevice.getComponentName());
                String filePath = taskResult.getFilePath();
                String[] split = filePath.split(",");
                Thread.sleep(3000);
                String filePath1 = split[0];
                String filePath2 = filePath1.replace(".jpeg", ".jpg");
                cn.hutool.core.io.FileUtil.touch(nettyServerHandler.httpServerConfig.getSnapFilePath() + filePath2);
                cn.hutool.core.io.FileUtil.copy(nettyServerHandler.httpServerConfig.getSnapFilePath() + filePath1,
                        nettyServerHandler.httpServerConfig.getSnapFilePath() + filePath2, true);
                if (split.length == 1) {
                    taskResult.setFilePath(URLEncoder.encode(filePath2, "utf-8"));
                    taskResult.setDefectFilePath(URLEncoder.encode(filePath2, "utf-8"));
                }
                if (split.length == 2) {
                    taskResult.setFilePath(URLEncoder.encode(filePath2, "utf-8"));
                    taskResult.setDefectFilePath(URLEncoder.encode(split[1], "utf-8"));
                }
                taskResult.setTaskTodoId(taskTodoId);
                String recognitionType = taskResult.getRecognitionType();
                taskResult.setDesc(taskResult.getValue());
                if ("1".equals(recognitionType)) {
                    taskResult.setValueType("meter");
                } else if ("4".equals(recognitionType)) {
                    taskResult.setValueType("infrared");
                } else {
                    List<Map<String, Object>> mapList =
                            nettyServerHandler.taskResultMapper.getValueByDeviceId(deviceId);
                    if (mapList.size() > 0) {
                        Map<String, Object> dataResult = mapList.get(0);
                        log.info("========================" + dataResult.toString());
                        String dataResultId = dataResult.get("dataResultId").toString();
                        List<SysDictionaryItems> sysDictionaryItems =
                                nettyServerHandler.sysDictionaryItemsService.list(new LambdaQueryWrapper<SysDictionaryItems>().eq(SysDictionaryItems::getDictId, "f6c757b42cbcd9281fe4a53d1f8cb4fa").eq(SysDictionaryItems::getItemCode, dataResultId));
                        if (sysDictionaryItems.size() > 0) {
                            SysDictionaryItems dictionaryItems = sysDictionaryItems.get(0);
                            log.info("========================" + dictionaryItems.getCustom1());
                            String results = dictionaryItems.getCustom1();
                            JSONArray jsonArray = JSONUtil.parseArray(results);
                            List<Object> minVal =
                                    jsonArray.stream().filter(j -> JSONUtil.parseObj(j).getStr("MinVal").equals(taskResult.getValue())).collect(Collectors.toList());
                            JSONObject o = JSONUtil.parseObj(minVal.get(0));
                            String showInfo = o.getStr("ShowInfo");
                            log.info("========================" + showInfo);
                            taskResult.setDesc(showInfo);
                        }
                    }
                }
                String deviceCode = substationDevice.getDeviceCode();
                List<String> codeList = Arrays.asList("50010", "50011", "50024", "50025", "50040","50041");
                boolean iscall=true;
                if(codeList.contains(deviceCode)){
                    taskResult.setValue("1");
                    taskResult.setDesc("");
                    taskResult.setValid("1");
                    iscall=false;
                }

                taskResult.setConf(taskResult.getValue());
                taskResult.setPatroldeviceDate(taskResult.getTime());
//                taskResult.setDesc(taskResult.getValue());
                taskResult.setFlag("2");
                taskResult.setDatastatus("1");
                taskResult.setLastmodifier("机器人系统");
                taskResult.setLastmodifydate(new Timestamp(System.currentTimeMillis()));
                LambdaQueryWrapper<TaskResult> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(TaskResult::getTaskTodoId, taskResult.getTaskTodoId()).eq(TaskResult::getDeviceId,
                        taskResult.getDeviceId());
                List<TaskResult> taskResultList = nettyServerHandler.taskResultMapper.selectList(queryWrapper);
                String callAnalyse = nettyServerHandler.httpServerConfig.getCallAnalyse();
                try {
                    if (taskResultList.size() > 0) {
                        TaskResult taskResult1 = taskResultList.get(0);
                        taskResult.setResultId(taskResult1.getResultId());
                        nettyServerHandler.taskResultMapper.updateById(taskResult);
                    } else {
                        nettyServerHandler.taskResultMapper.insert(taskResult);
                    }

                    if (iscall&&"true".equals(callAnalyse) && !"4".equals(taskResult.getRecognitionType())) {
                        com.alibaba.fastjson.JSONObject customParams = new com.alibaba.fastjson.JSONObject();
                        //表计类型
                        if (ObjectUtil.isNotEmpty(substationDevice.getMeterType())) {
                            customParams.put("meterType", substationDevice.getMeterType());

                        }
                        String outsideAngle = substationDevice.getOutsideAngle();
                        if (StrUtil.isNotEmpty(outsideAngle)) {
                            customParams.put("TempAngleList", outsideAngle);
                        }

                        if (ObjectUtil.isNotEmpty(substationDevice.getOutsideAngle())) {
                            if (JSONUtil.isTypeJSONArray(substationDevice.getOutsideAngle())) {
                                JSONArray jsonArray = JSONUtil.parseArray(substationDevice.getOutsideAngle());
                                customParams.put("TempAngleList", jsonArray);
                            }

                        }

                        //基准图
                        if (ObjUtil.isNotEmpty(taskResult.getPatroldeviceBaseimage())) {
                            customParams.put("imageNormalUrlPath", taskResult.getPatroldeviceBaseimage());
                        }
                        //有效识别区域
                        if (ObjUtil.isNotEmpty(taskResult.getPatroldeviceEffectiveregion())) {
                            customParams.put("effectiveregion", taskResult.getPatroldeviceEffectiveregion());
                        }

                        JSONArray typelist = new JSONArray();

                        if (StrUtil.isNotEmpty(substationDevice.getPictureAnalysisTypeList())) {
                            com.alibaba.fastjson.JSONObject jobj =
                                    JSON.parseObject(substationDevice.getPictureAnalysisTypeList());
                            if (ObjectUtil.isNotEmpty(jobj.getString("PictureAnalysisType"))) {
                                if ("meter".equals(jobj.getString("PictureAnalysisType"))) {
                                    customParams.put("meterType", substationDevice.getOutsideFeature());
                                }
                                typelist.add(jobj.getString("PictureAnalysisType"));
                            }
                            if (ObjectUtil.isNotEmpty(jobj.getString("PictureDefectAnalysisType"))) {
                                typelist.add(jobj.getString("PictureDefectAnalysisType"));
                            }

                            if (ObjectUtil.isNotEmpty(jobj.getString("PictureDefectAnalysisType"))) {
                                JSONArray defectresult = new JSONArray();
                                List<String> pictureType = StrUtil.split(jobj.getString("PictureDefectAnalysisType"), ",");
                                List<Map<String, Object>> pictureDefectAnalysisType =
                                        nettyServerHandler.sysDictionaryItemsService.getDeviceByType(
                                                "PictureDefectAnalysisType");
                                // 获取到子项
                                List<String> itemCodeList =
                                        pictureDefectAnalysisType.stream().filter(p -> pictureType.contains(p.get(
                                                "itemcode").toString())).map(m -> m.get("custom1").toString()).collect(Collectors.toList());

                                for (String code : itemCodeList) {
                                    JSONArray jsonArray = JSONUtil.parseArray(code);
                                    defectresult.addAll(jsonArray);
                                    List<String> keyList =
                                            jsonArray.stream().map(j -> JSONUtil.parseObj(j).getStr("key")).collect(Collectors.toList());
                                    typelist.addAll(keyList);
                                }
                                if (defectresult.size() > 0) {
                                    //缺陷识别结果类型
                                    customParams.put("defectresulttypes", defectresult);
                                }
                            }
                            if (ObjectUtil.isNotEmpty(jobj.getString("PictureDiscriminateAnalysisType"))) {
                                typelist.add(jobj.getString("PictureDiscriminateAnalysisType"));
                            }
                        }
                        if (typelist.size() == 0) {
                            throw new Exception("未设置识别方式，不能进行图形识别！");
                        }
                        com.alibaba.fastjson.JSONObject callresult =
                                nettyServerHandler.httpRESTfulUtils.callPicAnalyse(taskResult
                                                .getTaskTodoId(),
                                        taskResult.getResultId(), JSONUtil.toJsonStr(typelist),
                                        JSONUtil.toJsonStr(customParams), filePath2);
                        //                    com.alibaba.fastjson.JSONObject callresult =
                        //                            nettyServerHandler.httpRESTfulUtils.callPicAnalyse(taskResult.getTaskTodoId(),
                        //                                    taskResult.getResultId(), filePath2, substationDevice.getDeviceName());
                    }

                    WebSocketServer.sendInfo("taskresult_" + taskResult.getStationCode(), "msg");
                }catch (Exception e){
                    log.error(e.getMessage());;
                }

            }
            // 向上级发送
//            JSONArray jsonArray = JSONUtil.parseArray(items);

//            nettyServerHandler.stationRobotService.sendParentData(map.get("ReceiveCode").toString(),
//                    nettyServerHandler.parentConfig.getParentId(), Type, Command, Code, jsonArray
//                            .toString());
//            if (StrUtil.isNotBlank(parentCode)) {
//                nettyServerHandler.stationRobotService.sendParentData(map.get("ReceiveCode").toString(), parentCode, Type, Command, Code, jsonArray.toString());
//            }
            log.info("机器人或无人机发送巡视结果！状态{}", Type);
        }


        // 无人机机巢发送运行数据
        if (SystemCode.TYPE_NEST_RUN_CODE.getCode().equals(Type)) {
            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, msg, reponsexml);
            List<Map<String, String>> items = (List<Map<String, String>>) map.get("Items");
            JSONArray jsonArray = JSONUtil.parseArray(items);
            // 向上级发送
//            nettyServerHandler.stationRobotService.sendParentData(map.get("ReceiveCode").toString(), nettyServerHandler.parentConfig.getParentId(), Type, Command, Code, jsonArray.toString());
            log.info("无人机机巢主动发送自身状态！状态{}", Type);
        }

        // 无人机机巢状态数据
        if (SystemCode.TYPE_NEST_STATUS_CODE.getCode().equals(Type)) {
            log.info("无人机机巢主动发送自身状态！状态{}", Type);
            List<Map<String, String>> items = (List<Map<String, String>>) map.get("Items");
            JSONArray jsonArray = JSONUtil.parseArray(items);
            // 向上级发送
//            nettyServerHandler.stationRobotService.sendParentData(map.get("ReceiveCode").toString(), nettyServerHandler.parentConfig.getParentId(), 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, msg, reponsexml);
        }

    }

    /**********************************
     * 用途说明: 发送响应数据
     * 参数说明 ctx
     * 参数说明 msg
     * 参数说明 reponsexml
     * 返回值说明: void
     ***********************************/
    public void sendResponseData(ChannelHandlerContext ctx, MyMessageProtocol msg, String 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();
    }

    /**********************************
     * 用途说明: 生成报警记录(点位)
     * 参数说明 taskResult
     * 参数说明 map
     * 返回值说明: boolean
     ***********************************/
    private boolean createTaskAlarmLog(TaskResult taskResult, Map<String, Object> map) throws UnsupportedEncodingException {
        AlarmLog alarmLog = new AlarmLog();
        alarmLog.setId(IdUtil.fastSimpleUUID());
        String deviceid = taskResult.getDeviceId();
        SubstationDevice device = nettyServerHandler.substationDeviceService.getById(deviceid);
        String alarmDate = DateUtil.now();
        Substation substation = nettyServerHandler.substationService.getOne(new LambdaQueryWrapper<Substation>().
                eq(Substation::getStationCode, device.getStationCode()));
        alarmLog.setStationCode(device.getStationCode());
        alarmLog.setStationId(substation.getStationId());
        alarmLog.setStationName(substation.getStationName());
        alarmLog.setAreaId(taskResult.getAreaId());
        alarmLog.setAreaName(taskResult.getAreaName());
        alarmLog.setBayId(taskResult.getBayId());
        alarmLog.setBayName(taskResult.getBayName());
        alarmLog.setMainDeviceId(taskResult.getMainDeviceId());
        alarmLog.setMainDeviceName(taskResult.getMainDeviceName());
        alarmLog.setComponentId(taskResult.getComponentId());
        alarmLog.setComponentName(taskResult.getComponentName());
        alarmLog.setDeviceId(taskResult.getDeviceId());
        alarmLog.setDeviceName(taskResult.getDeviceName());
        alarmLog.setPatroldeviceCode(taskResult.getPatroldeviceCode());
        alarmLog.setPatroldeviceName(taskResult.getPatroldeviceName());
        alarmLog.setMaterialId(taskResult.getMaterialId());
        TaskTodo taskTodo = nettyServerHandler.taskTodoService.getById(taskResult.getTaskTodoId());
        alarmLog.setTaskId(taskTodo.getTaskId());
        alarmLog.setTaskPatrolledId(taskResult.getTaskTodoId());
        alarmLog.setTaskResultId(taskResult.getResultId());
        alarmLog.setTaskCode(taskResult.getTaskCode());
        alarmLog.setTaskName(taskResult.getTaskName());
        alarmLog.setTaskAlarmType("1"); //'1:巡视任务告警；2:静默任务告警，3：巡视设备告警',
        //alarmLog.setMonitorType("");//非静默监视不填
        alarmLog.setAlarmType(ObjUtil.isNotEmpty(map.get("alarmtype")) ? map.get("alarmtype").toString() : "");
        //'字典表<1>: = 超温报警<2>: = 温升报警<3>: = 三相温差报警<4>: = 三相对比报警<5>: = 声音异常<6>: = 外观异常<7>: = 仪表越限报警<8>: = 仪表超量程报警<9>: =
        // 仪表三相对比<10>: = 变位报警',
        alarmLog.setAlarmLevel(ObjUtil.isNotEmpty(map.get("alarmlevel")) ? map.get("alarmlevel").toString() : "3");//
        // '1:预警；2:一般；3:严重；4;危急',  待判断细分
        alarmLog.setRecognitionType(taskResult.getRecognitionType());//'1:表计读取；2:位置状态识别；3:设备外观查看；4:红外测温；5:声音检测；6
        // :闪烁检测11:局放超声波检测12:局放地电压检测13:局放特高频检测101:环境温度检测102:环境湿度检测103:氧气浓度检测104SF6浓度检测',
        alarmLog.setFileType(taskResult.getFileType());//'1:红外图谱；2:可见光照片；3:音频4:视频5:识别图片，存在多个文件，文件类型用逗号分隔',
        //告警文件目录规范：地市名/区域名/变电站名/分类/年月
        String type = "缺陷";//缺陷、判别
        String alarmfilepath = String.format("%s/%s/%s/%s/%s/",
                substation.getCityName(),
                substation.getSectionName(),
                substation.getStationName(),
                type,
                DateUtil.format(DateUtil.date(), "yyyyMM")
        );
        //拷贝原图到报警目录下
        String fullfilename = URLDecoder.decode(taskResult.getFilePath(), "utf-8");
        String alarmfullfilename = alarmfilepath + StrUtil.subAfter(fullfilename, "/", true);
        FileUtil.copy(nettyServerHandler.httpServerConfig.getSnapFilePath() + fullfilename,
                nettyServerHandler.httpServerConfig.getAlarmFilePath() + alarmfullfilename, true);
        alarmLog.setFilePath(URLEncoder.encode(alarmfullfilename, "utf-8"));//原图文件名称（含路径）
        alarmLog.setDefectType(taskResult.getValueType());//'缺陷类别'
        //拷贝识别图到报警目录下
        if (ObjUtil.isNotEmpty(taskResult.getDefectFilePath())) {
            String fulldefectfilename = URLDecoder.decode(taskResult.getDefectFilePath(), "utf-8");
            String alarmfilename = StrUtil.replace(StrUtil.subAfter(fulldefectfilename, "/", true), "识别", "缺陷告警");
            String fullalarmfile = alarmfilepath + alarmfilename;
            FileUtil.copy(nettyServerHandler.httpServerConfig.getSnapFilePath() + fulldefectfilename,
                    nettyServerHandler.httpServerConfig.getAlarmFilePath() + fullalarmfile,
                    true);
            alarmLog.setDefectFilePath(URLEncoder.encode(fullalarmfile, "utf-8"));//标注了识别框和信息
        }
        alarmLog.setValue(taskResult.getValue());//图形识别结果（值）
        alarmLog.setUnit(taskResult.getUnit());
        String alarminfo = "";
        String value = taskResult.getValue();
        String unit = "";
        if (StrUtil.isNotBlank(taskResult.getUnit())) {
            unit = taskResult.getUnit();
        }
        if ("meter".equals(taskResult.getValueType())) {
            alarminfo = String.format("%s-%s的%s，识别结果为%s%s，判定为[%s]超限缺陷！", taskResult.getMainDeviceName(),
                    taskResult.getComponentName(), taskResult.getDeviceName(), value,
                    unit, taskResult.getDesc());
        }
        if ("infrared".equals(taskResult.getValueType())) {
            alarminfo = String.format("%s-%s的%s，识别温度：%s单位：%s，判定为[%s]超限缺陷！", taskResult.getMainDeviceName(),
                    taskResult.getComponentName(), taskResult.getDeviceName(), value,
                    unit, taskResult.getDesc());
        }
        if ("sound".equals(taskResult.getValueType())) {
            alarminfo = "声音检测异常！";
        }
        if (StrUtil.isBlank(alarminfo)) {
            alarminfo = String.format("%s-%s的%s，识别结果为%s%s，判定为[%s]异常！", taskResult.getMainDeviceName(),
                    taskResult.getComponentName(), taskResult.getDeviceName(), value, unit
                    , taskResult.getDesc());
        }
        alarmLog.setContent(alarminfo);//告警描述信息
        alarmLog.setAlarmDate(alarmDate);//发送报警时间
        alarmLog.setCheckFlag("0");//'0:未核查；1:已审核；2.已修正'
        alarmLog.setRectangle(taskResult.getRectangle());//'格式：x1,y1,x2y2;x3,y3,x4,y4；多个报警框的左上角和右下角坐标'
        alarmLog.setDatastatus("1"); //初始创建
        alarmLog.setLastmodifier("系统创建");
        alarmLog.setLastmodifydate(new Timestamp(DateUtil.current()));
        nettyServerHandler.alarmLogService.save(alarmLog);//保存此报警数据
        LocalDateTime delayedAlarmDate = device.getDelayedAlarmDate();
        // 如果当前时间小于报警延迟时间则不报警
        if (delayedAlarmDate != null) {
            LocalDateTime parse = LocalDateTimeUtil.parse(alarmDate, "yyyy-MM-dd HH:mm:ss");
            if (!parse.isAfter(delayedAlarmDate)) {
                return true;
            }
        }
        Map<String, Object> logMap = BeanUtil.beanToMap(alarmLog);
        String stationId = alarmLog.getStationId();
        LambdaQueryWrapper<AlarmLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AlarmLog::getDatastatus, "1").eq(AlarmLog::getStationId, stationId).eq(AlarmLog::getCheckFlag
                , 0);
        int count = nettyServerHandler.alarmLogService.count(queryWrapper);
        logMap.put("alarmCount", count);
        JSONObject jsonObject = new JSONObject(logMap);
        String stationCode = substation.getStationCode();
        jsonObject.putOpt("deviceid", jsonObject.getStr("deviceId"));
        //        if (ObjectUtil.isNotEmpty(map.get("patroldeviceCode")) && ObjectUtil.isNotEmpty(map.get(
        //                "patroldeviceChannelcode"))) {
        //            jsonObject.putOpt("channelId", map.get("patroldeviceChannelcode").toString());
        //            jsonObject.putOpt("deviceId", map.get("patroldeviceCode").toString());
        //        }
        jsonObject.putOpt("channelId", taskResult.getPatroldeviceChannelcode());
        jsonObject.putOpt("deviceId", taskResult.getPatroldeviceCode());
        List<AlarmThreshold> list =
                alarmThresholdService.list(new LambdaQueryWrapper<AlarmThreshold>().eq(AlarmThreshold::getDeviceId,
                        deviceid));
        // 告警阈值
        if (list.size() > 0) {
            Map<String, String> thresholdInterval = alarmThresholdService.getThresholdInterval(deviceid);
            jsonObject.putAll(thresholdInterval);
        }
        // 如果是站端则区域也需要发送告警
        WebSocketServer.sendInfo(stationId, jsonObject.toString());
        return true;
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // 连接不活跃，可能是客户端或服务器关闭了连接
        log.error("===================Client disconnected from server=======================");
        // 在这里你可以进行清理工作，比如关闭资源
        LambdaQueryWrapper<SubstationPatroldevice> queryWrapper = new LambdaQueryWrapper<>();
        String robotIp = ctx.channel().remoteAddress().toString().substring(1).split(":")[0];
        queryWrapper.eq(SubstationPatroldevice::getIpaddr, robotIp);
        List<SubstationPatroldevice> list = nettyServerHandler.substationPatroldeviceService.list(queryWrapper);
        if (list.size() > 0) {
            SubstationPatroldevice substationPatroldevice = list.get(0);
            JSONArray jsonArray = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            jsonObject.putOpt("patroldevice_name", substationPatroldevice.getPatroldeviceName());
            jsonObject.putOpt("patroldevice_code", substationPatroldevice.getPatroldeviceCode());
            jsonObject.putOpt("time", DateUtil.now());
            jsonObject.putOpt("type", "301");
            jsonObject.putOpt("value", "1");
            jsonObject.putOpt("unit", "");
            jsonObject.putOpt("value_unit", "异常");
            jsonArray.add(jsonObject);
            WebSocketServer.sendInfo("robot_status_data", jsonArray.toString());
        }
    }

    /**
     * 发生异常触发
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        String robotIp = ctx.channel().remoteAddress().toString().substring(1).split(":")[0];
        nettyServerHandler.stationRobotService.updateRobotOnline(robotIp, "0");
        LambdaQueryWrapper<SubstationPatroldevice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SubstationPatroldevice::getIpaddr, robotIp);
        List<SubstationPatroldevice> list = nettyServerHandler.substationPatroldeviceService.list(queryWrapper);
        if (list.size() > 0) {
            SubstationPatroldevice substationPatroldevice = list.get(0);
            JSONArray jsonArray = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            jsonObject.putOpt("patroldevice_name", substationPatroldevice.getPatroldeviceName());
            jsonObject.putOpt("patroldevice_code", substationPatroldevice.getPatroldeviceCode());
            jsonObject.putOpt("time", DateUtil.now());
            jsonObject.putOpt("type", "301");
            jsonObject.putOpt("value", "1");
            jsonObject.putOpt("unit", "");
            jsonObject.putOpt("value_unit", "异常");
            jsonArray.add(jsonObject);
            WebSocketServer.sendInfo("robot_status_data", jsonArray.toString());
        }
        ctx.close();
        ChannelMap.getChannelMap().remove(robotIp);
        log.error(cause.getMessage());
        log.info("客户端异常断开连接：{}", cause.getMessage());
    }


}



