import styles from "./index.module.scss";

import { Input, Button } from "antd";
import { UserOutlined, LockOutlined } from "@ant-design/icons";
import { useEffect, useState } from "react";
import { Base64 } from "js-base64";
import encodeStr from "@/utils/pass";
import { userLoginAPI } from "@/store/action/login";
import { setTokenInfo } from "@/utils/storage";
import history from "@/utils/history";
import { useDispatch } from "react-redux";
import { MessageFu } from "@/utils/message";

export default function Login() {
  const dispatch = useDispatch();

  // 进登录页面把权限的信息初始化，防止登录成功之后进到首页，数据渲染问题
  useEffect(() => {
    dispatch({ type: "login/setAuthPageArr", payload: [] });
  }, [dispatch]);

  // 账号密码
  const [userName, setUserName] = useState("");
  const [passWord, setPassWord] = useState("");

  // 键盘按下回车事件
  const keyUpEntFu = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter") loginClickFu();
  };
  // 点击登录
  const loginClickFu = async () => {
    // 非空判断
    if (userName === "") return MessageFu.warning("请填写用户账号!");
    else if (passWord === "") return MessageFu.warning("请填写登录密码!");
    const obj = {
      userName,
      passWord: encodeStr(Base64.encode(passWord)),
    };
    const res: any = await userLoginAPI(obj);
    if (res.code === 0) {
      MessageFu.success("登录成功");
      // 用户信息存到本地
      setTokenInfo(res.data);
      history.push("/");
    }
  };

  return (
    <div className={styles.Login}>
      <div className="main">
        <h1>乐山大佛博物馆馆藏管理系统</h1>
        <p>LESHAN DAFO MUSEUMCOLLECTION MANAGEMENT SYSTEM</p>
        {/* 账号密码输入框 */}
        <div className="inputBox">
          <Input
            onKeyUp={(e) => keyUpEntFu(e)}
            value={userName}
            onChange={(e) => setUserName(e.target.value.trim())}
            prefix={<UserOutlined />}
            placeholder="请输入用户名称"
            maxLength={15}
          />
          <Input.Password
            onKeyUp={(e) => keyUpEntFu(e)}
            value={passWord}
            onChange={(e) => setPassWord(e.target.value.trim())}
            prefix={<LockOutlined />}
            placeholder="请输入登录密码"
            maxLength={15}
          />
        </div>

        {/* 登录按钮 */}
        <div className="loginBtn">
          <Button type="primary" size="large" onClick={loginClickFu}>
            登 录
          </Button>
        </div>
      </div>
    </div>
  );
}
