<template>
  <div style="background-color: #f0f0f0;">
    <div class="inviteView text-center" :style="{'width': isMobile ? '100%' : '750px'}">
      <div class="invite-title">
        <div style="color: var(--v-primary-base);" class="mb-3">【门墩儿招聘企业邀请】</div>
        <div style="font-size: 24px">
          <div>
            <span class="color-333">{{ enterpriseInfo.name }}</span>
            <span class="color-333"> 邀请您加入 </span>
          </div>
          <div class="color-333">{{ enterpriseInfo.enterpriseName }}</div>
          <div>招聘团队</div>
        </div>
      </div>
      <div class="mt-10 d-flex flex-column align-center">
        <div v-if="joinSuccess">
          <div style="color: var(--v-primary-base); font-size: 18px; font-weight: bold;">加入成功！</div>
          <!-- <div class="mt-3">您使用企业邮箱登录招聘端的初始密码为"邮箱账号"，请尽快登录招聘端修改密码！</div> -->
          <div class="mt-3">您使用企业邮箱登录招聘端的初始密码</div>
          <div class="mt-2">为 <span style="color: var(--v-error-base);">"{{ joinPersonEmail }}"</span></div>
          <div class="mt-2" style="color: var(--v-error-base);">请尽快登录招聘企业修改密码！</div>
          <!-- <div class="mt-3">您使用企业邮箱登录招聘端的初始密码为"邮箱账号"，请尽快登录招聘端修改密码！</div> -->
          <v-btn v-if="!isMobile" class="mt-10" color="warning" to="/recruitHome">{{ $t('common.toHome') }}</v-btn>
        </div>
        <div v-else>
          <phoneFrom ref="phoneRef" openVerify showEmailInput @handleEnter="handleLogin" class="text-left" :style="{'width': isMobile ? '100%' : '350px' }"></phoneFrom>
          <v-btn :loading="loginLoading" color="warning" class="white--text mt-5" min-width="350" @click="handleLogin" :style="{'width': isMobile ? '100%' : '350px' }">
            {{ $t('common.confirmJoin') }}
          </v-btn>
          <div class="font-size-15 text-end color-666 mt-2">提示：未注册的手机号，加入自动注册账号</div>
          <!-- <div class="color-999 mt-2" style="font-size: 13px;">注：确认即代表加入该企业</div> -->
        </div>
      </div>
    </div>
  </div>
  <!-- 快速填写简易人才信息 -->
  <CtDialog
    :visible="showSimpleInput"
    :widthType="2"
    titleClass="text-h6"
    title="补充基本信息"
    @close="showSimpleInput = false"
    @submit="simpleInfoSubmit"
  >
    <simplePageForm ref="formRef"></simplePageForm>
  </CtDialog>
</template>

<script setup>
defineOptions({ name: 'inviteConfirm'})
import { ref, onMounted } from 'vue'
import phoneFrom from '@/components/VerificationCode'
import simplePageForm from './components/simplePageForm.vue'
import { useRoute } from 'vue-router'; const route = useRoute()
import { enterpriseInviteRecordConsent, getEnterpriseInfoByCode } from '@/api/recruit/enterprise/enterpriseInvite.js'
import Snackbar from '@/plugins/snackbar'
import { getToken } from '@/utils/auth'
import { getBaseInfo, logout } from '@/api/common'
import { useUserStore } from '@/store/user'
import { savePersonSimpleInfo } from '@/api/recruit/personal/shareJob'


const joinSuccess = ref(false)
const code = route.query?.code || ''

// 组件挂载后添加事件监听器  
const isMobile = ref(false)
onMounted(() => {
  const userAgent = navigator.userAgent
  isMobile.value = /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i.test(userAgent)
})
const phoneRef = ref()
const loginLoading = ref(false)

let joinPersonEmail = ''
let copyLoginData = ''
let userId = ''
// 登录
const handleLogin = async () => {
  const { valid } = await phoneRef.value.phoneForm.validate()
  if (!valid) return
  loginLoading.value = true
  try {
    const params = { ...phoneRef.value.loginData, autoRegister: true } // 只能验证码登录
    joinPersonEmail = params.email || ''
    // 如果用户登录后点击关闭填写简易人才信息，再次点击登录仅弹出填写，不再调用登录
    if (copyLoginData === (params.phone + params.code.toString()) && userId) {
      getUserBaseInfos(userId)
      return
    }
    const data = await useUserStore().handleSmsLogin(params)
    copyLoginData = params.phone + params.code.toString()
    userId = data.userId
    getUserBaseInfos(data.userId)
  } catch (error) {
    const msg = error?.msg || error
    Snackbar.error(msg)
    logoutFun()
  } finally {
    loginLoading.value = false
  }
}

// 查询人才信息
const showSimpleInput = ref(false)
const getUserBaseInfos = async (userId) => {
  loginLoading.value = true
  try {
    const data = await getBaseInfo({ userId })
    if (!data) {
      showSimpleInput.value = true; Snackbar.warning('请先完善个人基本信息')
      return 
    }
    const keyArr = ['name', 'phone', 'jobStatus', 'expType', 'eduType'] // 必填人才信息
    const simpleInfoReady = Object.keys(data).length && keyArr.every(e => data[e] && data[e] !== 0) // 校验必填人才信息
    if (!simpleInfoReady) {
      showSimpleInput.value = true; Snackbar.warning('请先完善个人基本信息')
      return
    }
    join()
  } catch (error) {
    logoutFun()
    Snackbar.error('获取用户信息失败！ ' + error)
  } finally {
    loginLoading.value = false
  }
}

// 调用加入接口
const join = async () => {
  loginLoading.value = true
  try {
    const params = { code, email: joinPersonEmail }
    await enterpriseInviteRecordConsent(params)
    joinSuccess.value = true
    Snackbar.success('加入成功')
  } catch (error) {
    // 手机号或者邮箱已加入不能再加入
    Snackbar.error(error)
    // if (phoneRef.value?.resetPhone) phoneRef.value.resetForm()
  } finally {
    if (isMobile.value) logoutFun() // 网页打开保留登录状态
    loginLoading.value = false
  }
}

const logoutFun = async () => {
  if (!getToken(1)) {
    localStorage.clear()
    return
  }
  try {
    await logout()
    localStorage.clear()
  } catch (error) {
    console.log('登出失败！', error)
  }
}
logoutFun() // 清除之前的token

// 提交简易人才信息
const formRef = ref()
const simpleInfoSubmit = async () => {
  try {
    const obj = await formRef.value.getQuery()
    if (!obj) return
    await savePersonSimpleInfo(obj)
    join()
    if (!isMobile.value) await useUserStore().getUserBaseInfos() // 网页打开需更新用户信息
    showSimpleInput.value = false
  } catch (error) {
    console.error('error', error)
  }
}

const enterpriseInfo = ref({})
// 根据邀请码获取企业信息
const getEnterpriseInfo = async () => {
  try {
    const data = await getEnterpriseInfoByCode({ code })
    enterpriseInfo.value = data
  } catch (error) {
    Snackbar.error('链接失效')
  }
}
getEnterpriseInfo()
</script>

<style scoped lang="scss">
.inviteView {
  min-height: 100vh;
  display: block;
  overflow: hidden;
  margin: 0 auto;
  padding: 45px;
  background-color: #fff;
}
.invite-title {
  font-size: 20px;
  font-weight: 700;
  color: var(--color-333);
}
</style>
