<template>
  <div class="login login-box">
    <div class="login-body">
      <div class="login-title">
        <h1>逸教云</h1>
      </div>
      <div class="login-form">
        <el-form ref="loginForm" :model="loginModel" :rules="loginRules">
          <el-form-item prop="loginName">
            <el-input
              v-model.trim="loginModel.loginName"
              placeholder="请输入账号"
              clearable
            >
              <i class="icon icon-user" slot="prefix"></i>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              type="password"
              v-model.trim="loginModel.password"
              placeholder="请输入密码"
              clearable
            >
              <i class="icon icon-lock" slot="prefix"></i
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              style="width:116px;"
              type="primary"
              :disabled="isSubmit"
              @click="submit('loginForm')"
              >登录</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="login-shadow-top"></div>
    <div class="login-shadow-bottom"></div>
  </div>
</template>

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

export default {
  name: "login",
  data() {
    return {
      loginModel: {
        loginName: "",
        password: ""
      },
      loginRules: {
        loginName: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "change"
          }
        ],
        password
      },
      roles: [],
      isSubmit: false
    };
  },
  mounted() {
    this.$ls.clear();
  },
  methods: {
    async submit(name) {
      const valid = await this.$refs[name].validate().catch(() => {});
      if (!valid) return;

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

      this.$ls.set("token", data.token, this.GLOBAL.authTimeout);
      this.$ls.set("schoolId", data.account.schoolId, this.GLOBAL.authTimeout);
      this.$ls.set("user", data.account, this.GLOBAL.authTimeout);
      this.$store.commit("setUser", data.account);
      this.$router.push({
        name: "Home"
      });
    }
  }
};
</script>
