package chapter_13_solution;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.io.*;
import java.util.*;
import java.util.List;

public class PatientOperate extends JFrame {

    private static final String FILE_PATH = "database.txt";
    private static final String[] COLUMN_NAMES = {"患者姓名", "患者身份证号", "患者手机号", "患者地址"};

    public static void main(String[] args) {

        // 创建窗口
        JFrame mainFrame = new JFrame();
        // 设置窗口关闭操作（EXIT_ON_CLOSE表示关闭窗口时退出程序）
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // 设置窗口标题
        mainFrame.setTitle("患者信息管理");
        // 设置窗口大小（宽度，高度）
        mainFrame.setSize(800, 500);
        // 设置窗口的初始位置（null表示居中显示，但具体实现可能依赖于平台和Look and Feel）
        mainFrame.setLocationRelativeTo(null);
        // 设置窗口的布局为null（使用绝对定位）
        mainFrame.setLayout(null);

        // 初始化左右面板，此面板使用1行4列的网格布局，组件水平间隔10像素，垂直间隔10像素
        JPanel panelleft=new JPanel(new GridLayout(6,1,10,10));
        panelleft.setBorder(BorderFactory.createTitledBorder("患者信息录入"));
        panelleft.setBounds(10,10,220,450);

        // 创建文本框
        JTextField nameField = new JTextField(10);
        JTextField idCarNoField = new JTextField(10);
        JTextField phoneNoField = new JTextField(10);
        JTextField addrField = new JTextField(10);

        JPanel panelName = new JPanel(new GridLayout(2,1));
        panelName.add(new JLabel("请输入患者姓名:"));
        panelName.add(nameField);

        JPanel panelIdCardNo = new JPanel(new GridLayout(2,1));
        panelIdCardNo.add(new JLabel("请输入患者身份证号:"));
        panelIdCardNo.add(idCarNoField);

        JPanel panelPhoneNo = new JPanel(new GridLayout(2,1));
        panelPhoneNo.add(new JLabel("请输入患者手机号:"));
        panelPhoneNo.add(phoneNoField);

        JPanel panelAddr = new JPanel(new GridLayout(2,1));
        panelAddr.add(new JLabel("请输入患者地址:"));
        panelAddr.add(addrField);

        // 创建按钮
        JPanel panelButtonSave = new JPanel(null);
        JButton saveButton = new JButton("保存患者信息");
        saveButton.setBounds(0,20,205,36);
        panelButtonSave.add(saveButton);

        // 添加按钮的 ActionListener
        saveButton.addActionListener(e -> {
            if (nameField.getText().isEmpty() || idCarNoField.getText().isEmpty()
                    || phoneNoField.getText().isEmpty() || addrField.getText().isEmpty()) {
                JOptionPane optionPaneWarning = new JOptionPane();
                JOptionPane.showMessageDialog(optionPaneWarning, "患者信息不能为空！");
                return;
            }
            PatientVO currPatient = new PatientVO(
                    nameField.getText(),
                    idCarNoField.getText(),
                    phoneNoField.getText(),
                    addrField.getText()
            );
            addPatient(currPatient);
            SwingUtilities.invokeLater(() -> {
                nameField.setText("");
                idCarNoField.setText("");
                phoneNoField.setText("");
                addrField.setText("");
            });
        });

        panelleft.add(panelName);
        panelleft.add(panelIdCardNo);
        panelleft.add(panelPhoneNo);
        panelleft.add(panelAddr);
        panelleft.add(panelButtonSave);

        // 初始化右面板
        JPanel panelRight=new JPanel(new GridLayout(2,1,10,10));
        panelRight.setBorder(BorderFactory.createTitledBorder("患者信息查询"));
        panelRight.setBounds(235,10,555,450);

        // 创建按钮
        JPanel panelButtonSearch = new JPanel(null);
        JButton searchButton = new JButton("查询患者信息");
        searchButton.setBounds(0,0,205,36);
        panelButtonSearch.add(searchButton);

        // 创建 JTable 实例，并使用上面创建的 TableModel
        JTable table = new JTable();

        // 将 JTable 放入 JScrollPane 中，以便在需要时提供滚动功能
        JScrollPane scrollPane = new JScrollPane(table);

        // 添加按钮的 ActionListener
        searchButton.addActionListener(e -> {
            // 将数据转换为二维数组
            List<String[]> patients = getAllPatients();
            Object[][] arrayData = new Object[patients.size()][];
            for (int i = 0; i < patients.size(); i++) {
                arrayData[i] = patients.get(i);
            }
            SwingUtilities.invokeLater(() -> {
                // 使用列名和数据创建 DefaultTableModel 实例
                DefaultTableModel model = new DefaultTableModel(arrayData, COLUMN_NAMES);
                table.setModel(model);
            });
        });

        panelRight.add(scrollPane);
        panelRight.add(panelButtonSearch);

        mainFrame.add(panelleft);
        mainFrame.add(panelRight);

        // 设置窗口为可见（必须调用此方法来显示窗口）
        mainFrame.setVisible(true);
    }

    public static void addPatient(PatientVO patient) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(FILE_PATH, true))) {
            writer.write(
                    patient.getName() + ',' +
                            patient.getIdCardNo() + ',' +
                            patient.getPhoneNumber() + ',' +
                            patient.getAddress());
            writer.newLine();
            JOptionPane optionPaneSuccess = new JOptionPane();
            JOptionPane.showMessageDialog(optionPaneSuccess, "患者信息添加成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static List<String[]> getAllPatients() {
        List<String[]> patientsList = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] dataSplit = line.split(",");
                patientsList.add(dataSplit);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return patientsList;
    }
}

