<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"
                >登录</Button
              >
            </FormItem>
          </Form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { username, password } from "@/plugins/formRules";
import initStoreMixin from "../mixins/initStoreMixin";
import { formatDate } from "../plugins/utils";
import { $get } from "@/plugins/axios";

export default {
  name: "login",
  mixins: [initStoreMixin],
  data() {
    return {
      loginModel: {
        loginname: "test1",
        password: "111111"
      },
      loginRules: {
        loginname: username,
        password
      },
      isSubmit: false
    };
  },
  mounted() {
    this.$ls.clear();
  },
  methods: {
    submit1() {
      this.$router.push({
        name: "Subject"
      });
    },
    async submit(name) {
      const valid = await this.$refs.loginForm.validate();
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      const data = await $get(
        "/api/user/login",
        this.loginModel
      ).catch(() => {});
      this.isSubmit = false;
      if (!data) return;

      await this.initScanArea(data.subjects);
      await this.initStore();

      data.loginTime = formatDate();

      this.$ls.set("user", data);
      this.$store.commit("setUser", data);
      this.$store.commit("client/setClientConfig", {
        imageEnc: data.imageEnc,
        isPackageMode: data.isPackageMode,
        isLevelKnown: data.isLevelKnown
      });
      this.$router.push({
        name: "Subject"
      });
    }
  }
};
</script>
