package com.njcn.utils;

import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.njcn.enums.LogTypeEnum;
import com.njcn.mapper.configuration.DevFunctionMapper;
import com.njcn.mapper.configuration.TerminalMapper;
import com.njcn.mapper.data.DevEdAssNapper;
import com.njcn.pojo.terminal.UpDevVO;
import com.njcn.service.log.UserLogDetailService;
import com.njcn.shiro.token.TokenManager;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.kafka.common.protocol.types.Field;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.njcn.mapper.configuration.LineMapper;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import javax.json.JsonObject;
import javax.persistence.criteria.CriteriaBuilder;
import javax.servlet.http.HttpServletRequest;


@Component
public class SocketClient {
    private static final Logger logger = LoggerFactory.getLogger(SocketClient.class);
    private boolean finalFlag = true;
    private boolean finalConValue = true;

    @Autowired
    private LineMapper lineMapper;
    @Autowired
    private DevFunctionMapper devFunctionMapper;
    @Resource
    private DevEdAssNapper devEdAssNapper;

    private final WebSocketUtil webSocketUtil = new WebSocketUtil();

    /*** 线程池 */
    private final ExecutorService executorPool = Executors.newCachedThreadPool();

    private final ConcurrentHashMap<String, Socket> socketMap = new ConcurrentHashMap<>();
    //用于存储连接查看性能的socket
    private final Map<String, Socket> socketQuMap = new HashMap<>();

    private final ConcurrentHashMap<String, Integer> sumDevMap = new ConcurrentHashMap<>();

    //用于记录升级装置当前处理总数
    private final ConcurrentHashMap<String, Integer> sumMap = new ConcurrentHashMap<>();
    //用于记录升级装置当前重启总数
    private final ConcurrentHashMap<String, Integer> sumResMap = new ConcurrentHashMap<>();
    //用于记录升级装置当前取消总数
    private final ConcurrentHashMap<String, Integer> sumCanMap = new ConcurrentHashMap<>();

    //9000在线监测点实时数据功能
    private Map<Integer, List<String>> lineMap;

    private Map<Integer, Socket> lineSocketMap;


    @Resource
    UserLogDetailService userLog;


    //9000在线监测点实时数据
    public String sent(String message, Long lineIndex) {
        String result = null;
        // 与服务端建立连接
        Socket socket = null;
        InputStream is = null;
        BufferedReader din = null;
        DataInputStream dis = null;
        try {
            // 读取配置文件
            Properties pros = PubUtils.readProperties(getClass().getClassLoader(), "java.properties");
            // 要连接的服务端IP地址和端口
            String host = lineMapper.getNodeIpbylineIndex(lineIndex);
            if (host == null) {
                host = pros.get("SOCKETHOST").toString();
            }
            int port = Integer.valueOf(pros.get("SOCKETPORT").toString());
            SocketAddress endpoint = new InetSocketAddress(host, port);
            socket = new Socket();
            socket.connect(endpoint, 3000);
            socket.setSoTimeout(5000);
            // 建立连接后获得输出流
            OutputStream outputStream = socket.getOutputStream();

            socket.getOutputStream().write(message.getBytes("UTF-8"));
            // 通过shutdownOutput高速服务器已经发送完数据，后续只能接受数据
            socket.shutdownOutput();

            is = socket.getInputStream();
            din = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            char[] cbuf = new char[1024];
            int len = din.read(cbuf);
            if (len != -1) {
                result = new String(cbuf, 0, len).trim();
            }

        } catch (IOException e) {
            logger.error("建立连接发生异常，异常是" + e.getMessage());
        }finally {
            safeColse(socket,din,is,null);
        }
        return result;
    }

    //终端
    public String sentDev(String message, Long lineIndex) {
        String result = null;
        // 与服务端建立连接
        Socket socket;
        InputStream is = null;
        BufferedReader din = null;
        DataInputStream dis = null;
        try {
            // 读取配置文件
            Properties pros = PubUtils.readProperties(getClass().getClassLoader(), "java.properties");
//			// 要连接的服务端IP地址和端口
            String host = lineMapper.getNodeIpbyDevIndex(lineIndex);
            if (host == null) {
                host = pros.get("SOCKETHOST").toString();
            }
            int port = Integer.valueOf(pros.get("SOCKETPORT").toString());
            socket = new Socket(host, port);
            // 建立连接后获得输出流
            OutputStream outputStream = socket.getOutputStream();
            // String message = "发送消息";
            socket.getOutputStream().write(message.getBytes("UTF-8"));
            // 通过shutdownOutput高速服务器已经发送完数据，后续只能接受数据
            is = socket.getInputStream();
            din = new BufferedReader(new InputStreamReader(is));
            char[] cbuf = new char[1024];
            din.read(cbuf);
            result = new String(cbuf);
            is.close();
            outputStream.close();
            socket.close();
        } catch (UnknownHostException e) {

        } catch (IOException e) {
            // TODO Auto-generated catch block
            logger.error(e.getMessage());
        }
        return result;
    }

    //监测点
    public String sentLine(String ip, String message, String host, Integer port, String name, List<UpDevVO> list, String index) {
        String msg = "";
        Boolean flag = true;
        String result = null;
        Socket socket = null;
        InputStream is = null;
        BufferedReader din = null;
        Integer allsum = list.size();
        Integer succees = 0;
        Integer fail = 0;
      //  System.out.println(message + ip);
        try {
            socket = new Socket(host, port);
            socket.setSoTimeout(20000);//设置超时时间
            socket.getOutputStream().write(message.getBytes("UTF-8"));
            is = socket.getInputStream();
            din = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            char[] buffer = new char[100240000];
            StringBuffer stringBuffer = new StringBuffer();
            while (true) {
                int len = din.read(buffer);
                if (len > -1) {
                    result = new String(buffer, 0, len);
                    stringBuffer.append(result);
                    try {
                        new JSONObject(stringBuffer);
                        break;
                    } catch (Exception e) {
                        logger.error("未加载完全，持续加载中！");
                    }
                }
            }
            JSONObject jsonObject = new JSONObject(stringBuffer.toString());
            if (jsonObject != null) {
                if (jsonObject.get("resultcode").toString().equals("10000")) {
                    JSONObject data = jsonObject.getJSONObject("data");
                    if (data == null) {
                        //表示刚连接成功
                        flag = true;
                        webSocketUtil.sendMessageFor(stringBuffer.toString(), name);
                        msg = "无数据传输";
                        userLog.getLog("外部定值无数据传输", "失败", ip, LogTypeEnum.SYSTEM.toString(), 1);
                    } else {
                        flag = true;
                        webSocketUtil.sendMessageFor(stringBuffer.toString(), name);
                        msg = "请求成功！" + "请稍候......";
                        userLog.getLog("外部定值获取", "成功", ip, LogTypeEnum.SYSTEM.toString(), 0);
                    }
                } else if (jsonObject.get("resultcode").toString().equals("10010")) {
                    flag = true;
                    webSocketUtil.sendMessageFor(stringBuffer.toString(), name);
                    msg = "";
                } else if (jsonObject.get("resultcode").toString().equals("10003")) {
                    flag = true;
                    JSONArray jsonArray = new JSONArray(list);
                    String json = "{\"resultcode\":" + 10003 + ",\"data\":" + jsonArray.toString() + "}";
                    webSocketUtil.sendMessageFor(json, name);
                    fail += list.size();
                    msg = "JSON字符串解析出错";
                    userLog.getLog("外部定值获取", "json解析失败", ip, LogTypeEnum.SYSTEM.toString(), 1);
                } else {
                    fail++;
                    flag = true;
                    webSocketUtil.sendMessageFor(stringBuffer.toString(), name);
                }
                if (succees + fail == allsum) {
                    flag = false;
                }
            } else {
                msg = "接收json数据为空";
            }
        } catch (ConnectException e) {
            e.printStackTrace();
            JSONArray jsonArray = new JSONArray(list);
            String json = "{\"resultcode\":" + 100 + ",\"data\":" + jsonArray.toString() + "}";
            try {
                webSocketUtil.sendMessageFor(json, name);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            msg = "socket连接失败!";
            userLog.getLog("socket连接", "连接失败", ip, LogTypeEnum.SYSTEM.toString(), 1);
        } catch (SocketException e) {
            e.printStackTrace();
            JSONArray jsonArray = new JSONArray(list);
            String json = "{\"resultcode\":" + 101 + ",\"data\":" + jsonArray.toString() + "}";
            try {
                webSocketUtil.sendMessageFor(json, name);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            msg = "socket异常";
            userLog.getLog("socket", "发生异常", ip, LogTypeEnum.SYSTEM.toString(), 1);
        } catch (UnknownHostException e) {
            e.printStackTrace();
            JSONArray jsonArray = new JSONArray(list);
            String json = "{\"resultcode\":\"10011\",\"data\":" + jsonArray.toString() + "}";
            try {
                webSocketUtil.sendMessageFor(json, name);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            msg = "DNS解析失败!";
            userLog.getLog("socket", "DNS解析失败", ip, LogTypeEnum.SYSTEM.toString(), 1);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            JSONArray jsonArray = new JSONArray(list);
            String json = "{\"resultcode\":\"10012\",\"data\":" + jsonArray.toString() + "}";
            try {
                webSocketUtil.sendMessageFor(json, name);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            msg = "转码异常!";
            userLog.getLog("socket", "转码异常", ip, LogTypeEnum.SYSTEM.toString(), 1);
        } catch (IOException e) {
            e.printStackTrace();
            JSONArray jsonArray = new JSONArray(list);
            String json = "{\"resultcode\":\"10013\",\"data\":" + jsonArray.toString() + "}";
            try {
                webSocketUtil.sendMessageFor(json, name);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            msg = "连接超时导致读写异常!";
            userLog.getLog("socket", "连接超时导致读写异常", ip, LogTypeEnum.SYSTEM.toString(), 1);
        } finally {
            safeColse(socket, din, is, null);
        }
        return msg;
    }

    //暂降波形补招
    public String sentLineWave(String message, String host, Integer port) {
        String result = "";
        String res = "";
        Socket socket = null;
        InputStream is = null;
        BufferedReader din = null;

        try {
            socket = new Socket(host, port);
            socket.setSoTimeout(8000);//设置超时时间
            socket.getOutputStream().write(message.getBytes("UTF-8"));
            is = socket.getInputStream();
            din = new BufferedReader(new InputStreamReader(is, "UTF-8"));


            while((result = din.readLine())!=null){
                System.out.println(result);
                net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(result);
                if(jsonObject.get("resultcode").equals("10000")){
                    res ="波形补招命令接收成功";
                }else{
                    res = "波形补招命令接收失败";
                }
                break;
            }
            return res;
        }catch (SocketTimeoutException e){
            logger.error("9200暂降补招socket连接超时"+e.getMessage());
            return "Socket等待超时";
        }catch (ConnectException e){
            logger.error("9200暂降补招socket连接出错"+e.getMessage());
            return "Socket连接异常";
        } catch (Exception e){
            logger.error("9200暂降补招异常"+e.getMessage());
            return "波形补招命令异常";
        } finally {
            safeColse(socket,din,is,null);
        }
    }

    //终端校验内部定值
    public String sentDZDev(String ip, String message, String host, Integer port, String name, List<UpDevVO> list, String index) {
        String msg = "";
        String result = null;
        Socket socket = null;
        InputStream is = null;
        BufferedReader din = null;
        try {
            socket = new Socket(host, port);
            socket.setSoTimeout(20000);//设置超时时间
            socket.getOutputStream().write(message.getBytes("UTF-8"));
            is = socket.getInputStream();
            din = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            char[] buffer = new char[100240000];
            StringBuffer stringBuffer = new StringBuffer();
            while (true) {
                int len = din.read(buffer);
                if (len > -1) {
                    result = new String(buffer, 0, len);
                    stringBuffer.append(result);
                    try {
                        new JSONObject(stringBuffer);
                        break;
                    } catch (Exception e) {
                        logger.error("未加载完全，持续加载中！");
                    }
                }
            }
            JSONObject jsonObject = new JSONObject(stringBuffer.toString());
            if (jsonObject != null) {
                if (jsonObject.get("resultcode").toString().equals("10000")) {
                    JSONObject data = jsonObject.getJSONObject("data");
                    if (data == null) {
                        //表示刚连接成功
                        webSocketUtil.sendMessageFor(stringBuffer.toString(), name);
                        msg = "无数据传输";
                        userLog.getLog("内部定值无数据传输", "失败", ip, LogTypeEnum.SYSTEM.toString(), 1);
                    } else {
                        webSocketUtil.sendMessageFor(stringBuffer.toString(), name);

                        msg = "请求成功！" + "请稍候......";
                        userLog.getLog("内部定值获取", "成功", ip, LogTypeEnum.SYSTEM.toString(), 0);
                    }
                } else if (jsonObject.get("resultcode").toString().equals("10010")) {

                    webSocketUtil.sendMessageFor(stringBuffer.toString(), name);
                    msg = "";
                } else if (jsonObject.get("resultcode").toString().equals("10003")) {

                    JSONArray jsonArray = new JSONArray(list);
                    String json = "{\"resultcode\":" + 10003 + ",\"data\":" + jsonArray.toString() + "}";
                    webSocketUtil.sendMessageFor(json, name);

                    msg = "JSON字符串解析出错";
                    userLog.getLog("JSON字符串解析", "失败", ip, LogTypeEnum.SYSTEM.toString(), 1);
                } else {
                    webSocketUtil.sendMessageFor(stringBuffer.toString(), name);
                }

            } else {
                msg = "接收json数据为空";
                userLog.getLog("接收JSON数据", "失败", ip, LogTypeEnum.SYSTEM.toString(), 1);
            }
        } catch (ConnectException e) {
            e.printStackTrace();
            JSONArray jsonArray = new JSONArray(list);
            String json = "{\"resultcode\":" + 100 + ",\"data\":" + jsonArray.toString() + "}";
            try {
                webSocketUtil.sendMessageFor(json, name);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            msg = "socket连接失败!";
            userLog.getLog("socket连接", "连接失败", ip, LogTypeEnum.SYSTEM.toString(), 1);
        } catch (SocketException e) {
            e.printStackTrace();
            JSONArray jsonArray = new JSONArray(list);
            String json = "{\"resultcode\":" + 101 + ",\"data\":" + jsonArray.toString() + "}";
            try {
                webSocketUtil.sendMessageFor(json, name);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            msg = "socket异常";
            userLog.getLog("socket", "发生异常", ip, LogTypeEnum.SYSTEM.toString(), 1);
        } catch (UnknownHostException e) {
            e.printStackTrace();
            JSONArray jsonArray = new JSONArray(list);
            String json = "{\"resultcode\":\"10011\",\"data\":" + jsonArray.toString() + "}";
            try {
                webSocketUtil.sendMessageFor(json, name);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            msg = "DNS解析失败!";
            userLog.getLog("socket", "DNS解析失败", ip, LogTypeEnum.SYSTEM.toString(), 1);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            JSONArray jsonArray = new JSONArray(list);
            String json = "{\"resultcode\":\"10012\",\"data\":" + jsonArray.toString() + "}";
            try {
                webSocketUtil.sendMessageFor(json, name);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            msg = "转码异常!";
            userLog.getLog("socket", "转码异常", ip, LogTypeEnum.SYSTEM.toString(), 1);
        } catch (IOException e) {
            e.printStackTrace();
            JSONArray jsonArray = new JSONArray(list);
            String json = "{\"resultcode\":\"10013\",\"data\":" + jsonArray.toString() + "}";
            try {
                webSocketUtil.sendMessageFor(json, name);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            msg = "连接超时导致读写异常!";
            userLog.getLog("socket", "连接超时导致读写异常", ip, LogTypeEnum.SYSTEM.toString(), 1);
        } finally {
            safeColse(socket, din, is, null);
        }
        return msg;
    }


    //重启前置程序命令
    public void sentCloseWeb(String msg, String name, String ip, Integer port) {

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                OutputStream outputStream = null;
                InputStream inputStream = null;
                BufferedReader din = null;
                Socket socket = null;
                Boolean flag = true;
                String mes = null;

                try {
                    socket = new Socket(ip, port);
                    socket.setSoTimeout(10 * 1000); //10S
                    // 建立连接后获得输出流
                    outputStream = socket.getOutputStream();
                    outputStream.write(msg.getBytes("UTF-8"));
                    inputStream = socket.getInputStream();
                    din = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                    byte[] bytes = new byte[1024];
                    while (flag) {
                      //  System.out.println("进入循环");
                        int len = inputStream.read(bytes);
                        if (len > -1) {
                            //注意指定编码格式，发送方和接收方一定要统一，建议使用UTF-8
                            mes = new String(bytes, 0, len, "UTF-8");
                            JSONObject jsonObject1 = new JSONObject(mes);
                            if (jsonObject1 != null) {
                                jsonObject1.put("type", "200");
                                if (jsonObject1.get("resultcode").toString().equals("10000")) {
                                    devFunctionMapper.delNodeIp(ip);
                                    userLog.getLog("前置重启", "成功", ip, LogTypeEnum.SYSTEM.toString(), 1);
                                }
                                webSocketUtil.sendMessageFor(jsonObject1.toString(), name);
                                flag = false;
                            }
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    JSONObject json = new JSONObject();
                    json.put("type", "200");
                    json.put("resultcode", "13333");
                    json.put("resultmsg", ip);
                    json.put("data", ip);
                    try {
                        webSocketUtil.sendMessageFor(json.toString(), name);
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                    userLog.getLog("前置重启", "失败", ip, LogTypeEnum.SYSTEM.toString(), 1);
                } finally {
                    safeColse(socket, din, inputStream, outputStream);
                }
            }
        };
        executorPool.execute(runnable);
    }

    //展示终端性能
    public void showQuaity(String message, String host, Integer port, String name) {
        String userId = TokenManager.getUserId();
       // System.out.println(message);
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                String result = null;
                OutputStream outputStream = null;
                BufferedReader din = null;
                Socket socket = null;

                Boolean flag = true;
                try {
                    socket = new Socket(host, port);
                    socket.setSoTimeout(20000); //20s未接受到数据自动超时中断
                    socketQuMap.put(userId, socket);
                    outputStream = socket.getOutputStream();
                    outputStream.write(message.getBytes("UTF-8"));

                    din = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));

                    while ((result = din.readLine()) != null) {
                      //  System.out.println(result);
                        JSONObject jsonObject = new JSONObject(result);
                        jsonObject.put("type", "190");
                        if (jsonObject.get("resultcode").toString().equals("10000")) {
                            webSocketUtil.sendMessageFor(jsonObject.toString(), name);
                        } else {
                            webSocketUtil.sendMessageFor(jsonObject.toString(), name);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.error("终端性能异常" + e.getMessage());
                    JSONObject json = new JSONObject();
                    json.put("type", "190").put("resultcode", "20000").put("resultmsg", "未知异常");
                    try {
                        webSocketUtil.sendMessageFor(json.toString(), name);
                    } catch (IOException ioException) {
                        logger.error(ioException.getMessage());
                    }
                } catch (Exception e) {
                  //  System.out.println("出错了+++");
                    e.printStackTrace();
                } finally {
                 //   System.out.println("查看性能安全退出");

                    safeColse(socket, din, null, outputStream);
                    if (socketQuMap != null) {
                        socketQuMap.remove(userId);
                    }
                }
            }
        };
        executorPool.execute(runnable);
    }

    //心跳机制
    public String heartSocket(String msg, String host, Integer port) {
      //  System.out.println("性能心跳"+msg);
        if (socketQuMap.containsKey(TokenManager.getUserId())) {
            Socket socket = null;
            OutputStream outputStream = null;
            BufferedReader bufferedReader = null;

            try {
                String result = null;
                socket = new Socket(host, port);
                socket.setSoTimeout(10000);
                outputStream = socket.getOutputStream();
                outputStream.write(msg.getBytes("UTF-8"));
                bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                while ((result = bufferedReader.readLine()) != null) {
                    JSONObject jsonObject = new JSONObject(result.trim());
                    if (jsonObject.get("resultcode").equals("10000")) {
                        break;
                    } else {
                        break;
                    }
                }
                return "发送成功";
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("发送心跳异常" + e.getMessage());
            } finally {
                safeColse(socket, null, null, outputStream);
            }
        } else {
            return "socket异常";
        }
        return "发送失败";
    }

    //关闭socket
    public void closeMySocket(String msg, String host, Integer port) throws Exception {
        if (socketQuMap.containsKey(TokenManager.getUserId())) {
            String result = null;
            Socket socket = null;
            OutputStream outputStream = null;
            BufferedReader bufferedReader = null;
            try {
                socket = new Socket(host, port);
                socket.setSoTimeout(5000);
                outputStream = socket.getOutputStream();
                outputStream.write(msg.getBytes("UTF-8"));
                bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                while ((result = bufferedReader.readLine()) != null) {
                    JSONObject jsonObject = new JSONObject(result);
                    if (jsonObject.getStr("resultcode").equals("10000")) {
                       // System.out.println(jsonObject.toString());
                    }
                    break;
                }

                // Thread.sleep(2000);
            } catch (IOException e) {
                e.printStackTrace();
                logger.error(e.getMessage());
            } finally {
              //  System.out.println("关闭+++");
                socketQuMap.get(TokenManager.getUserId()).shutdownOutput();
                safeColse(socket, null, null, outputStream);
            }
        }
    }


    /**
     * @Author chendaofei
     * @Description 安全关闭
     * @Date 20:10 2020/8/27
     **/
    private void safeColse(Socket socket, BufferedReader bufferedReader, InputStream inputStream, OutputStream outputStream) {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                logger.error("发生错误，错误信息" + e.getMessage());
            }
        }
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                logger.error("发生错误，错误信息" + e.getMessage());
            }
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                logger.error("发生错误，错误信息" + e.getMessage());
            }
        }
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                logger.error("发生错误，错误信息" + e.getMessage());
            }
        }
    }

    //仪表盘实时数据/点击谐波频谱
    public String sentLineRealTime(String message, String host, Integer port) {

        String jsonStr = null;
        String result = null;
        Socket socket = null;
        InputStream is = null;
        BufferedReader din = null;
        JSONObject jsonObject=null;
        try {
            socket = new Socket(host, port);
            socket.setSoTimeout(6000);
            socket.getOutputStream().write(message.getBytes("UTF-8"));
            din = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));

            while ((result = din.readLine())!=null) {
              //  System.out.println(result);

                try {
                    jsonObject = new JSONObject(result.trim());

                } catch (Exception e) {
                    logger.info("未加载完全，持续加载中！");
                }

                jsonStr = jsonObject.toString();
                break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取实时数据错误" + e.getMessage());
            jsonStr = null;
        } finally {
            safeColse(socket, din, is, null);
        }

        return  jsonStr;
    }

    //终端
    public String sentResetDev(String ip, String message, String host, Integer port, String name) {
        String msg = "";
        Boolean flag = true;
        String result = null;
        Socket socket = null;
        InputStream is = null;
        BufferedReader din = null;
        Integer succees = 0;
        Integer fail = 0;
        try {
            socket = new Socket(host, port);
            socket.getOutputStream().write(message.getBytes("UTF-8"));
            is = socket.getInputStream();
            din = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            char[] buffer = new char[102400];
            StringBuffer stringBuffer = new StringBuffer();
            while (true) {
                int len = din.read(buffer);
                if (len > -1) {
                    result = new String(buffer, 0, len);
                    stringBuffer.append(result);
                    try {
                        new JSONObject(stringBuffer);
                        break;
                    } catch (Exception e) {
                        logger.error("未加载完全，持续加载中！");
                    }
                }
            }
            JSONObject jsonObject = new JSONObject(stringBuffer.toString());
            if (jsonObject != null) {
                if (jsonObject.get("resultcode").toString().equals("10000")) {
                    String data = jsonObject.getStr("resultmsg");
                    if (data == null) {
                        //表示刚连接成功
                        flag = true;
                        webSocketUtil.sendMessageFor(result, name);
                        msg = "无数据传输";
                        userLog.getLog("无数据传输", "失败", ip, LogTypeEnum.SYSTEM.toString(), 1);
                    } else {
                        flag = true;
                        webSocketUtil.sendMessageFor(result, name);
                        msg = "请求成功！" + "请稍候......";
                        userLog.getLog("定值下发", "成功", ip, LogTypeEnum.SYSTEM.toString(), 0);
                    }
                } else if (jsonObject.get("resultcode").toString().equals("10010")) {
                    flag = true;
                    webSocketUtil.sendMessageFor(result, name);
                    msg = "";
                } else if (jsonObject.get("resultcode").toString().equals("10003")) {
                    flag = true;
                    webSocketUtil.sendMessageFor(result, name);
                    msg = "JSON字符串解析出错";
                } else {
                    fail++;
                    flag = true;
                    webSocketUtil.sendMessageFor(result, name);
                }
            } else {
                msg = "接收json数据为空";
            }
        } catch (ConnectException e) {
            e.printStackTrace();
            try {
                webSocketUtil.sendMessageFor(result, name);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            msg = "socket连接失败!";
            userLog.getLog("socket连接", "失败", ip, LogTypeEnum.SYSTEM.toString(), 1);
        } catch (SocketException e) {
            e.printStackTrace();
            try {
                webSocketUtil.sendMessageFor(result, name);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            msg = "socket异常";
            userLog.getLog("socket连接", "失败", ip, LogTypeEnum.SYSTEM.toString(), 1);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                webSocketUtil.sendMessageFor(result, name);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        } finally {
            safeColse(socket, din, is, null);
        }
        return msg;
    }

    //app谐波频谱实时数据运行稳定后删除
    public String sentLineRealTimeTwo(String message, String host, Integer port) {
        try {
            Future<String> future = executorPool.submit(new MyCallableTask(host, port, message));
            return future.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return "出错";
    }


    //升级终端
    public void sentTerminal(String message, String host, Integer port, String name, String edIndex, List<UpDevVO> list) {
        String userId = TokenManager.getUserId();
        sumMap.put(userId + host, 0);
        sumCanMap.put(userId + host, 0);
        sumResMap.put(userId + host, 0);
        sumDevMap.put(userId + host, list.size());
        System.out.println(message);
        logger.info("发起升级装置命令:"+message);
        Runnable myCallable = new Runnable() {
            @Override
            public void run() {

                String result = null;
                Socket socket = null;
                InputStream is = null;
                BufferedReader din = null;
                OutputStream outputStream = null;
                JSONArray jsonArray = new JSONArray(list);
                String json = "{\"resultcode\":\"100\",\"type\":\"180\",\"data\":" + jsonArray.toString() + "}";

                try {
                    SocketAddress socketAddress = new InetSocketAddress(host, port);
                    socket = new Socket();
                    socket.connect(socketAddress, 7000);
                    socket.setSoTimeout(60*1000*3);
                    socketMap.put(userId + host, socket);
                    outputStream = socket.getOutputStream();
                    outputStream.write(message.getBytes("UTF-8"));
                    is = socket.getInputStream();
                    din = new BufferedReader(new InputStreamReader(is, "UTF-8"));

                    while ((result = din.readLine()) != null) {

                        System.out.println(result);
                        logger.info("升级流程:"+message);

                        JSONObject jsonObject = new JSONObject(result.trim());

                        jsonObject.put("type", "180");
                        if (jsonObject.get("resultcode").toString().equals("10000")) {
                            JSONObject data = jsonObject.getJSONObject("data");
                            if (data == null) {
                                //表示刚连接成功

                                webSocketUtil.sendMessageFor(jsonObject.toString(), name);
                            } else {
                                webSocketUtil.sendMessageFor(jsonObject.toString(), name);
                                if (data.get("state").equals("2")) {
                                    Integer succeed = sumMap.get(userId + host);
                                    succeed++;
                                    sumMap.put(userId + host, succeed);
                                    userLog.getLog("终端版本升级", "成功", host, LogTypeEnum.SYSTEM.toString(), 1);
                                } else if (data.get("state").equals("3")) {
                                    Integer fail = sumMap.get(userId + host);
                                    fail++;
                                    sumMap.put(userId + host, fail);
                                    userLog.getLog("终端版本升级", "失败", host, LogTypeEnum.SYSTEM.toString(), 1);
                                }
                            }
                        } else if (jsonObject.get("resultcode").toString().equals("10010")) {

                            webSocketUtil.sendMessageFor(jsonObject.toString(), name);

                        } else if (jsonObject.get("resultcode").toString().equals("10003")) {

                            webSocketUtil.sendMessageFor(json, name);
                            Integer fail = sumMap.get(userId + host);
                            for (UpDevVO dev : list) {
                                fail++;
                                devEdAssNapper.addUpDevAssDetail(dev.getDevIndex(), edIndex, new Date(), TokenManager.getUserId(), 0, 0);
                            }
                            sumMap.put(userId + host, fail);

                        } else if (jsonObject.get("resultcode").toString().equals("10008")) {
                            webSocketUtil.sendMessageFor(jsonObject.toString(), name);
                        } else {
                            Integer fail = sumMap.get(userId + host);
                            System.out.println(fail);
                            fail++;
                            sumMap.put(userId + host, fail);
                            webSocketUtil.sendMessageFor(jsonObject.toString(), name);
                            //devEdAssNapper.addUpDevAssDetail(jsonObject.data., edIndex, new Date(), TokenManager.getUserId(), 0, 0);
                        }

                        Integer resSum = sumMap.get(userId + host);

                        if (resSum == list.size()) {
                            System.out.println("进入break跳出升级流程总装置数:" + resSum);
                            break;
                        }


                    }
                } catch (SocketTimeoutException red) {
                    red.printStackTrace();
                    //全部取消升级操作  异常不处理
                    logger.error("终端升级连接超时,联系管理员排查问题" + red.getMessage());
                    try {
                        JSONObject jj = new JSONObject();
                        jj.put("resultcode",77777);
                        jj.put("type",180);
                        webSocketUtil.sendMessageFor(jj.toString(), name);
                    } catch (IOException ex) {
                        logger.error("发生错误，错误信息" + ex.getMessage());
                    }
                } catch (ConnectException e) {
                    e.printStackTrace();
                    logger.error("发生错误，错误信息" + e.getMessage());
                    userLog.getLog("终端版本升级", "失败", host, LogTypeEnum.SYSTEM.toString(), 1);
                    for (UpDevVO dev : list) {
                        devEdAssNapper.addUpDevAssDetail(dev.getDevIndex(), edIndex, new Date(), userId, 0, 0);
                    }
                    try {
                        webSocketUtil.sendMessageFor(json, name);
                    } catch (IOException ex) {
                        logger.error("发生错误，错误信息" + ex.getMessage());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("发生错误，错误信息" + e.getMessage());
                    userLog.getLog("终端版本升级", "失败", host, LogTypeEnum.SYSTEM.toString(), 1);
                    for (UpDevVO dev : list) {
                        devEdAssNapper.addUpDevAssDetail(dev.getDevIndex(), edIndex, new Date(), userId, 0, 0);
                    }
                    try {
                        webSocketUtil.sendMessageFor(json, name);
                    } catch (IOException ex) {
                        logger.error("发生错误，错误信息" + ex.getMessage());
                    }
                } finally {
                    try {
                        //不管失败成功告诉前台页面升级程序结束
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("type",180);
                        jsonObject.put("resultcode",-10000);
                        jsonObject.put("data",list);
                        webSocketUtil.sendMessageFor(jsonObject.toString(), name);
                    } catch (IOException ex) {
                        logger.error("webSocket发生错误，错误信息" + ex.getMessage());
                    }
                    System.out.println("socket+++++++安全关闭++++++++");
                    safeColse(socket, din, is, outputStream);
                    delMapData(userId + host);
                }
            }
        };
        executorPool.execute(myCallable);
    }

    /**
     * 重启升级成功的装置
     *
     * @author cdf
     * @date 2021/8/2
     */
    public void restartDev(String json, String host, Integer port, List<String> devL) {
        System.out.println("重启装置" + host + "命令：" + json);
        Integer sum = devL.size();
        String loginName = TokenManager.getToken().getLoginName();
        String userId = TokenManager.getUserId();
        Runnable aaa = new Runnable() {
            @Override
            public void run() {
                Socket socket = null;
                BufferedReader bufferedReader = null;
                OutputStream outputStream = null;
                JSONObject jsonObject = null;
                String result = null;
                List<String> devIndexList = new ArrayList<>();
                try {
                    socket = new Socket(host, port);
                    socket.setSoTimeout(1000*60*6);
                    outputStream = socket.getOutputStream();
                    outputStream.write(json.getBytes());
                    bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                    Socket socket1 = socket;


                    Runnable heart = new Runnable() {

                        @Override
                        public void run() {
                            finalFlag = true;
                            try {
                                while (finalFlag){
                                    Thread.sleep(15000);
                                    if(socket1!=null) {
                                        if (socket1.isConnected() && !socket1.isClosed()) {
                                            socket1.getOutputStream().write(new JSONObject().put("heart", "666").toString().getBytes());
                                            System.out.println("心跳发送成功");
                                        }
                                    }

                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                                finalFlag = false;
                            }
                            System.out.println("是否发送心跳标识"+ finalFlag);
                        }
                    };
                    executorPool.execute(heart);



                    while ((result = bufferedReader.readLine()) != null) {
                        System.out.println(result);

                        try {
                            jsonObject = new JSONObject(result.trim());
                        } catch (Exception json) {
                            json.printStackTrace();
                            logger.error("终端升级重启命令发送失败" + json.getMessage());
                            break;
                        }
                        if ((jsonObject.get("resultcode")).equals(10000)) {
                            //处理成功进行入库记录日志
                         //   Integer succeed = sumResMap.get(userId + host);
                         //   succeed++;
                          //  sumResMap.put(userId + host, succeed);
                        } else if ((jsonObject.get("resultcode")).equals(10008)) {

                        } else if ((jsonObject.get("resultcode")).equals(10001)) {
                            devIndexList.add(jsonObject.getJSONObject("data").getStr("devIndex"));
                            Integer succeed = sumResMap.get(userId + host);
                            succeed++;
                            sumResMap.put(userId + host, succeed);
                        }   else {
                            Integer succeed = sumResMap.get(userId + host);
                            succeed++;
                            sumResMap.put(userId + host, succeed);
                        }
                        jsonObject.put("type", "181");
                        webSocketUtil.sendMessageFor(jsonObject.toString(), loginName);


                        if (sum.equals(sumResMap.get(userId + host))) {
                            System.out.println("重启总数量："+sum+"-"+sumResMap.get(userId + host));
                            finalFlag = false;
                            break;
                        }
                    }

                } catch (SocketTimeoutException e) {
                    e.printStackTrace();
                    //超时处理
                    try {
                        JSONObject json = new JSONObject();
                        json.put("resultcode",5555);
                        json.put("resultmsg","超时");
                        //json.put("resultdata",devL);
                        json.put("type",181);
                        webSocketUtil.sendMessageFor(json.toString(), loginName);
                    } catch (IOException ioException) {
                        ioException.printStackTrace();
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception ee) {
                    ee.printStackTrace();
                } finally {
                    finalFlag = false;
                    System.out.println("重启socket结束+++");
                    safeColse(socket, bufferedReader, null, outputStream);
                    socketMap.remove(userId + host);

                    /*//返回前台情况
                    if(CollectionUtil.isNotEmpty(devIndexList)){
                        for(int i=0;i<devIndexList.size();i++){
                           devL.remove(devIndexList.get(i));
                        }

                        if(CollectionUtil.isNotEmpty(devL)){
                            for(int j=0;j<devL.size();j++){
                                try {
                                    JSONObject js = new JSONObject();
                                    js.put("resultcode",99999);
                                    js.put("resultmsg","通讯超时");
                                    JSONObject jj = new JSONObject();
                                    jj.put("devIndex",devL.get(j));
                                    js.put("type",181);
                                    js.put("data",jj);
                                    webSocketUtil.sendMessageFor(js.toString(), loginName);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }

                    }*/
                }

            }
        };
        executorPool.execute(aaa);

    }


    /**
     * 取消升级装置
     *
     * @author cdf
     * @date 2021/8/2
     */
    public void cancelUp(String json, String host, Integer port, Integer devNum) {
        System.out.println(json);
        System.out.println(host);

        String loginName = TokenManager.getToken().getLoginName();
        String userId = TokenManager.getUserId();
        Runnable aaa = new Runnable() {
            @Override
            public void run() {
                Socket socket = null;
                InputStream inputStream = null;
                BufferedReader bufferedReader = null;
                String result = "";
                try {
                    Integer deflag = 0;
                    socket = new Socket(host, port);
                    socket.setSoTimeout(20000);
                    socket.getOutputStream().write(json.getBytes());
                    inputStream = socket.getInputStream();
                    bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

                    System.out.println(result);
                    while ((result = bufferedReader.readLine()) != null) {
                        System.out.println(result);
                        JSONObject jsonObject = null;
                        try {
                            jsonObject = new JSONObject(result.trim());
                        } catch (Exception json) {
                            json.printStackTrace();
                        }
                        if ((jsonObject.get("resultcode").toString()).equals("10000")) {
                            deflag++;
                            Integer csum = sumCanMap.get(userId + host);
                            csum++;
                            sumCanMap.put(userId + host, csum);

                            Integer sum = sumMap.get(userId + host);
                            sum++;
                            sumMap.put(userId + host, sum);
                        }
                        jsonObject.put("type", "182");
                        webSocketUtil.sendMessageFor(jsonObject.toString(), loginName);
                        System.out.println(sumCanMap.get(userId + host));
                        System.out.println(sumMap.get(userId + host));


                        if (sumMap.get(userId + host).equals(sumDevMap.get(userId + host))) {
                            Socket ss = socketMap.get(userId + host);
                            System.out.println("进入关闭socket流程");
                            if (ss != null) {
                                ss.shutdownOutput();
                            }
                        }


                        if (devNum.equals(deflag)) {
                            break;
                        }
                    }

                } catch (IOException e) {
                    logger.error("终端升级取消命令发送失败");
                    e.printStackTrace();
                } finally {
                    System.out.println("取消结束+++");
                    safeColse(socket, bufferedReader, inputStream, null);
                    //  socketMap.remove(userId + host);
                }

            }
        };
        executorPool.execute(aaa);
    }


    /**
     * 9000在线监测点实时数据功能
     *
     * @author cdf
     * @date 2021/8/9
     */

    public void realTimeData(String message, String host, Integer port, Integer lineIndex) {
         //System.out.println(message);
         //System.out.println(host+":"+port);
         //System.out.println(lineIndex);
        String loginName = TokenManager.getToken().getLoginName();
        Runnable real = new Runnable() {
            @Override
            public void run() {
                if (Objects.isNull(lineMap)) {
                    lineMap = new HashMap<>();
                }
                if (lineMap.containsKey(lineIndex)) {
                    //存在监测点
                    List<String> lineL = lineMap.get(lineIndex);
                    if (!lineL.contains(loginName)) {
                        lineL.add(loginName);
                    }
                } else {
                    List<String> userList = new ArrayList<>();
                    userList.add(loginName);
                    lineMap.put(lineIndex, userList);
                }

                Iterator<Map.Entry<Integer, List<String>>> iterator = lineMap.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<Integer, List<String>> en = iterator.next();
                    if (!en.getKey().equals(lineIndex)) {
                        List<String> login = en.getValue();
                        if (CollectionUtil.isNotEmpty(login)) {
                            login.remove(loginName);
                          //  System.out.println("删除用户名" + loginName);
                        }
                    }

                }

                if (lineMap.size() > 1) {
                    //判断是否查看的是同一台装置信息
                    Set<Integer> set = lineMap.keySet();
                    Integer count = lineMapper.getDevSumForLine(set);
                    if (count < lineMap.size()) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("resultcode", 5557);
                        jsonObject.put("resultmsg", "存在其他用户相同操作,请稍后尝试");
                        try {
                            if (Objects.nonNull(lineMap)) {
                                webSocketUtil.sendMessageFor(jsonObject.toString(), loginName);
                            }
                        } catch (IOException ioException) {
                            ioException.printStackTrace();
                        }
                        lineMap.remove(lineIndex);
                        return;
                    }
                }


                if (lineSocketMap == null) {
                    lineSocketMap = new HashMap<>();
                }
                if (!lineSocketMap.containsKey(lineIndex)) {
                    Socket socket = null;
                    BufferedReader bufferedReader = null;
                    OutputStream outputStream = null;
                    try {
                        socket = new Socket();
                        SocketAddress socketAddress = new InetSocketAddress(host, port);
                        socket.connect(socketAddress, 7000);
                        socket.setSoTimeout(20000);
                        lineSocketMap.put(lineIndex, socket);
                        outputStream = socket.getOutputStream();
                        System.out.println("请求消息："+message);
                        outputStream.write(message.getBytes("UTF-8"));

                      //  System.out.println(lineIndex + "socket已经建立连接-----" + new Date());

                        bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
                        String result = null;
                        while ((result = bufferedReader.readLine()) != null) {
                            System.out.println(result);
                            net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(result);
                            String code = jsonObject.getString("resultcode");
                            if (code.equals("10000")) {


                                String str = "";
                                List<String> nameList = lineMap.get(lineIndex);
                                if (CollectionUtil.isNotEmpty(nameList)) {
                                    for (String s : nameList) {
                                        str += s + " ";
                                    }
                                  //  System.out.println(str + " " + lineIndex);
                                    webSocketUtil.sendMessageForBatch(jsonObject.toString(), nameList);
                                }
                            } else if (code.equals("10008")) {
                                List<String> nameList = lineMap.get(lineIndex);
                                if (CollectionUtil.isNotEmpty(nameList)) {
                                    webSocketUtil.sendMessageForBatch(jsonObject.toString(), nameList);
                                }
                               // System.out.println(jsonObject.toString() + "gggg" + lineIndex);
                                break;
                            }

                        }
                    } catch (SocketTimeoutException e) {
                        System.out.println(loginName + "超时异常" + lineIndex);
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("resultcode", 5555);
                        jsonObject.put("resultmsg", "请求超时");
                        try {
                            if (Objects.nonNull(lineMap)) {
                                List<String> name = lineMap.get(lineIndex);
                                if (CollectionUtil.isNotEmpty(name)) {
                                    webSocketUtil.sendMessageForBatch(jsonObject.toString(), name);
                                }
                            }
                        } catch (IOException ioException) {
                            ioException.printStackTrace();
                        }
                        e.printStackTrace();
                    } catch (ConnectException e) {
                        e.printStackTrace();
                      //  System.out.println("连接异常");
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("resultcode", 5556);
                        jsonObject.put("resultmsg", "连接前置服务器失败");
                        try {
                            if (lineMap.get(lineIndex) != null) {
                                webSocketUtil.sendMessageForBatch(jsonObject.toString(), lineMap.get(lineIndex));
                            }
                        } catch (IOException ioException) {
                            ioException.printStackTrace();
                        }
                        e.printStackTrace();
                    } catch (IOException e) {
                      //  System.out.println("socket其他异常" + lineIndex);
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                     //   System.out.println(new Date() + "进入最后处理阶段" + lineIndex);
                        safeColse(socket, bufferedReader, null, outputStream);
                        if (lineSocketMap != null) {
                            lineSocketMap.remove(lineIndex);
                        }
                        if (lineMap != null) {
                            lineMap.remove(lineIndex);
                        }
                    }
                }
            }
        };
        executorPool.execute(real);
    }

    /**
     * 9000实时数据心跳机制
     *
     * @author cdf
     * @date 2021/8/9
     */
    public void heartRealData(String msg, String host, Integer port, Integer lineIndex) {

        if (lineMap != null) {
            if (lineMap.containsKey(lineIndex)) {
                String loginName = TokenManager.getToken().getLoginName();
              //  System.out.println(loginName + "进入心跳socket");
                String result = null;
                OutputStream outputStream = null;
                BufferedReader bufferedReader = null;
                Socket socket = null;

                try {
                    socket = new Socket(host, port);
                    socket.setSoTimeout(10000);
                    outputStream = socket.getOutputStream();
                    outputStream.write(msg.getBytes("UTF-8"));
                    System.out.println(msg);
                    bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    while ((result = bufferedReader.readLine()) != null) {
                        if (StrUtil.isNotBlank(result)) {
                            net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(result);
                            if (jsonObject.get("resultcode").equals("10000")) {
                                break;
                            }
                        } else {
                            logger.error("实时数据socket异常!");
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("resultcode", 5555);
                    jsonObject.put("resultmsg", "请求超时");
                    try {
                        if (Objects.nonNull(lineMap)) {
                            List<String> name = lineMap.get(lineIndex);
                            if (CollectionUtil.isNotEmpty(name)) {
                                webSocketUtil.sendMessageForBatch(jsonObject.toString(), name);
                            }
                        }
                    } catch (IOException ioException) {
                        ioException.printStackTrace();
                    }
                } finally {
                    safeColse(socket, bufferedReader, null, outputStream);
                }
            }
        }
    }

    /**
     * 关闭9000实时数据功能
     *
     * @author cdf
     * @date 2021/8/9
     */
    public void closeRealData(Integer lineIndex) {
        String loginName = TokenManager.getToken().getLoginName();
        if (lineMap != null) {
            if (lineMap.containsKey(lineIndex)) {
                List<String> user = lineMap.get(lineIndex);
                if (CollectionUtil.isNotEmpty(user)) {
                    user.remove(loginName);
                    if (user.size() == 0) {
                        lineMap.remove(lineIndex);
                        Socket socket = null;
                        String result = null;
                        OutputStream outputStream = null;
                        BufferedReader bufferedReader = null;
                        try {
                            cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject();
                            jsonObject.put("LineId", lineIndex);
                            jsonObject.put("type", 2);
                            cn.hutool.json.JSONObject jsonObject1 = new cn.hutool.json.JSONObject();
                            jsonObject1.put("len", 0);
                            jsonObject1.put("data", jsonObject);

                            String host = lineMapper.getNodeIpbylineIndex(lineIndex.longValue());
                            socket = new Socket(host, 60000);
                            socket.setSoTimeout(10000);
                            outputStream = socket.getOutputStream();
                            System.out.println("用户关闭操作发送socket"+jsonObject1.toString());
                            outputStream.write(jsonObject1.toString().getBytes());
                            InputStream inputStream = socket.getInputStream();
                            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                            while ((result = bufferedReader.readLine()) != null) {
                                System.out.println(result);
                                net.sf.json.JSONObject jj = net.sf.json.JSONObject.fromObject(result);
                                //JSONObject jj = new JSONObject(result);
                                if (jj.getString("resultcode").equals("10000")) {
                                    System.out.println("已经告诉前置关闭实时数据" + lineIndex);
                                    lineSocketMap.get(lineIndex).shutdownOutput();
                                    break;
                                }
                            }

                           System.out.println(loginName + "前台请求关闭实时数据" + lineIndex);
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            safeColse(socket, bufferedReader, null, outputStream);
                        }
                        lineSocketMap.remove(lineIndex);
                    }
                }
            }
        }
    }

    class MyCallableTask implements Callable<String> {
        private String host;
        private Integer port;
        private String message;

        public MyCallableTask(String host, Integer port, String message) {
            this.host = host;
            this.port = port;
            this.message = message;
        }

        @Override
        public String call() throws Exception {
            String result = null;
            Socket socket = null;
            InputStream is = null;
            BufferedReader din = null;
            StringBuffer stringBuffer = null;
            try {
                socket = new Socket(host, port);
                socket.setSoTimeout(20000);
                socket.getOutputStream().write(message.getBytes("UTF-8"));
                socket.shutdownOutput();
                is = socket.getInputStream();
                din = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                char[] buffer = new char[102400];
                stringBuffer = new StringBuffer();
                while (true) {
                    int len = din.read(buffer);
                    if (len > -1) {
                        result = new String(buffer, 0, len);
                        stringBuffer.append(result);
                        try {
                            new JSONObject(stringBuffer);
                            break;
                        } catch (Exception e) {
                            logger.error("未加载完全，持续加载中！");
                        }
                    }
                }
                logger.info(stringBuffer.toString());
                if (stringBuffer.length() == 0) {
                    return "";
                } else {
                    return stringBuffer.toString();
                }


            } catch (Exception e) {
                e.printStackTrace();
                logger.error("实时数据出现错误" + e.getMessage());
            } finally {
                safeColse(socket, din, is, null);
            }
            return "";
        }
    }


    /**
     * 清空全局变量释放内存
     *
     * @author cdf
     * @date 2021/8/9
     */
    public void delMapData(String key) {
        if (sumMap != null) {
            sumMap.remove(key);
        }
        if (sumCanMap != null) {
            sumCanMap.remove(key);
        }
    }

    /**
     * create by: xu yang
     * description: 获取终端目录
     * create time: 2021/8/16 13:32
     */
    public JSONObject getFileDirectory(String message, String host, Integer port) {
        JSONObject jsonObject = null;
        // 与服务端建立连接
        Socket socket = null;
        InputStream is = null;
        BufferedReader din = null;
        StringBuilder stringBuilder = new StringBuilder();
        try {
            socket = new Socket(host, port);
            socket.setSoTimeout(10000);
            // 建立连接后获得输出流
            socket.getOutputStream().write(message.getBytes("UTF-8"));
            is = socket.getInputStream();
            din = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            byte[] data = new byte[1024];
            int len = 0;
            while ((len = is.read(data)) != -1) {
                String str = new String(data, 0, len);
                stringBuilder.append(str);
                try {
                    jsonObject = new JSONObject(stringBuilder.toString());
                    if (jsonObject.get("resultcode").equals(10000)) {
                        break;
                    }
                } catch (Exception e) {
                    e.getMessage();
                }
            }
        } catch (ConnectException e) {
            System.out.println("socket连接失败!");
            e.getMessage();
            userLog.getLog("socket连接", "失败", host, LogTypeEnum.SYSTEM.toString(), 1);
        } catch (IOException e) {
            e.getMessage();
            userLog.getLog("获取装置数据", "失败", host, LogTypeEnum.SYSTEM.toString(), 1);
        } finally {
            safeColse(socket, din, is, null);
        }
        return jsonObject;
    }


    /**
     * create by: xu yang
     * description: 获取文件流
     * create time: 2021/8/19 13:25
     */
    public List<Map<String, byte[]>> getFile(String message, String host, Integer port, int counts) {
        List<Map<String, byte[]>> list = new ArrayList<>();
        Map<String, byte[]> map = new HashMap<>();
        JSONObject jsonObject = null;
        // 与服务端建立连接
        Socket socket = null;
        InputStream is = null;
        BufferedReader din = null;
        StringBuilder stringBuilder = new StringBuilder();
        byte[] myByte = new byte[1024];
        byte[] fileByte = new byte[0];
        String file = "";
        String fileName = "";
        String line;
        try {
            socket = new Socket(host, port);
            socket.setSoTimeout(5000);
            // 建立连接后获得输出流
            socket.getOutputStream().write(message.getBytes("UTF-8"));
            is = socket.getInputStream();
            din = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            int count = 0;
            int max = 0;
            int now = 0;
            while ((line = din.readLine()) != null) {
                jsonObject = new JSONObject(line);
                file = jsonObject.getJSONObject("data").getObj("Buf").toString();
                fileName = jsonObject.getJSONObject("data").getObj("FileName").toString();
                int pos = fileName.lastIndexOf("/");
                fileName = fileName.substring(pos + 1);
                max = Integer.parseInt(jsonObject.getJSONObject("data").getObj("MaxFrame").toString());
                now = Integer.parseInt(jsonObject.getJSONObject("data").getObj("FrameIndex").toString());
                BASE64Decoder base = new BASE64Decoder();
                myByte = base.decodeBuffer(file);
                fileByte = mergeBytes(fileByte, myByte);
                if (now == max) {
                    count++;
                    map = new HashMap<>();
                    map.put(fileName, fileByte);
                    list.add(map);
                    fileByte = new byte[0];
                    if (count == counts) {
                        break;
                    }
                }
            }
        } catch (ConnectException e) {
            System.out.println("socket连接失败!");
            e.getMessage();
            userLog.getLog("socket连接", "失败", host, LogTypeEnum.SYSTEM.toString(), 1);
        } catch (IOException e) {
            e.getMessage();
            userLog.getLog("获取装置数据", "失败", host, LogTypeEnum.SYSTEM.toString(), 1);
        } finally {
            safeColse(socket, din, is, null);
        }
        return list;
    }

    //组合byte数组
    private static byte[] mergeBytes(byte[] data1, byte[] data2) {
        byte[] data3 = new byte[data1.length + data2.length];
        System.arraycopy(data1, 0, data3, 0, data1.length);
        System.arraycopy(data2, 0, data3, data1.length, data2.length);
        return data3;
    }

    /**
     * 重启成功的装置(定值)
     *
     * @author dhj
     * @date 2021/8/31
     */
    public void restartDevConValue(String json, String host, Integer port) {
        System.out.println("重启装置" + host + "命令：" + json);
        String loginName = TokenManager.getToken().getLoginName();
        String userId = TokenManager.getUserId();
        Runnable aaa = new Runnable() {
            @Override
            public void run() {
                Socket socket = null;
                BufferedReader bufferedReader = null;
                OutputStream outputStream = null;
                JSONObject jsonObject = null;
                String result = null;
                try {
                    socket = new Socket(host, port);
                    socket.setSoTimeout(1000*60*5);
                    outputStream = socket.getOutputStream();
                    outputStream.write(json.getBytes());
                    bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                    Socket socket1 = socket;



                    Runnable heart = new Runnable() {

                        @Override
                        public void run() {
                            finalConValue = true;
                            try {
                                while (finalConValue){
                                    Thread.sleep(5000);
                                    if(socket1!=null) {
                                        if (socket1.isConnected() && !socket1.isClosed()) {
                                            socket1.getOutputStream().write(new JSONObject().put("heart", "666").toString().getBytes());
                                        }
                                    }
                                    System.out.println("心跳发送成功");
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                                finalConValue = false;
                            }
                            System.out.println("是否发送心跳标识"+ finalConValue);
                        }
                    };
                    executorPool.execute(heart);


                    while ((result = bufferedReader.readLine()) != null) {
                        System.out.println(result);

                        try {
                            jsonObject = new JSONObject(result.trim());
                        } catch (Exception json) {
                            json.printStackTrace();
                            logger.error("终端升级重启命令发送失败" + json.getMessage());
                            break;
                        }
                        if ((jsonObject.get("resultcode")).equals(10000)) {
                            jsonObject.put("type", "181");
                            webSocketUtil.sendMessageFor(jsonObject.toString(), loginName);
                            //处理成功进行入库记录日志
                            //   Integer succeed = sumResMap.get(userId + host);
                            //   succeed++;
                            //  sumResMap.put(userId + host, succeed);
                        } else if ((jsonObject.get("resultcode")).equals(10008)) {
                            jsonObject.put("type", "181");
                            webSocketUtil.sendMessageFor(jsonObject.toString(), loginName);
                        } else if ((jsonObject.get("resultcode")).equals(10001)) {
                            jsonObject.put("type", "181");
                            webSocketUtil.sendMessageFor(jsonObject.toString(), loginName);
                            break;
                            //重启成功进行入库记录日志
//                            Integer succeed = sumResMap.get(userId + host);
//                            succeed++;
//                            sumResMap.put(userId + host, succeed);
                        } else {
//                            Integer succeed = sumResMap.get(userId + host);
//                            succeed++;
//                            sumResMap.put(userId + host, succeed);
                        }
                    }

                } catch (SocketTimeoutException e) {
                    //超时处理
                    try {
                        JSONObject json = new JSONObject();
                        json.put("resultcode",5555);
                        json.put("resultmsg","超时");
                        json.put("type",181);
                        webSocketUtil.sendMessageFor(json.toString(), loginName);
                    } catch (IOException ioException) {
                        ioException.printStackTrace();
                    }
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception ee) {
                    ee.printStackTrace();
                } finally {
                    finalConValue = false;
                    System.out.println("重启socket结束+++");
                    safeColse(socket, bufferedReader, null, outputStream);
                    socketMap.remove(userId + host);
                }

            }
        };
        executorPool.execute(aaa);

    }


    //稳态数据补招
    public String sentIntegrityData(String message, String host, Integer port) {
        String result = "";
        String res = "";
        Socket socket = null;
        InputStream is = null;
        BufferedReader din = null;

        try {
            socket = new Socket(host, port);
            socket.setSoTimeout(8000);//设置超时时间
            socket.getOutputStream().write(message.getBytes("UTF-8"));
            is = socket.getInputStream();
            din = new BufferedReader(new InputStreamReader(is, "UTF-8"));


            while((result = din.readLine())!=null){
                System.out.println(result);
                net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(result);
                if(jsonObject.get("resultcode").equals("10000")){
                    res ="稳态数据补招命令接收成功";
                }else{
                    res = "稳态数据补招命令接收失败";
                }
                break;
            }
            return res;
        }catch (SocketTimeoutException e){
            return "Socket等待超时";
        }catch (ConnectException e){
            return "Socket连接异常";
        } catch (Exception e){
            return "稳态数据补招命令异常";
        } finally {
            safeColse(socket,din,is,null);
        }
    }
}





