package com.zksy.lamp.server;

import com.zksy.common.exception.CommonException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author Administrator
 * @version 1.0
 * @project dh-server-micro
 * @description 指令执行
 * @date 2025/2/10 16:25:14
 */
@Component
public class ExecutionServer {
    private static final Logger log = LoggerFactory.getLogger(ExecutionServer.class);
    private BufferedReader reader;
    private BufferedWriter writer;
    private ServerSocket server;
    private Socket client;
    private int serverPort = 15678;

    @PostConstruct
    public void init(){
        Runnable func0 = this::startServer;
        Thread thread = new Thread(func0);
        thread.start();
    }

    @PreDestroy
    public void closeResource(){
        try {
            if (reader != null) reader.close();
            if (writer != null) writer.close();
            if (client != null) client.close();
            if (server != null) server.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 启动服务器并等待客户端连接
     */
    public void startServer() {
        try {
            System.out.println("本机作为服务端");
            System.out.println("本机端口：" + serverPort);
            server = new ServerSocket(serverPort);

            System.out.println("等待客户机的连接");
            client = server.accept();
            System.out.println("连接成功");

            reader = new BufferedReader(new InputStreamReader(client.getInputStream(), "GB2312"));
            writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream(), "GB2312"));
            System.out.println("测试完成！");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public String ExecutionData(String msg) {
        try {
            String returnMsgReplace = "";
            System.out.println("第1路闭合，发送指令："+msg);
            //发送数据
            writer.write(msg);
            writer.flush();
            //读数据
            String returnMsg = reader.readLine();
            System.out.println("returnMsg================："+returnMsg);
            if (returnMsg != null) {
                returnMsgReplace = returnMsg.replace("\r\n", "\\r\\n");
                System.out.println("设备应答：" + returnMsgReplace);
            } else {
                System.out.println("接收到的消息为 null，重新建立连接...");
                // 关闭当前连接资源
                closeResource();
                // 重新启动服务器并等待客户端连接
                startServer();
                // 重新发送指令
                writer.write(msg);
                writer.flush();
                String returnMsg2 = reader.readLine();
                returnMsgReplace = returnMsg2.replace("\r\n", "\\r\\n");
                System.out.println("重新连接后接收到的消息：" + returnMsgReplace);
            }
            if("AT".equals(returnMsgReplace)) {
                String s = "AT+ACK\r\n";
                writer.write(s);
                writer.flush();
                throw new CommonException("当次设置失败,请再次设置",456);
            }
            System.out.println("指令执行成功!");
            return returnMsgReplace;
        } catch (Exception e) {
            log.info(e.toString());
            throw new RuntimeException("指令执行失败");
        }
    }
}

