package com.msksbr.MainFrm.MenuItemDiaog.Adder;

import com.msksbr.LoginFrm.ScreenSize;
import com.msksbr.SQL.Connector;

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

public class StudentAdder extends JDialog {
    private JPanel contentPane;
    private JButton buttonOK;
    private JTextField textField1;
    private JTextField IDField;
    private JTextField textField3;
    private JRadioButton maleRadioButton;
    private JRadioButton femaleRadioButton;
    private Connector connector;
    private String sName;
    private int sID;
    private String sClass;
    private String sGender;
    private ButtonGroup genderGroup;
    private String sql;

    public StudentAdder() {

        try {
            connector = new Connector();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        genderGroup = new ButtonGroup();
        genderGroup.add(maleRadioButton);
        genderGroup.add(femaleRadioButton);

        buttonOK.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onOK();
            }
        });

        try {
            sID = getStudentMaxID() + 1;
            IDField.setText(String.valueOf(sID));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        IDField.setEditable(false);

        setTitle("添加学生信息");
        setContentPane(contentPane);
        setModal(true);
        getRootPane().setDefaultButton(buttonOK);

        setSize(new Dimension(260, 265));
        setResizable(false);
        pack();
        setLocation();
        setVisible(true);

    }

    public void setLocation() {
        setLocation(new ScreenSize().width / 2 - getWidth() / 2, new ScreenSize().height / 2 - getHeight() / 2);
    }

    private void onOK() {
        // 在此处添加您的代码
        sName = textField1.getText();
        sClass = textField3.getText();
        sGender = maleRadioButton.isSelected() ? "男" : "女";
        sql = "INSERT INTO students (student_name,student_id,student_class,student_gender) VALUES ('" + sName + "'," + sID + ",'" + sClass + "','" + sGender + "');";
        commit2SQL();
        dispose();
    }

    private void commit2SQL() {
        try {
            connector.executeUpdate(sql);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public int getStudentMaxID() throws SQLException {
        ResultSet rs = connector.executeQuery("SELECT MAX(student_id) FROM students;");
        rs.next();
        return rs.getInt("MAX(student_id)");
    }
}
