<template>
  <div class="login">
    <main class="login-main">
      <div class="login-title">
        <p>欢迎登录</p>
        <p>题库管理系统</p>
      </div>
      <div class="login-footer">
        Copyright &copy; 2021
        <a href="https://www.qmth.com.cn" target="_block">启明泰和</a>.<a
          href="https://beian.miit.gov.cn/"
          target="_blank"
          >鄂ICP备12000033号-13</a
        >
      </div>
      <div class="login-body" @keyup.enter="submit">
        <h1 class="login-body-title">题库管理系统</h1>
        <el-form ref="loginForm" :model="loginInfo" :rules="loginRules">
          <el-form-item prop="accountValue">
            <el-input
              v-model.trim="loginInfo.accountValue"
              placeholder="请输入账号"
              clearable
            >
              <i slot="prefix" class="icon icon-username"></i>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model.trim="loginInfo.password"
              type="password"
              placeholder="请输入密码"
              clearable
            >
              <i slot="prefix" class="icon icon-password"></i>
            </el-input>
          </el-form-item>
          <el-form-item v-if="dialogVisible" prop="smsCode">
            <el-input
              v-model.trim="loginInfo.smsCode"
              placeholder="请输入短信验证码"
              clearable=""
            >
              <i slot="prefix" class="icon icon-code"></i>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              class="login-submit-btn"
              type="danger"
              :disabled="isSubmit"
              @click="submit"
              >登录</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </main>
  </div>
</template>

<script>
import { mapActions } from "vuex";
import { USER_SIGNIN } from "../store/user";
import { QUESTION_API } from "@/constants/constants";

export default {
  data() {
    return {
      isSubmit: false,
      dialogVisible: false,
      loginInfo: {
        rootOrgId: "",
        domain: "",
        accountType: "COMMON_LOGIN_NAME",
        accountValue: "",
        password: "",
        smsCode: null,
      },
      loginRules: {
        accountValue: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "change",
          },
        ],
        password: [
          {
            validator: (rule, value, callback) => {
              if (
                value &&
                (/^([0-9]+|[a-z]+|[A-Z]+)$/.test(value) ||
                  !/^[a-zA-Z0-9_]+$/.test(value))
              ) {
                callback(
                  new Error("密码只能大写字母、小写字母、数字至少两种组成")
                );
              } else {
                callback();
              }
            },
            trigger: "change",
          },
          {
            required: true,
            min: 8,
            max: 16,
            message: "密码只能8-16个字符",
            trigger: "change",
          },
        ],
        // password: [
        //   {
        //     required: true,
        //     pattern: /^[a-zA-Z0-9_]{1,20}$/,
        //     message: "密码只能由数字、字母和下划线组成，长度1-20个字符",
        //     trigger: "change",
        //   },
        // ],
        smsCode: [
          {
            required: true,
            message: "请输入短信验证码",
            trigger: "change",
          },
        ],
      },
    };
  },
  watch: {
    $route(to) {
      this.loginInfo.rootOrgId = to.query.orgId;
    },
  },
  created() {
    if (this.$route.hash && this.$route.hash.startsWith("#/access?")) {
      this.$router.push(this.$route.hash.slice(1));
      return;
    }
    this.loginInfo.domain = window.location.hostname.split(".")[0];
    sessionStorage.clear();
    var params = this.$route.query;

    this.loginInfo.rootOrgId = params.orgId;
  },
  methods: {
    ...mapActions([USER_SIGNIN]),
    async submit() {
      const valid = await this.$refs.loginForm.validate().catch(() => {});
      if (!valid) return;

      var url = QUESTION_API + "/auth/login";
      this.$httpWithMsg
        .post(url, this.loginInfo)
        .then((response) => {
          var user = response.data;
          user.questionUnlock = false;
          this.USER_SIGNIN(user);
          this.$router.replace({ path: "/questions/tips" });
          this.$notify({
            message: "登录成功",
            type: "success",
            duration: 1000,
          });
        })
        .catch((error) => {
          if (error.response.data.code === "UQ-003100") {
            this.dialogVisible = true;
          }
        });
    },
    loginWithSms() {
      this.dialogVisible = false;
      this.submit();
    },
  },
};
</script>
