<template>
  <div class="login login-box" @keyup.enter="submit('loginForm')">
    <el-tabs class="login-menu" v-model="loginType">
      <el-tab-pane label="密码登录" name="ACCOUNT"></el-tab-pane>
      <el-tab-pane
        v-if="schoolInfo.phoneLogin"
        label="短信登录"
        name="PHONE"
      ></el-tab-pane>
    </el-tabs>
    <div class="login-form">
      <el-form
        v-if="IS_USERNAME_TYPE"
        ref="loginForm"
        size="large"
        :model="loginModel"
        :rules="loginRules"
      >
        <el-form-item prop="loginName">
          <el-input
            v-model.trim="loginModel.loginName"
            placeholder="请输入你的账号"
            name="username"
            clearable
          >
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model.trim="loginModel.password"
            type="password"
            placeholder="请输入你的密码"
            name="password"
            show-password
            clearable
          >
          </el-input>
        </el-form-item>
        <el-form-item v-if="schoolInfo.accountSmsVerify" prop="code">
          <el-input
            v-model.trim="loginModel.code"
            placeholder="请输入手机验证码"
            name="code"
            clearable
            class="code-input"
          >
            <template slot="suffix">
              <el-button
                class="code-btn"
                type="text"
                size="medium"
                :disabled="isFetchingCode"
                @click="fetchAccountSmsCode"
                >{{ codeContent }}</el-button
              >
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            class="login-submit-btn"
            type="info"
            :disabled="isSubmit"
            @click="submit('loginForm')"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
      <el-form
        v-else
        ref="loginForm"
        size="large"
        :model="loginModel"
        :rules="loginRules"
      >
        <el-form-item prop="mobileNumber">
          <el-input
            v-model.trim="loginModel.mobileNumber"
            placeholder="请输入你的手机号"
            name="mobileNumber"
            clearable
          >
          </el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input
            v-model.trim="loginModel.code"
            placeholder="请输入你的验证码"
            name="code"
            clearable
            class="code-input"
          >
            <template slot="suffix">
              <el-button
                class="code-btn"
                type="text"
                size="medium"
                :disabled="isFetchingCode"
                @click.stop="fetchSmsCode"
                >{{ codeContent }}</el-button
              >
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            class="login-submit-btn"
            type="info"
            :disabled="isSubmit"
            @click="submit('loginForm')"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <!-- 修改密码 -->
    <reset-pwd
      :user-info="userInfo"
      ref="ResetPwd"
      @modified="resetPwdSuccess"
      @cancel="resetCancel"
    ></reset-pwd>
  </div>
</template>

<script>
import { phone, smscode } from "@/plugins/formRules";
import { login, getSmsCode, getSchoolInfo, getAccountSmsCode } from "../api";
import { Base64 } from "@/plugins/crypto";
import { MD5 } from "@/plugins/md5";
import ResetPwd from "@/modules/base/components/ResetPwd.vue";
import { getOrgCode } from "@/constants/app";
import fetchSmsMixins from "../fetchSmsMixins";

export default {
  name: "login",
  components: { ResetPwd },
  mixins: [fetchSmsMixins],
  data() {
    return {
      nameWaitTime: "login",
      smsCodeRequired: false,
      loginModel: {
        schoolCode: "",
        loginName: "",
        password: "",
        code: "",
        mobileNumber: "",
      },
      loginRules: {
        code: smscode,
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "change",
          },
        ],
        loginName: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "change",
          },
        ],
        schoolCode: [
          {
            required: true,
            message: "学校编码缺失",
            trigger: "change",
          },
        ],
        mobileNumber: phone,
      },
      userInfo: {},
      roles: [],
      isSubmit: false,
      loginType: "ACCOUNT",
      schoolInfo: {
        accountSmsVerify: false,
        phoneLogin: false,
      },
    };
  },
  mounted() {
    window.sessionStorage.removeItem("routeDomainCode");
    window.sessionStorage.removeItem("paramDomainCode");
    this.$ls.clear();
    this.setWaitingTime();
    this.getSchool();
  },
  computed: {
    IS_USERNAME_TYPE() {
      return this.loginType === "ACCOUNT";
    },
    switchBtnName() {
      return this.loginType === "ACCOUNT" ? "短信登录" : "账号登录";
    },
  },
  methods: {
    async getSchool() {
      if (this.$route.params.code) {
        this.loginModel.schoolCode = this.$route.params.code;
        window.sessionStorage.setItem(
          "routeDomainCode",
          this.$route.params.code
        );
      } else {
        this.loginModel.schoolCode = getOrgCode();
      }
      const data = await getSchoolInfo(this.loginModel.schoolCode);
      this.$ls.set("schoolLogo", data.logo);
      this.$ls.set("schoolName", data.name);
      this.$parent.version = data.version || "";
      this.$parent.schoolInfo = data;
      this.schoolInfo = data;
      this.loginModel.schoolCode = data.schoolCode;
      this.$ls.set("schoolInfo", data);
    },
    async submit(name) {
      const valid = await this.$refs[name].validate().catch(() => {});
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      let datas = {
        schoolCode: this.loginModel.schoolCode,
        type: this.loginType,
      };
      if (this.IS_USERNAME_TYPE) {
        datas = {
          ...datas,
          loginName: this.loginModel.loginName,
          password: Base64(this.loginModel.password),
        };
        if (this.schoolInfo.accountSmsVerify) datas.code = this.loginModel.code;
      } else {
        datas = {
          ...datas,
          code: this.loginModel.code,
          mobileNumber: this.loginModel.mobileNumber,
        };
      }
      const data = await login(datas).catch(() => {});
      this.isSubmit = false;
      if (!data) return;

      if (data.orgInfo)
        this.$ls.set("orgId", data.orgInfo.id, this.GLOBAL.authTimeout);
      if (data.schoolInfo && data.schoolInfo.length) {
        const curSchool = data.schoolInfo.find(
          (item) => item.code === this.loginModel.schoolCode
        );
        if (curSchool) {
          this.$ls.set("schoolId", curSchool.id, this.GLOBAL.authTimeout);
          this.$ls.set("schoolName", curSchool.name, this.GLOBAL.authTimeout);
        }
      }
      this.$ls.set(
        "user",
        { ...data, pwd: MD5(this.loginModel.password) },
        this.GLOBAL.authTimeout
      );

      this.$ls.set("token", data.accessToken, this.GLOBAL.authTimeout);

      // 强制修改密码和绑定手机号
      if (
        data.userLoginCheckResult &&
        (!data.userLoginCheckResult.pwdCount ||
          (!data.userLoginCheckResult.mobileNumber &&
            this.schoolInfo.phoneLogin))
      ) {
        this.userInfo = {
          ...this.loginModel,
          ...data.userLoginCheckResult,
          phoneLogin: this.schoolInfo.phoneLogin,
        };
        this.$refs.ResetPwd.open();
        return;
      }

      if (data.roleList && data.roleList.includes("ADMIN")) {
        this.$router.push({
          name: "SelectSchool",
        });
      } else {
        this.$router.push({
          name: "Home",
        });
      }
    },
    resetPwdSuccess(data) {
      if (data.orgInfo)
        this.$ls.set("orgId", data.orgInfo.id, this.GLOBAL.authTimeout);
      if (data.schoolInfo && data.schoolInfo.length) {
        const curSchool = data.schoolInfo.find(
          (item) => item.code === this.loginModel.schoolCode
        );
        if (curSchool) {
          this.$ls.set("schoolId", curSchool.id, this.GLOBAL.authTimeout);
          this.$ls.set("schoolName", curSchool.name, this.GLOBAL.authTimeout);
        }
      }
      this.$ls.set(
        "user",
        { ...data, pwd: MD5(this.loginModel.password) },
        this.GLOBAL.authTimeout
      );

      this.$ls.set("token", data.accessToken, this.GLOBAL.authTimeout);

      if (data.roleList && data.roleList.includes("ADMIN")) {
        this.$router.push({
          name: "SelectSchool",
        });
      } else {
        this.$router.push({
          name: "Home",
        });
      }
    },
    resetCancel() {
      this.$ls.remove("orgId");
      this.$ls.remove("schoolId");
      this.$ls.remove("schoolName");
      this.$ls.remove("user");
      this.$ls.remove("token");
    },
    // code valid
    checkField(field) {
      return new Promise((resolve, reject) => {
        this.$refs.loginForm.validateField(field, (unvalid) => {
          if (unvalid) {
            reject();
          } else {
            resolve();
          }
        });
      });
    },
    async fetchSmsCode() {
      let result = true;
      await this.checkField("mobileNumber").catch(() => {
        result = false;
      });
      if (!result) return;

      this.isFetchingCode = true;
      const data = await getSmsCode({
        schoolCode: this.loginModel.schoolCode,
        mobileNumber: this.loginModel.mobileNumber,
      }).catch(() => {
        this.isFetchingCode = false;
      });
      if (!data) return;

      if (data.mobileNumber) {
        this.$message.success(
          `已向手机尾号【${data.mobileNumber.slice(
            -4
          )}】成功发送短信，请在2分钟内进行验证！`
        );
        this.changeContent();
      } else {
        this.isFetchingCode = false;
        this.$message.error("未绑定手机号，请先绑定！");
        // this.userInfo = {
        //   ...data,
        //   loginName: this.loginModel.loginName,
        //   schoolCode: this.loginModel.schoolCode,
        //   password: this.loginModel.password
        // };
        // this.$refs.ResetPwd.open();
      }
    },
    async fetchAccountSmsCode() {
      const validAll = [
        this.checkField("loginName"),
        this.checkField("password"),
      ];

      let result = true;
      await Promise.all(validAll).catch(() => {
        result = false;
      });

      if (!result) return;

      this.isFetchingCode = true;
      const data = await getAccountSmsCode({
        schoolCode: this.loginModel.schoolCode,
        loginName: this.loginModel.loginName,
        password: Base64(this.loginModel.password),
      }).catch(() => {
        this.isFetchingCode = false;
      });
      if (!data) return;

      if (data) {
        this.$message.success(
          `已向手机尾号【${data.slice(-4)}】成功发送短信，请在2分钟内进行验证！`
        );
        this.changeContent();
      } else {
        this.isFetchingCode = false;
        this.$message.error("未绑定手机号！");
      }
    },
  },
};
</script>
