<!--  -->
<template>
  <div class="my-5">
    <phoneFrom ref="phoneRef" @handleEnter="handleLogin"></phoneFrom>
    <v-btn  :loading="loginLoading" color="primary" class="white--text mt-5" min-width="350" @click="handleLogin">
      {{ $t('login.register') }}
    </v-btn>
  </div>
</template>

<script setup>
import phoneFrom from '@/components/VerificationCode'
import { useUserStore } from '@/store/user'; const userStore = useUserStore()
import { useI18n } from '@/hooks/web/useI18n'; const { t } = useI18n()
import Snackbar from '@/plugins/snackbar'
import { ref } from 'vue'
defineOptions({name: 'shareJob-login'})
const emit = defineEmits(['loginSuccess'])

// 验证码登录
const phoneRef = ref()
const loginLoading = ref(false)

const timer = ref(null)
const baseInfo = ref(null)
const handleLogin = async () => {
  localStorage.removeItem('currentRole')
  const { valid } = await phoneRef.value.phoneForm.validate()
  if (!valid) return
  loginLoading.value = true
  try {
    const params = { ...phoneRef.value.loginData } // 只能验证码登录
    await userStore.handleSmsLogin(params)
    // 查询用户基本信息
    timer.value = setInterval(() => { getUserInfoVerify() }, 1000)
    // 十秒后停止获取清除timer
    setTimeout(() => { if (!baseInfo.value) getUserInfoFail() }, 10000);
  } catch (error) {
    console.error('error', error)
  }
}

// 查询用户基本信息失败 
const getUserInfoVerify = () => {
  if (baseInfo.value) {
    clearInterval(timer.value)
    timer.value = null
    loginLoading.value = false
    const info = baseInfo.value
    const keyArr = ['name', 'phone', 'jobStatus', 'expType', 'eduType']
    // type = true, 符合快速投递，进入查看是否存在简历 // type = false, 不符合快速投递，进入填写基本信息
    const type = keyArr.every(e => baseInfo.value[e] && baseInfo.value[e] !== 0)
    emit('loginSuccess', { type, info, keyArr })
  }
  baseInfo.value = JSON.parse(localStorage.getItem('baseInfo'))
}

// 查询用户基本信息失败 
const getUserInfoFail = () => {
  clearInterval(timer.value)
  timer.value = null
  loginLoading.value = false
  Snackbar.success(t('login.getUserInfoFailed')+'，'+t('login.loginAgain'))
}
</script>
<style lang="scss" scoped>
</style>
