<template>
  <div class="login">
    <div class="loginBg"></div>
    <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
      <div class="title">课件收集管理系统</div>
      <div class="login-con">
        <el-form-item prop="phonenumber">
          <el-input v-model="loginForm.phonenumber" type="text" size="large" auto-complete="off" placeholder="请输入手机号">
            <template #prefix>
              <!-- <svg-icon icon-class="user" class="el-input__icon input-icon" /> -->
              <img style="width: 16px;height: 16px;" src="@/assets/images/phone.png" alt="" />
              <!-- <el-image style="width: 16px;height: 16px;" fit="cover" src="../assets/images/phone.png"></el-image> -->
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="smsCode" class="smsCode">
          <el-input v-model="loginForm.smsCode" type="smsCode" size="large" auto-complete="off" placeholder="输入验证码" @keyup.enter="handleLogin">
            <template #prefix>
              <img style="width: 16px;height: 16px;" src="@/assets/images/message.png" alt="" />
              <!-- <svg-icon icon-class="message" class="el-input__icon input-icon" /> -->
            </template>
            <template #suffix>
              <div class="codeText" @click="getMsg">{{tips}}</div>
            </template>
          </el-input>
        </el-form-item>
        <div class="noSend" @click="showSend">收不到验证码</div>
      </div>
      <el-form-item class="btn" style="width:100%;">
        <el-button :loading="loading" size="large" type="primary" style="width:100%;" @click.prevent="loginBefore">
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
      <span></span>
    </div>
  </div>
</template>

<script setup lang="ts">
import api from "@/api/login"
import { LoginData } from '@/api/types';
import { useUserStore } from '@/store/modules/user';
import { to } from 'await-to-js';

const router = useRouter();
const userStore = useUserStore();

const { proxy } = getCurrentInstance() as ComponentInternalInstance
const loginForm = ref<LoginData>({
  tenantId: '',
  phonenumber: '',
  smsCode: '',
  uuid: ''
} as LoginData);
const register = ref('')
const tips = ref('获取验证码')
const count = ref(59)
const redirect = ref(undefined);
const loginRef = ref<ElFormInstance>();

const loginRules: ElFormRules = {
  phonenumber: [{ required: true, trigger: 'blur', message: '请输入您的账号' }],
  smsCode: [{ required: true, trigger: 'change', message: '请输入您的验证码' }],
};
const loading = ref(false);

watch(() => router.currentRoute.value, (newRoute: any) => {
  redirect.value = newRoute.query && newRoute.query.redirect;
}, { immediate: true });

const showSend = async() => {
  const [err] = await to(proxy?.$modal.confirm('请再次获取验证码，如仍然无法收到，请描述问题发送至hr01@nullht.com') as any);
  if (!err) {
    console.log('111')
  }
}

//1.先获取租户信息是否允许注册
const loginBefore = () => {
  loginRef.value?.validate(async (valid: boolean, fields: any) => {
    if (valid) {
      // 直接登录
      handleLogin()
    }
  });
}

const handleLogin = async() => {
  loading.value = true;
  const [err] = await to(userStore.loginIn(loginForm.value));
  // const res = await api.loginIn(loginForm.value)
  if(!err){
    localStorage.setItem("tenantId", String(loginForm.value.tenantId));
    await router.push({ path: redirect.value || '/' });
    loading.value = false;
  }else{
    loading.value = false;
  }
};

const getMsg = () => {
  if(!loginForm.value.phonenumber){
    proxy?.$modal.msgError("请输入账号");
    return
  }
  if(count.value != 59){
    return
  }
  getMsgCode(loginForm.value.phonenumber)
  let timer = setInterval(() => {
    if (count.value > 0) {
      count.value--;
      tips.value = count.value+'秒后重新获取'
    } else {
      clearInterval(timer);
      count.value = 59; // 重置倒计时时间
      tips.value = '获取验证码'
    }
  }, 1000);
}

const getTenantInfo = async (tenantId: string | undefined) => {
  const res = await api.getTenantInfo(tenantId)
  register.value = res.data.register
}

const registerUser = async (loginForm: any) => {
  const res = await api.registerUser(loginForm)
  if(res.code == 200){
    handleLogin()
  }
}

const getMsgCode = async (phone: string) => {
  await api.getMsgCode(phone)
}

const initData = () => {
  localStorage.removeItem("tenantId");
  let urls = window.location.href.split('?')
  if(urls.length > 1){
    let strs = urls[urls.length - 1]
    let arr = strs.split('&')
    let arr2 = arr.filter(item => item.indexOf('tenantId') > -1)
    if(arr2.length > 0){
      let tenant = arr2[0].split('=')[1]
      loginForm.value.tenantId = tenant
      getTenantInfo(tenant)
    }else {
      proxy?.$modal.msgError("缺少租户编号");
    }
  }else{
    proxy?.$modal.msgError("缺少租户编号");
  }
}


onMounted(() => {
  initData()
});
</script>

<style lang="scss" scoped>
.loginBg{
  width: 200%;
  height: 200%;
  bottom: 45%;
  left: -50%;
  position: fixed;
  border-radius: 50%;
  background: linear-gradient(133deg, #36C2EF 39.57%, #165DFF 79.9%);
}
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  // background-image: url("../assets/images/login-background.jpg");
  // background-size: cover;
}
.login-form{
  position: absolute;
  z-index: 5;
  width: 315px;
  .title{
    width: 100%;
    text-align: center;
    font-size: 36px;
    height: 44px;
    line-height: 44px;
    margin-bottom: 130px;
    color: #fff;
  }
  .login-con{
    border-radius: 8px;
    background: #FFF;
    box-shadow: 0px 4px 30px 0px rgba(0, 0, 0, 0.08);
    margin-bottom: 60px;
    padding: 9px 0;
    .noSend{
      width: 100%;
      overflow: hidden;
      color: #86909C;
      text-align: center;
      white-space: nowrap;
      font-size: 13px;
      font-style: normal;
      font-weight: 400;
      line-height: 22px;
      cursor: pointer;
    }
    .codeText{
      color: #165DFF;
      text-align: right;
      font-size: 14px;
      font-style: normal;
      font-weight: 400;
      line-height: 22px;
      cursor: pointer;
    }
  }
  .btn{
    :deep(.el-button){
      background-color: #165DFF;
      border-color: #165DFF;
    }
  }
}
:deep(.el-input--large){
  height: 44px;
  line-height: 44px;
}

:deep(.el-input__wrapper){
  border: none;
  box-shadow: none!important;;
}
:deep(.el-form-item__error){
  padding: 0 40px;
}
</style>
