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

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

export default function Login() {
  // 账号密码
  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("/");
    } else if (res.code === 3014)
      MessageFu.warning("用户名不存在或密码错误，请联系管理员!");
  };

  return (
    <div className={styles.Login}>
      <div className="main">
        <div className="mainTitle">登 录</div>
        {/* 账号密码输入框 */}
        <div className="inputBox">
          <div className="inputBoxRow">
            <Input
              onKeyUp={(e) => keyUpEntFu(e)}
              value={userName}
              onChange={(e) => setUserName(e.target.value.trim())}
              prefix={<UserOutlined />}
              placeholder="请输入用户名"
              maxLength={15}
            />
          </div>
          <div className="inputBoxRow">
            <Input.Password
              onKeyUp={(e) => keyUpEntFu(e)}
              value={passWord}
              onChange={(e) => setPassWord(e.target.value.trim())}
              prefix={<LockOutlined />}
              placeholder="请输入用户密码"
              maxLength={15}
            />
          </div>
        </div>

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