import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class ChatWindow extends JFrame {
    private JTextArea receivedMessagesArea;
    private JTextField messageField;
    private JButton sendButton;
    private JTextField ipField;
    private JTextField portField;
    private JButton connectButton;
    private JButton disconnectButton;
    private JLabel connectionStatusLabel; // 连接状态标签
    private JTextArea sentMessagesArea;
    //private JTextArea chatArea;

    private Socket socket;
    private BufferedReader input;
    private OutputStream output;

    public ChatWindow() {
        setTitle("socket test Window1");
        setSize(800, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel contentPane = new JPanel(new BorderLayout());

        receivedMessagesArea = new JTextArea();
        receivedMessagesArea.setPreferredSize(new Dimension(400, receivedMessagesArea.getPreferredSize().height));
       // receivedMessagesArea.set
        receivedMessagesArea.setEditable(false);
        contentPane.add(new JScrollPane(receivedMessagesArea), BorderLayout.WEST);

        sentMessagesArea = new JTextArea(); // 初始化已发送消息的文本区域
        sentMessagesArea.setPreferredSize(new Dimension(400, sentMessagesArea.getPreferredSize().height));
        // 设置已发送消息的文本区域为只读
        sentMessagesArea.setEditable(false);
        // 重新发送功能的实现，例如在已发送消息区域的双击事件中进行重新发送

        //contentPane.add(new JScrollPane(sentMessagesArea), BorderLayout.EAST);
        contentPane.add(new JScrollPane(sentMessagesArea), BorderLayout.EAST);
        setContentPane(contentPane);

        JPanel messagePanel = new JPanel(new BorderLayout());
        messageField = new JTextField("{\"cmd\":\"loginreq\",\"ipaddr\":\"192.168.25.37\",\"serialNo\":\"23450501024971\",\"recordNumber\":4,\"webport\":80,\"filestoretype\":0}");
        sendButton = new JButton("Send");
        sendButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sendMessage(messageField.getText());
            }
        });
        messagePanel.add(messageField, BorderLayout.CENTER);
        messagePanel.add(sendButton, BorderLayout.EAST);
        add(messagePanel, BorderLayout.SOUTH);


        JPanel connectPanel = new JPanel();
        ipField = new JTextField("192.168.3.111",10);
        portField = new JTextField("8087",5);
        connectButton = new JButton("连接");
        disconnectButton = new JButton("断开");
        connectionStatusLabel = new JLabel("未连接");

        connectButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                connectToServer();
            }
        });

        disconnectButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                disconnectFromServer();
            }
        });

        connectPanel.add(new JLabel("Server IP:"));
        connectPanel.add(ipField);
        connectPanel.add(new JLabel("Port:"));
        connectPanel.add(portField);
        connectPanel.add(connectButton);
        connectPanel.add(disconnectButton);
        connectPanel.add(connectionStatusLabel);
        add(connectPanel, BorderLayout.NORTH);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    public void connectToServer() {
        String ip = ipField.getText();
        int port = Integer.parseInt(portField.getText());

        try {
            socket = new Socket(ip, port);
            input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            output = socket.getOutputStream();

            SwingUtilities.invokeLater(() -> {
                connectionStatusLabel.setText("已连接");
            });

            Thread receiveThread = new Thread(() -> {
                try {
                    char[] buffer = new char[1024]; // 用于存储读取的消息
                    int bytesRead;
                    while ((bytesRead = input.read(buffer, 0, buffer.length)) != -1) {
                        String message = new String(buffer, 0, bytesRead);
                        receivedMessagesArea.append(message+"\n");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            receiveThread.start();
        } catch (IOException e) {
            e.printStackTrace();
            // 更新连接状态为"连接断开"
            SwingUtilities.invokeLater(() -> {
                connectionStatusLabel.setText("已断开");
            });
        }
    }

    public void disconnectFromServer() {
        try {
            if (socket != null) {
                socket.close();
                socket = null;
                input = null;
                output = null;
            }
            SwingUtilities.invokeLater(() -> {
                connectionStatusLabel.setText("已断开");
            });
        } catch (IOException e) {
            e.printStackTrace();
            // 更新连接状态为"连接断开"
            SwingUtilities.invokeLater(() -> {
                connectionStatusLabel.setText("已断开");
            });
        }
    }

    public void sendMessage(String message) {
        //String message =
        sentMessagesArea.append(message + "\n");
        try {
            String header = message.length() + ""; // 根据实际情况替换为包头字符数
            byte[] requestData = message.getBytes(StandardCharsets.UTF_8); // 根据实际情况替换为请求字节数据

            // 发送包头字符数
            output.write(header.getBytes(StandardCharsets.UTF_8));

            // 发送请求数据
            output.write(requestData);
            //output.write(message.getBytes());
            //output.write('\n');
            output.flush();
            messageField.setText("");
        } catch (IOException e) {
            e.printStackTrace();
            // 更新连接状态为"连接断开"
            SwingUtilities.invokeLater(() -> {
                connectionStatusLabel.setText("Disconnected");
            });
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            ChatWindow chatWindow = new ChatWindow();
        });
    }
}