import "./login.scss";
import {Input, Button, message} from "antd";
import {useState, useEffect} from "react";
import {useNavigate} from 'react-router-dom'
import axios from '@/utils/axios.js'
export default function Login() {
    let navagite = useNavigate()
    // 用户名
    const [user, setUser] = useState("");
    // 密码
    const [password, setPassword] = useState("");
    const [messageApi, contextHolder] = message.useMessage();

    // 点击登陆调用
    async function goLogin() {
      let {data,code,message}= await  axios.post('/sys/login',{account:user,password:password})
        if (code===200) {
            localStorage.setItem('user',JSON.stringify(data))
            messageApi.success("登陆成功");
            navagite("/statisticsData")
        } else {
            messageApi.error(message);
        }
    }

    // 全局login
    function enterLogin(e) {
        if (e.keyCode === 13) {
            goLogin()
        }
    }
    // 添加全局enter
    useEffect(() => {
        window.addEventListener('keydown', enterLogin); // 添加全局事件
        return () => {
            window.removeEventListener('keydown', enterLogin); // 销毁
        };
    }, [user, password]);
    return (
        <div className="login">
            {contextHolder}
            <div className="box">
                <h1>管理系统</h1>
                <Input
                    placeholder="请输入用户名"
                    className="user"
                    value={user}
                    onChange={(e) => setUser(e.target.value)}
                />
                <Input.Password
                    placeholder="请输入密码"
                    className="password"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                />
                <Button type="primary" onClick={goLogin}>
                    登陆
                </Button>
            </div>
        </div>
    );
}
