package com.qst.dms.ui;

import com.qst.dms.entity.User;
import com.qst.dms.security.String_SHA_256;
import com.qst.dms.service.UserService;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;

import java.sql.SQLException;


public class LoginFXML
{
    @FXML
    private TextField Username;
    @FXML
    private PasswordField Password;
    @FXML
    private Button Login_Button;
    @FXML
    private Button Reset_Button;
    @FXML
    private Button Register_Button;
    @FXML
    void Login(ActionEvent event)
    {
        UserService userService =new UserService();
        try
        {
            User user = userService.findUserByName(Username.getText());
            if(user==null||!(String_SHA_256.String_to_SHA256(Password.getText()).equals(user.getPassword())))
                Login_failed();
            else
            {
                InfoInputFXML.loginUser = Username.getText();
                LoginFrame.close_scene();
            }
        }
        catch(SQLException e)
        {
            SQLErrorAlert(0);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    void SQLErrorAlert(int type)
    {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("错误");
        alert.setHeaderText("连接到sql数据库失败");
        if(type==0)
            alert.setContentText("当前无法校验用户名和密码");
        if(type==1)
            alert.setContentText("当前无法添加用户");
        alert.showAndWait();
    }
    @FXML
    void Reset(ActionEvent event)
    {
        Username.clear();
        Password.clear();
    }
    @FXML
    void Register(ActionEvent event)
    {
        UserService userService =new UserService();
        try
        {
            User user = userService.findUserByName("");
            RegistFrame.main(null);
        }
        catch (SQLException e)
        {
            SQLErrorAlert(1);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
    void Login_failed()
    {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("错误");
        alert.setHeaderText("用户名或密码错误");
        alert.setContentText("请检查输入的用户名和密码");
        alert.showAndWait();
    }


}
