package com.yfd.platform.modules.robotapi.service.impl;

import cn.hutool.core.date.DateUtil;
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.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yfd.platform.component.WebSocketServer;
import com.yfd.platform.component.nettyclient.BootNettyClientChannel;
import com.yfd.platform.component.nettyclient.BootNettyClientChannelCache;
import com.yfd.platform.component.nettyclient.BootNettyClientThread;
import com.yfd.platform.component.nettyserver.BootSessionCache;
import com.yfd.platform.component.nettyserver.ChannelMap;
import com.yfd.platform.component.nettyserver.MyMessageProtocol;
import com.yfd.platform.component.nettyserver.MyXmlUtil;
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.mapper.*;
import com.yfd.platform.modules.patroltask.domain.ExaminePlan;
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.ExaminePlanMapper;
import com.yfd.platform.modules.patroltask.mapper.TaskMapper;
import com.yfd.platform.modules.patroltask.mapper.TaskResultMapper;
import com.yfd.platform.modules.patroltask.service.ITaskTodoService;
import com.yfd.platform.modules.robotapi.service.IStationRobotService;
import com.yfd.platform.utils.FileUtil;
import io.netty.channel.Channel;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.*;

/**
 * <p>
 * 巡视任务表 服务实现类
 * </p>
 *
 * @since 2023-04-08
 */
@Service
@Slf4j
public class StationRobotServiceImpl extends ServiceImpl<SubstationMapper, Substation> implements IStationRobotService {

    @Resource
    private SubstationMapper substationMapper;

    @Resource
    private HttpServerConfig serverConfig;
    @Resource
    private SubstationDeviceMapper substationDeviceMapper;
    @Resource
    private SubstationPatroldeviceMapper substationPatroldeviceMapper;
    @Resource
    private TaskMapper taskMapper;
    @Resource
    private ITaskTodoService taskTodoService;
    @Resource
    private TaskResultMapper taskResultMapper;
    @Resource
    private ExaminePlanMapper examinePlanMapper;
    @Resource
    private LinkageSignalMapper linkageSignalMapper;
    @Resource
    private ParentConfig parentConfig;

    @Resource
    private RedisTemplate<Object, Object> redisTemplate;

    @Value("${file-space.confirmfilepath}")
    private String confirmfilepath;

    @Value("${file-space.system}")
    private String systempath;


    @Override
    public boolean updateRobotOnline(String robotIp, String online) {
        LambdaUpdateWrapper<SubstationPatroldevice> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SubstationPatroldevice::getIpaddr, robotIp).set(SubstationPatroldevice::getOnline, online);
        substationPatroldeviceMapper.update(null, updateWrapper);
        return true;
    }

    @Override
    public boolean sendMsgOfSyncBaseData(String stationcode) {
        //根据变电站编号获取变电站对象信息
        List<Substation> list = substationMapper.selectByStaionCode(stationcode);
        if (list.size() == 0) {
            return false;
        }
        Substation substation = list.get(0);

        //向机器人发送基础数据同步指令
        sendMsgtoRobot(substation.getStationIp(), serverConfig.getPatrolServerid(), substation.getNodeId(), "250",
                "1", stationcode, null);

        return true;
    }

    @Override
    public void sendCommand(String targetId, String sendcode, String receivecode, String type, String command,
                            String code, String items) {
        log.info("进入sendCommand方法");
        if (StrUtil.isBlank(targetId)) {
            log.info("判断机器人");
            // 机器人编码
            List<SubstationPatroldevice> list =
                    substationPatroldeviceMapper.selectList(new LambdaQueryWrapper<SubstationPatroldevice>().eq(SubstationPatroldevice::getPatroldeviceCode, code));
            // 发送机器人控制指令
            if (list.size() > 0) {
                SubstationPatroldevice substationPatroldevice = list.get(0);
                sendMsgtoRobot(substationPatroldevice.getInternationalId(), sendcode, substationPatroldevice.getInternationalId(), type, command, code, items);
            }
        } else {
            sendMsgtoRobot(targetId, sendcode, receivecode, type, command, code, items);
        }


    }

    @Override
    public void sendMsgOfTask(String stationcode, String taskid) {
        //根据变电站编号获取变电站对象信息
        List<Substation> list = substationMapper.selectByStaionCode(stationcode);
        if (list.size() == 0) {
            return;
        }
        Substation substation = list.get(0);

        //根据巡视任务ID获取巡视任务信息
        Task task = taskMapper.selectById(taskid);
        String jsonstr = JSONUtil.toJsonStr(task);

        //向机器人发送巡视任务数据
        sendMsgtoRobot(substation.getStationIp(), serverConfig.getPatrolServerid(), substation.getNodeId(), SystemCode.TYPE_TASK_ISSUED_CODE.getCode(), "1"
                , stationcode, jsonstr);

    }

    @Override
    public void sendMsgOfTaskCommand(String stationcode, String todotaskid, String command) {
        //根据变电站编号获取变电站对象信息
        List<Substation> list = substationMapper.selectByStaionCode(stationcode);
        if (list.size() == 0) {
            return;
        }
        Substation substation = list.get(0);
        //向机器人发送巡视任务数据
        sendMsgtoRobot(substation.getStationIp(), serverConfig.getPatrolServerid(), substation.getNodeId(), SystemCode.TYPE_TASK_CONTROL_CODE.getCode(),
                command, todotaskid, null);

    }

    @Override
    public void sendMsgOfExaminePlan(String stationcode, String planid) {
        //根据变电站编号获取变电站对象信息
        List<Substation> list = substationMapper.selectByStaionCode(stationcode);
        if (list.size() == 0) {
            return;
        }
        Substation substation = list.get(0);

        //根据检修计划 ID获取巡视任务信息
        ExaminePlan plan = examinePlanMapper.selectById(planid);
        String jsonstr = JSONUtil.toJsonStr(plan);

        //向变电站发送检修计划数据
        sendMsgtoRobot(substation.getStationIp(), serverConfig.getPatrolServerid(), substation.getNodeId(), SystemCode.TYPE_EXAMINE_ISSUED_CODE.getCode(), SystemCode.COMMAND_EXAMINE_CONFIG_CODE.getCode()
                , stationcode, jsonstr);
    }

    @Override
    public void sendMsgOfLinkageSignal(String stationcode, String signalid) {
        //根据变电站编号获取变电站对象信息
        List<Substation> list = substationMapper.selectByStaionCode(stationcode);
        if (list.size() == 0) {
            return;
        }
        Substation substation = list.get(0);

        //根据信号ID获取联动信号
        LinkageSignal signal = linkageSignalMapper.selectById(signalid);
        String jsonstr = JSONUtil.toJsonStr(signal);

        //向机器人发送联动信号配置
        sendMsgtoRobot(substation.getStationIp(), serverConfig.getPatrolServerid(), substation.getNodeId(), "71", "1"
                , stationcode, jsonstr);

    }


    /**
     * 机器人发送消息
     *
     * @param targetIp 目标id
     *                 sendcode 发送方GBId
     *                 receivecode  接收方BGId
     *                 type 巡视系统规范中定义
     *                 command 巡视系统中规范定
     *                 code 发送的编码
     *                 items  发送的内容数据信息封装成jsonstr
     */
    private void sendMsgtoRobot(String targetIp, String sendcode, String receivecode, String type, String command,
                                String code, String items) {
        log.info("接收控制值targetip" + targetIp + "接收控制值sendcode" + sendcode + "接收控制值receivecode" + receivecode + "接收控制值items" + items);
        String reponsexml = MyXmlUtil.getXml(sendcode, receivecode, type, command, code, items);
        log.info("主动发送控制命令" + reponsexml);
        MyMessageProtocol messageProtocol = new MyMessageProtocol();
        long requestSessionID = BootSessionCache.getRequestSessionID();
        redisTemplate.opsForValue().set(Constant.ROBOT_SEND_CODE + requestSessionID, reponsexml);
        messageProtocol.setSenderSerialNo(requestSessionID);
        //接收者回复的会话ID，发送时赋0
        messageProtocol.setReceiverSerialNo(0L);
        messageProtocol.setSessionflag(0);
        messageProtocol.setXmllen(reponsexml.getBytes(CharsetUtil.UTF_8).length);
        messageProtocol.setXmlcontent(reponsexml.getBytes(CharsetUtil.UTF_8));
        Channel channel = ChannelMap.getChannel(targetIp);
        if (null == channel) {
            throw new RuntimeException("客户端已离线");
        }
        channel.writeAndFlush(messageProtocol);
    }

    /**********************************
     * 用途说明: 接收任务信息并同步
     * 参数说明 jsonStr
     * 返回值说明: cn.hutool.json.JSONObject
     ***********************************/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public JSONObject getTaskInfo(String jsonStr) {
        JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
        // 向数据库中插入或更新任务
        insertTask(jsonObject);
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.putOpt("code", 200);
        return jsonObject1;
    }

    /**********************************
     * 用途说明: 向数据库中插入或更新任务
     * 参数说明 jsonObject
     * 返回值说明: void
     ***********************************/
    private void insertTask(JSONObject jsonObject) {
        for (String key : jsonObject.keySet()) {
            JSONArray jsonArray = jsonObject.getJSONArray(key);
            if ("task".equals(key)) {
                List<Task> taskList = JSONUtil.toList(jsonArray, Task.class);
                taskMapper.batchAdd(taskList);
            } else if ("task_todo".equals(key)) {
                List<TaskTodo> taskList = JSONUtil.toList(jsonArray, TaskTodo.class);
                taskTodoService.saveOrUpdateBatch(taskList);
            } else if ("task_result".equals(key)) {
                List<TaskResult> taskList = JSONUtil.toList(jsonArray, TaskResult.class);
                taskResultMapper.batchAdd(taskList);
            }
        }
    }

    @Override
    public void createVideocfmresult(String stationcode, String taskcode, String videoresult) throws UnsupportedEncodingException {
        String[] temp = taskcode.split("-");
        //监控索引号
        String monitorindex = temp[0];
        //事件时标
        String eventtime = DateUtil.format(DateUtil.date(Long.parseLong(temp[1])), "yyyy-MM-dd HH:mm:ss.SSS");

        List<Map<String, Object>> tasklist =
                taskMapper.selectMaps(new LambdaQueryWrapper<Task>().eq(Task::getTaskCode, taskcode));
//        String value1 = "";//一键顺控的原始值
        String equip = "";
        List<LinkageSignal> linkageSignals =
                linkageSignalMapper.selectList(new LambdaQueryWrapper<LinkageSignal>().eq(LinkageSignal::getControlNum, monitorindex));
        String stationNum = "";
        if (tasklist.size() > 0) {//任务表
//            value1 = tasklist.get(0).get("custom3").toString();
            if (linkageSignals.size() > 0) {
                LinkageSignal linkageSignal = linkageSignals.get(0);
                stationNum = linkageSignal.getStationNum();
                String linkageDeviceName = linkageSignal.getLinkageDeviceName();
                equip = StrUtil.subBefore(linkageDeviceName, "-", true);
            }
        }
//        String result = "分析识别";
//        if (value1.equals("合位") && videoresult.equals("刀闸关闭")) {
//            result = "合闸正常";
//        }
//        if (value1.equals("合位") && (videoresult.equals("中间状态") || videoresult.equals("刀闸打开"))) {
//            result = "合闸异常";
//        }
//        if (value1.equals("分位") && videoresult.equals("刀闸打开")) {
//            result = "分闸正常";
//        }
//        if (value1.equals("分位") && (videoresult.equals("中间状态") || videoresult.equals("刀闸关闭"))) {
//            result = "分闸异常";
//        }
        String cimfilecontent = getReturnCimFile(stationNum, monitorindex, equip, videoresult, eventtime);
        String filename = confirmfilepath + "videocfmresult.cime";
        FileUtil.writeString(cimfilecontent, filename, Charset.forName("GB2312"));

    }


    /**********************************
     * 用途说明: 向边缘节点发送机器人控制指令
     * 参数说明 jsonStr
     * 返回值说明: void
     ***********************************/
    @Override
    public void sendRobotCommand(String jsonStr) {
        JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
        this.sendCommand("", serverConfig.getPatrolServerid(), serverConfig.getRobotId(), jsonObject.getStr("Type"), jsonObject.getStr("Command"), jsonObject.getStr("Code"), jsonObject.getStr("Items"));
    }

    /**********************************
     * 用途说明: 向上级发送设备状态
     * 参数说明 jsonStr
     * 返回值说明: void
     ***********************************/
    @Override
    public void sendParentData(String SendCode, String ReceiveCode, String Type, String Command, String Code,
                               String Items) throws IOException {

        log.info("向上级系统发送信息SendCode"+SendCode);
        if (StrUtil.isBlank(SendCode)) {
            return;
        }
        String xml = com.yfd.platform.component.nettyclient.MyXmlUtil.getXml(SendCode, ReceiveCode, Type, Command,
                Code, Items);
        WebSocketServer.sendInfo("robotinfo", xml);
        log.info("向上级系统发送信息" + xml);
        com.yfd.platform.component.nettyclient.MyMessageProtocol messageProtocol =
                new com.yfd.platform.component.nettyclient.MyMessageProtocol();
        messageProtocol.setSenderSerialNo(BootSessionCache.getRequestSessionID());
        messageProtocol.setReceiverSerialNo(new Long(0L));
        messageProtocol.setSessionflag(0);
        messageProtocol.setXmllen(xml.getBytes(CharsetUtil.UTF_8).length);
        messageProtocol.setXmlcontent(xml.getBytes(CharsetUtil.UTF_8));
        if (BootNettyClientChannelCache.channelMapCache.size() > 0) {
            for (Map.Entry<String, BootNettyClientChannel> entry :
                    BootNettyClientChannelCache.channelMapCache.entrySet()) {
                BootNettyClientChannel bootNettyChannel = entry.getValue();
                if (bootNettyChannel != null && bootNettyChannel.getChannel().isOpen()) {
                    bootNettyChannel.getChannel().writeAndFlush(messageProtocol);
                } else {
//                    BootNettyClientThread thread = new BootNettyClientThread(parentConfig.getParentIp(),
//                            Integer.parseInt(parentConfig.getTcpPort()), parentConfig);
//                    thread.start();
                    log.error("============================存在通道但是已经关闭============================="+BootNettyClientChannelCache.channelMapCache.size());
                }
            }
        } else {
            log.error("============================没有找到合适的通道============================="+BootNettyClientChannelCache.channelMapCache.size());
//            BootNettyClientThread thread = new BootNettyClientThread(parentConfig.getParentIp(),
//                    Integer.parseInt(parentConfig.getTcpPort()), parentConfig);
//            thread.start();
        }
    }

    /**********************************
     * 用途说明: 上报上级系统
     * 参数说明 ids
     * 参数说明 type
     * 返回值说明: boolean
     ***********************************/
    @Override
    public String reportParentById(String ids, String type) throws IOException {
        String filePath = "";
        List<Map<String, Object>> mapList = new ArrayList<>();
        String xmlPath = "";
        String stationCode="7FE4BB37-F54A-4808-852B-6CAB43DD71B3-00001";
        switch (type) {
            case "1":
                List<Substation> substations =
                        substationMapper.selectList(new LambdaQueryWrapper<Substation>().eq(Substation::getDatastatus
                                , "1"));
                for (Substation substation : substations) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("station_code", substation.getStationCode());
                    map.put("station_name", substation.getStationName());
                    map.put("station_ip", substation.getStationIp());
                    map.put("section_id", substation.getSectionId());
                    map.put("section_name", substation.getSectionName());
                    map.put("station_address", substation.getStationAddress());
                    map.put("volt_level", substation.getVoltLevel());
                    map.put("city_name", substation.getCityName());
                    map.put("province_name", substation.getProvinceName());
                    map.put("company_name", substation.getCompanyName());
                    map.put("contact_phone", substation.getContactPhone());
                    map.put("contact_person", substation.getContactPerson());
                    map.put("introduction", substation.getIntroduction());
                    mapList.add(map);
                }
                filePath = String.format("%s_%s_%s.xml", "host", DateUtil.format(DateUtil.date(), "yyyyMMdd"), DateUtil.format(DateUtil.date(), "HHmmss"));
                xmlPath = serverConfig.getModelPath() + filePath;
                FileUtil.parseNodeToXML(mapList, xmlPath, "Host_Model");
                break;
            case "2":
                List<SubstationPatroldevice> robots =
                        substationPatroldeviceMapper.selectList(new LambdaQueryWrapper<SubstationPatroldevice>().in(SubstationPatroldevice::getType, "1", "2", "3"));
                for (SubstationPatroldevice patroldevice : robots) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("patroldevice_code", patroldevice.getPatroldeviceCode());
                    map.put("patroldevice_name", patroldevice.getPatroldeviceName());
                    map.put("station_name", patroldevice.getStationName());
                    map.put("station_code", patroldevice.getStationCode());
                    map.put("device_model", patroldevice.getAreaId());
                    map.put("manufacturer", patroldevice.getAreaName());
                    map.put("use_unit", patroldevice.getUseUnit());
                    map.put("device_source", patroldevice.getDeviceSource());
                    map.put("production_date", patroldevice.getProductionDate());
                    map.put("production_code", patroldevice.getProductionDate());
                    map.put("istransport", patroldevice.getIstransport());
                    map.put("use_mode", patroldevice.getUseMode());
                    map.put("video_mode", patroldevice.getVideoMode());
                    map.put("place", patroldevice.getPlace());
                    map.put("type", patroldevice.getType());
                    map.put("patroldevice_info", patroldevice.getPatroldeviceInfo());
                    map.put("robots_code", patroldevice.getRobotsCode());
                    mapList.add(map);
                }
                filePath = String.format("%s/Model/%s.xml", stationCode, "robot_model_ZzServer01");
//                filePath=String.format("%s_%s_%s.xml", "robot", DateUtil.format(DateUtil.date(), "yyyyMMdd"), DateUtil.format(DateUtil.date(), "HHmmss"));
                xmlPath = serverConfig.getModelPath() + filePath;
                FileUtil.parseNodeToXML(mapList, xmlPath, "Robot_Model");
                break;
            case "3":
                List<SubstationPatroldevice> patroldevices =
                        substationPatroldeviceMapper.selectList(new LambdaQueryWrapper<SubstationPatroldevice>().eq(SubstationPatroldevice::getType, "10"));
                for (SubstationPatroldevice patroldevice : patroldevices) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("patroldevice_code", patroldevice.getPatroldeviceCode());
                    map.put("patroldevice_name", patroldevice.getPatroldeviceName());
                    map.put("station_name", patroldevice.getStationName());
                    map.put("station_code", patroldevice.getStationCode());
                    map.put("device_model", patroldevice.getAreaId());
                    map.put("manufacturer", patroldevice.getAreaName());
                    map.put("use_unit", patroldevice.getUseUnit());
                    map.put("device_source", patroldevice.getDeviceSource());
                    map.put("production_date", patroldevice.getProductionDate());
                    map.put("production_code", patroldevice.getProductionDate());
                    map.put("istransport", patroldevice.getIstransport());
                    map.put("use_mode", patroldevice.getUseMode());
                    map.put("video_mode", patroldevice.getVideoMode());
                    map.put("place", patroldevice.getPlace());
                    map.put("type", patroldevice.getType());
                    map.put("patroldevice_info", patroldevice.getPatroldeviceInfo());
                    map.put("robots_code", patroldevice.getRobotsCode());
                    mapList.add(map);
                }
                filePath = String.format("%s/Model/%s.xml", stationCode, "camera_model_ZzServer01");
//                filePath =String.format("%s_%s_%s.xml", "camera", DateUtil.format(DateUtil.date(), "yyyyMMdd"), DateUtil.format(DateUtil.date(), "HHmmss"));
                xmlPath = serverConfig.getModelPath() + filePath;
                FileUtil.parseNodeToXML(mapList, xmlPath, "PatrolDevice_Model");
                break;
            case "4":
                List<SubstationDevice> substationDevices = substationDeviceMapper.selectList(new LambdaQueryWrapper<SubstationDevice>().eq(SubstationDevice::getDataType,"0x01").ne(SubstationDevice::getLastmodifier,"机器人系统"));
                for (SubstationDevice substationDevice : substationDevices) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("station_name", substationDevice.getStationName());
                    map.put("station_code", substationDevice.getStationCode());
                    map.put("area_id", substationDevice.getAreaId());
                    map.put("area_name", substationDevice.getAreaName());
                    map.put("device_id", substationDevice.getDeviceId());
                    map.put("device_name", substationDevice.getDeviceName());
                    map.put("component_id", substationDevice.getComponentId());
                    map.put("component_name", substationDevice.getComponentName());
                    map.put("bay_id", substationDevice.getBayId());
                    map.put("bay_name", substationDevice.getBayName());
                    map.put("main_device_id", substationDevice.getMainDeviceId());
                    map.put("main_device_name", substationDevice.getMainDeviceName());
                    map.put("device_type", substationDevice.getDeviceType());
                    map.put("point_type", substationDevice.getDeviceClass());
                    map.put("meter_type", substationDevice.getMeterType());
                    map.put("appearance_type", substationDevice.getAppearanceType());
                    map.put("save_type_list", substationDevice.getSaveTypeList());
                    map.put("recognition_type_list", substationDevice.getRecognitionTypeList());
                    map.put("phase", substationDevice.getPhase());
                    map.put("device_info", substationDevice.getDeviceInfo());
                    String dataType = substationDevice.getDataType();
                    int datatype=1;
                    if("0x03".equals(dataType)){
                        datatype=3;
                    }
                    if("0x02".equals(dataType)){
                        datatype=2;
                    }
                    map.put("data_type", datatype);
                    map.put("lower_value", substationDevice.getLowerValue());
                    map.put("upper_value", substationDevice.getUpperValue());
                    String videoPos = substationDevice.getVideoPos();
                    map.put("video_pos", videoPos);
                    mapList.add(map);
                }
                filePath = String.format("%s/Model/%s.xml", stationCode, "device_model_ZzServer01");
                xmlPath = serverConfig.getModelPath() + filePath;
                FileUtil.parseNodeToXML(mapList, xmlPath, "Device_Model");
                break;
            case "5":
                List<SubstationPatroldevice> uavList =
                        substationPatroldeviceMapper.selectList(new LambdaQueryWrapper<SubstationPatroldevice>().eq(SubstationPatroldevice::getType, "13"));
                for (SubstationPatroldevice patroldevice : uavList) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("patroldevice_code", patroldevice.getPatroldeviceCode());
                    map.put("patroldevice_name", patroldevice.getPatroldeviceName());
                    map.put("station_name", patroldevice.getStationName());
                    map.put("station_code", patroldevice.getStationCode());
                    map.put("device_model", patroldevice.getAreaId());
                    map.put("manufacturer", patroldevice.getAreaName());
                    map.put("use_unit", patroldevice.getUseUnit());
                    map.put("device_source", patroldevice.getDeviceSource());
                    map.put("production_date", patroldevice.getProductionDate());
                    map.put("production_code", patroldevice.getProductionDate());
                    map.put("istransport", patroldevice.getIstransport());
                    map.put("use_mode", patroldevice.getUseMode());
                    map.put("video_mode", patroldevice.getVideoMode());
                    map.put("place", patroldevice.getPlace());
                    map.put("type", patroldevice.getType());
                    map.put("patroldevice_info", patroldevice.getPatroldeviceInfo());
                    map.put("robots_code", patroldevice.getRobotsCode());
                    mapList.add(map);
                }
                filePath = String.format("%s/Model/%s.xml", stationCode, "uav_model_ZzServer01");
//                filePath=String.format("%s_%s_%s.xml", "uav", DateUtil.format(DateUtil.date(), "yyyyMMdd"), DateUtil.format(DateUtil.date(), "HHmmss"));
                xmlPath = serverConfig.getModelPath() + filePath;
                FileUtil.parseNodeToXML(mapList, xmlPath, "Uav_Model");
                break;
            case "6":
                List<SubstationPatroldevice> vocalList =
                        substationPatroldeviceMapper.selectList(new LambdaQueryWrapper<SubstationPatroldevice>().eq(SubstationPatroldevice::getType, "14"));
                for (SubstationPatroldevice patroldevice : vocalList) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("patroldevice_code", patroldevice.getPatroldeviceCode());
                    map.put("patroldevice_name", patroldevice.getPatroldeviceName());
                    map.put("station_name", patroldevice.getStationName());
                    map.put("station_code", patroldevice.getStationCode());
                    map.put("device_model", patroldevice.getAreaId());
                    map.put("manufacturer", patroldevice.getAreaName());
                    map.put("use_unit", patroldevice.getUseUnit());
                    map.put("device_source", patroldevice.getDeviceSource());
                    map.put("production_date", patroldevice.getProductionDate());
                    map.put("production_code", patroldevice.getProductionDate());
                    map.put("istransport", patroldevice.getIstransport());
                    map.put("use_mode", patroldevice.getUseMode());
                    map.put("video_mode", patroldevice.getVideoMode());
                    map.put("place", patroldevice.getPlace());
                    map.put("type", patroldevice.getType());
                    map.put("patroldevice_info", patroldevice.getPatroldeviceInfo());
                    map.put("robots_code", patroldevice.getRobotsCode());
                    mapList.add(map);
                }
                filePath = String.format("%s/Model/%s.xml", stationCode, "voca_model_ZzServer01");
//                filePath=String.format("%s_%s_%s.xml", "vocal", DateUtil.format(DateUtil.date(), "yyyyMMdd"), DateUtil.format(DateUtil.date(), "HHmmss"));
                xmlPath = serverConfig.getModelPath() + filePath;
                FileUtil.parseNodeToXML(mapList, xmlPath, "Vocal_Model");
                break;
            case "7":
                List<Task> taskList = taskMapper.selectList(null);
                for (Task task : taskList) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("station_name", task.getStationName());
                    map.put("station_code", task.getStationCode());
                    map.put("type", task.getType());
                    map.put("task_code", task.getTaskCode());
                    map.put("task_name", task.getTaskName());
                    map.put("priority", task.getPriority());
                    map.put("device_level", task.getDeviceLevel());
                    map.put("device_list", task.getDeviceList());
                    map.put("fixed_start_time", task.getFixedStartTime());
                    map.put("cycle_month", task.getCycleMonth());
                    map.put("cycle_week", task.getCycleWeek());
                    map.put("cycle_execute_time", task.getCycleExecuteTime());
                    map.put("cycle_start_time", task.getCycleStartTime());
                    map.put("cycle_end_time", task.getCycleEndTime());
                    map.put("interval_number", task.getIntervalNumber());
                    map.put("interval_type", task.getIntervalType());
                    map.put("interval_execute_time", task.getIntervalExecuteTime());
                    map.put("interval_start_time", task.getIntervalStartTime());
                    map.put("interval_end_time", task.getIntervalEndTime());
                    map.put("invalid_start_time", task.getInvalidStartTime());
                    map.put("invalid_end_time", task.getInvalidEndTime());
                    map.put("isenable", task.getIsenable());
                    map.put("creator", task.getCreator());
                    map.put("create_time", task.getCreateTime());
                    mapList.add(map);
                }
                filePath = String.format("%s/Model/%s.xml", stationCode, "task_model_ZzServer01");
//                filePath=String.format("%s_%s_%s.xml", "task", DateUtil.format(DateUtil.date(), "yyyyMMdd"), DateUtil.format(DateUtil.date(), "HHmmss"));
                xmlPath = serverConfig.getModelPath() + filePath;
                FileUtil.parseNodeToXML(mapList, xmlPath, "Task_Model");
                break;
            case "8":
                List<ExaminePlan> examinePlanList = examinePlanMapper.selectList(null);
                for (ExaminePlan examinePlan : examinePlanList) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("station_name", examinePlan.getStationName());
                    map.put("station_code", examinePlan.getStationCode());
                    map.put("config_code", examinePlan.getConfigCode());
                    map.put("enable", examinePlan.getEnable());
                    map.put("start_time", examinePlan.getStartTime());
                    map.put("end_time", examinePlan.getEndTime());
                    map.put("device_level", examinePlan.getDeviceLevel());
                    map.put("device_list", examinePlan.getDeviceList());
                    map.put("coordinate_pixel", examinePlan.getCoordinatePixel());
                    mapList.add(map);
                }
                filePath = String.format("%s/Model/%s.xml", stationCode, "overhaularea_model_ZzServer01");
//                filePath=String.format("%s_%s_%s.xml", "overhaularea", DateUtil.format(DateUtil.date(), "yyyyMMdd"), DateUtil.format(DateUtil.date(), "HHmmss"));
                xmlPath = serverConfig.getModelPath() + filePath;
                FileUtil.parseNodeToXML(mapList, xmlPath, "Overhaularea_Model");
                break;
            case "9":
                List<Substation> substationList =
                        substationMapper.selectList(new LambdaQueryWrapper<Substation>().eq(Substation::getDatastatus
                                , "1"));
                Substation substation = substationList.get(0);
                String images = substation.getImages();
                filePath = systempath + "station" + File.separator + images;
                break;
        }
        return filePath;
    }

    @Override
    public void sendRobotModel(String robotId) {
        SubstationPatroldevice substationPatroldevice = substationPatroldeviceMapper.selectById(robotId);
        if (substationPatroldevice != null) {
            sendMsgtoRobot(substationPatroldevice.getInternationalId(), serverConfig.getPatrolServerid(), substationPatroldevice.getInternationalId(), SystemCode.TYPE_MODEL_SYNC_CODE.getCode(), SystemCode.COMMAND_MODEL_HOST_CODE.getCode(), substationPatroldevice.getStationCode(), "");
        }
    }


    private String getReturnCimFile(String stationcode, String monitorindex, String equip, String result, String time) {
        StringBuffer content = new StringBuffer();
        content.append(String.format("<!Entity=设备状态请求结果 ver='V1.0' time='%s'（文件最新时间)!>\n", DateUtil.now()));
        content.append("<DeviceInfo::设备状态>\n");
        content.append("@序号 站序号 监控索引号 设备名称 设备状态 事件时标\n");
        String resultinfo = String.format("#1\t%s\t%s\t%s\t%s\t%s\n",
                stationcode, monitorindex, equip, result, time);
        content.append(resultinfo);
        content.append("</DeviceInfo::设备状态>\n");
        return content.toString();
    }

}
