package com.example;

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

public class Main extends JFrame implements ActionListener {

    JButton jb1,jb2,jb3;
    JTextField tf1,tf3;
    JPasswordField tf2;
    JLabel jl1,jl2,jl3,jl4;
    Random rand = new Random();
    Main(){
        super("登录");
        jb1=new JButton("登录");
        jb2=new JButton("取消");
        tf1=new JTextField(6);
        tf2=new JPasswordField(6);
        tf3=new JTextField(6);
        jl1=new JLabel("用户名",JLabel.CENTER);
        jl2=new JLabel("密码",JLabel.CENTER);
        jl3=new JLabel("验证码",JLabel.CENTER);
        jl4=new JLabel("验证码：",JLabel.CENTER);
        jb3=new JButton("");
        jb1.addActionListener(this);
        jb2.addActionListener(this);
        jb3.addActionListener(this);
        setLayout(new GridLayout(5,2));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        add(jl1);add(tf1);
        add(jl2);add(tf2);
        add(jl3);add(tf3);
        add(jl4);add(jb3);
        add(jb1);add(jb2);
        jb3.setText(Integer.toString(rand.nextInt(100)+100));
        setSize(500,500);
        setLocationRelativeTo(null);

        setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {

        if(e.getSource()==jb1){
            Jdbc jdbc = new Jdbc();
            String sql = "select * from user where username='"+tf1.getText()+"' and password='"+tf2.getText()+"'"; ;
            try {
                ResultSet rs = jdbc.query(sql);
                if(rs.next()&&tf3.getText().equals(jb3.getText())) {
                    JOptionPane.showMessageDialog(null, "登录成功");
                    new Home();
                    this.setVisible(false);
                }
                else{
                    JOptionPane.showMessageDialog(null,"登录失败");
                    jb3.setText(Integer.toString(rand.nextInt(100)+100));
                }
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(null,"出现错误");
                throw new RuntimeException(ex);
            }
        }else if(e.getSource()==jb2){
            System.exit(0);
        }else if(e.getSource()==jb3){
            jb3.setText(Integer.toString(rand.nextInt(100)+100));
        }
    }

    public static void main(String[] args) {
        new  Main();
    }
}