<template>
  <div class="login">
    <div class="login-home">
      <div class="login-title">
        <h1>美术阅卷系统登录</h1>
      </div>
      <div class="login-box">
        <h2>欢迎登录</h2>
        <div class="login-form">
          <Form ref="loginForm" :model="loginModel" :rules="loginRules">
            <FormItem prop="loginName">
              <Input
                v-model.trim="loginModel.loginName"
                prefix="md-person"
                placeholder="请输入用户名"
                clearable
              ></Input>
            </FormItem>
            <FormItem prop="password">
              <Input
                type="password"
                v-model.trim="loginModel.password"
                prefix="md-lock"
                placeholder="请输入密码"
                clearable
              ></Input>
            </FormItem>
            <FormItem>
              <Button
                long
                type="primary"
                :disabled="isSubmit"
                @click="submit('loginForm')"
                >登录</Button
              >
            </FormItem>
          </Form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { username, password } from "@/plugins/formRules";
import { login } from "./api";

export default {
  name: "login",
  data() {
    return {
      loginModel: {
        loginName: "test1",
        password: "123456"
      },
      loginRules: {
        loginName: username,
        password
      },
      isSubmit: false
    };
  },
  mounted() {
    this.$ls.clear();
  },
  methods: {
    async submit(name) {
      const valid = await this.$refs[name].validate();
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      const data = await login(this.loginModel).catch(() => {
        this.isSubmit = false;
      });
      if (!data) return;

      this.isSubmit = false;
      this.$ls.set("user", data, this.GLOBAL.authTimeout);
      this.$store.commit("setUser", data);
      this.$router.push({
        name: "Subject"
      });
    }
  }
};
</script>
