<template>
  <div
    class="
      login_background
      min-h-screen
      bg-center bg-cover
      flex flex-col
      justify-center
    "
  >
    <p class="text-3xl semi-bold text-white text-center mb-10">
      中小企业普惠金融管理平台
    </p>
    <div class="flex items-center">
      <div
        class="
          w-96
          bg-white
          mx-auto
          py-9
          rounded-lg
          ring-15 ring-white ring-opacity-40
        "
      >
        <div class="w-60 mx-auto text-center">
          <a-tabs default-active-key="1" @change="toggleLoginWay">
            <!-- 账号登录 -->
            <a-tab-pane key="1" tab="密码登录">
              <a-form-model
                v-if="!loading"
                :model="loginByPwdForm"
                :rules="loginByPwdForm.rule"
                ref="loginByPwdForm"
              >
                <a-form-model-item prop="username">
                  <a-input
                    placeholder="请输入账号"
                    v-model="loginByPwdForm.username"
                  >
                    <a-icon slot="prefix" type="user" />
                  </a-input>
                </a-form-model-item>
                <a-form-model-item prop="password">
                  <a-input-password
                    placeholder="请输入密码"
                    type="password"
                    v-model="loginByPwdForm.password"
                  >
                    <a-icon slot="prefix" type="lock" />
                  </a-input-password>
                </a-form-model-item>
              </a-form-model>
              <div v-else class="example">
                <a-spin size="large" />
              </div>
            </a-tab-pane>
            <!-- 验证码登录 -->
            <a-tab-pane key="2" tab="验证码登录" force-render>
              <a-form-model
                v-if="!loading"
                :model="loginBySmsForm"
                :rules="loginBySmsForm.rule"
                ref="loginBySmsForm"
              >
                <a-form-model-item prop="phoneNumber">
                  <a-input
                    placeholder="请输入手机号"
                    :maxLength="11"
                    v-model="loginBySmsForm.phoneNumber"
                  >
                    <a-icon slot="prefix" type="phone" />
                  </a-input>
                </a-form-model-item>
                <a-form-model-item prop="validation">
                  <div class="w-full flex justify-between">
                    <a-input
                      style="width: 60%; margin-right: 10px"
                      placeholder="请输入验证码"
                      v-model="loginBySmsForm.validation"
                    />
                    <a-button
                      v-if="smsCount === 60"
                      @click="handleClickSendSms"
                    >
                      获取验证码
                    </a-button>
                    <a-button v-else type="primary" disabled>
                      已发送 {{ smsCount }} S
                    </a-button>
                  </div>
                </a-form-model-item>
              </a-form-model>
              <div v-else class="example">
                <a-spin size="large" />
              </div>
            </a-tab-pane>
          </a-tabs>
          <a-button
            v-if="!loading"
            type="primary"
            @click="handleClickLogin"
            style="width: 100%; margin-bottom: 30px"
          >
            登录
          </a-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { eNewRoleRelatedToBackEnd, eRole } from "@/types/role";
import { setUserMsg } from "@/utils/userMsg/userMsg";
import { eLoginWay } from "./type";
import { phoneValid } from "./const";
import { isPhoneValid } from "@/utils/phone/index";
import { Tabs, FormModel, message, Icon } from "ant-design-vue";
import Vue from "vue";
import UserService from "@/service/UserManagementService";
import VerifyCodeService, { eSmsType } from "@/service/VerifyCodeService";

Vue.use(Tabs).use(Icon);

export default Vue.extend({
  props: {
    adminLogin: {
      type: Boolean,
      required: false,
      default: false,
    },
  },
  data() {
    return {
      smsCount: 60,
      smsLock: false,
      loginWay: eLoginWay.PWD,
      loading: false,
      loginByPwdForm: {
        username: "",
        password: "",
        rule: {
          username: [
            { required: true, message: "请输入账号", trigger: "blur" },
          ],
          password: [
            { required: true, message: "请输入密码", trigger: "blur" },
          ],
        },
      },
      loginBySmsForm: {
        phoneNumber: "",
        validation: "",
        rule: {
          phoneNumber: [
            { required: true, message: "请输入手机号", trigger: "blur" },
            {
              pattern: phoneValid,
              message: "请输入有效手机号",
              trigger: "blur",
            },
          ],
          validation: [
            { required: true, message: "请输入验证码", trigger: "blur" },
          ],
        },
      },
      timerId1: 0,
    };
  },
  mounted() {
    this.adminLogin && this.initAdmin();
  },
  methods: {
    initAdmin() {
      this.loginByPwdForm.username = "admin";
    },
    toggleLoginWay(key: Number) {
      this.loginWay = key == 1 ? eLoginWay.PWD : eLoginWay.CODE;
    },
    sendSmsFunc(phone: string) {
      return VerifyCodeService.getInstance().send({
        phone,
        smsType: eSmsType.registerOrLogin,
      });
    },
    async handleClickSendSms() {
      const phoneValid = isPhoneValid(this.loginBySmsForm.phoneNumber);
      if (!phoneValid) return;
      if (this.smsLock === true) return;
      this.smsLock = true;
      try {
        await (this.sendSmsFunc &&
          this.sendSmsFunc(this.loginBySmsForm.phoneNumber));
      } catch (err) {
        this.smsLock = false;
        return;
      }
      this.smsCount--;
      this.timerId1 = window.setInterval(() => {
        this.smsCount--;
        if (this.smsCount === -1) {
          this.smsCount = 60;
          this.smsLock = false;
          window.clearInterval(this.timerId1);
        }
      }, 1000);
    },
    isValid(): Boolean {
      let isValid = false;
      if (this.loginWay == eLoginWay.PWD) {
        (this.$refs.loginByPwdForm as FormModel).validate((valid) => {
          if (valid) {
            isValid = true;
          }
        });
      } else {
        (this.$refs.loginBySmsForm as FormModel).validate((valid) => {
          if (valid) {
            isValid = true;
          }
        });
      }
      return isValid;
    },
    async loginByCodeFunc(phone: string, code: string) {
      const ret = await UserService.getInstance().login({
        is_admin: false,
        use_pwd: false,
        verify_code: code,
        phone,
      });
      if (ret.code === 200) {
        const { accessToken, level, phone, role, userType } = ret.data;
        setUserMsg({
          token: accessToken,
          newRole: this.adminLogin
            ? eNewRoleRelatedToBackEnd.PlatformAdmin
            : role,
          level: level,
          phone,
          userType,
        });
        this.$router.push({
          name: "home",
        });
      } else {
        // message.warn(ret.msg);
      }
    },
    async loginByPwdFunc(name: string, pwd: string) {
      const isAdminAccount = !!name.match(/admin/);
      const ret = await UserService.getInstance().login({
        is_admin: isAdminAccount,
        use_pwd: true,
        phone: isAdminAccount ? undefined : name,
        pwd,
      });
      console.log(ret);

      if (ret.code === 200) {
        const { accessToken, level, phone, role, userType } = ret.data;
        setUserMsg({
          token: accessToken,
          newRole: this.adminLogin
            ? eNewRoleRelatedToBackEnd.PlatformAdmin
            : role,
          level: level,
          phone,
          userType,
        });
        this.$router.push({
          name: "home",
        });
      }
    },
    async handleClickLogin() {
      if (this.isValid()) {
        const { username, password } = this.loginByPwdForm;
        const { phoneNumber, validation } = this.loginBySmsForm;
        this.loading = true;
        try {
          if (this.loginWay == eLoginWay.PWD) {
            // 调用登录接口
            await this.loginByPwdFunc(username, password);
          } else if (this.loginWay === eLoginWay.CODE) {
            // 调用登录接口
            await this.loginByCodeFunc(phoneNumber, validation);
          }
        } catch (err) {
          console.log(err);
        }
        this.loading = false;
      } else {
        return false;
      }
    },
  },
});
</script>

<style scoped>
.example {
  text-align: center;
  margin-bottom: 20px;
  padding: 30px 50px;
  margin: 20px 0;
}

.login_background {
  background-image: url(../../assets/login_background.png);
}
</style>