package Pages;

import Util.BasicOperation;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.sql.SQLException;

public class Register {
    public static void main() {
        // 初始JFrame
        JFrame jFrame = new JFrame("用户注册");
        jFrame.setSize(400,400);
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // 初始JPanel
        JPanel jPanel = new JPanel();
        // 将panel添加到frame
        jFrame.add(jPanel);
        // 调用组件构造函数
        placeRegisterComponents(jFrame,jPanel);
        // 设置可视化
        jFrame.setVisible(true);
    }

    private static void placeRegisterComponents(JFrame jFrame,JPanel jPanel) {
        // placeRegisterComponents方法
        jPanel.setLayout(null);

        JButton callBack = new JButton("返回");
        callBack.setBounds(325,5,60,25);
        callBack.setContentAreaFilled(false);
        callBack.setBorder(null);
        callBack.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                jFrame.dispose();
                Login.main();
            }
        });
        jPanel.add(callBack);

        JLabel title = new JLabel("用户注册");
        title.setBounds(170,85,60,25);
        jPanel.add(title);

        JLabel username = new JLabel("用户");
        username.setBounds(120,120,40,25);
        jPanel.add(username);

        JTextField nameField = new JTextField(20);
        nameField.setBounds(160,120,100,25);
        jPanel.add(nameField);

        JLabel password = new JLabel("密码");
        password.setBounds(120,155,40,25);
        jPanel.add(password);

        JPasswordField passwordField = new JPasswordField(20);
        passwordField.setBounds(160,155,100,25);
        jPanel.add(passwordField);

        JButton register = new JButton("注册");
        register.setBounds(120,190,140,25);
        register.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String username = nameField.getText();
                String password = new String(passwordField.getPassword());
                int admin = 0;
                BasicOperation basicOperation = new BasicOperation();
                try {
                    if (basicOperation.registerCheck(username,password,admin)) {
                        JOptionPane.showMessageDialog(jPanel,"注册成功");
                        jFrame.dispose();
                        Login.main();
                    } else {
                        JOptionPane.showMessageDialog(jPanel,"注册失败，请重新注册");
                    }
                } catch (SQLException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });
        jPanel.add(register);
    }
}
