<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">
          <span class="color-333">{{ enterpriseInfo.name }}</span>
          <span class="color-333"> 邀请您加入 </span>
          <span class="color-333">{{ enterpriseInfo.enterpriseName }}</span>
          <span>的招聘团</span>
        </div>
      </div>
      <div class="mt-10 d-flex flex-column align-center">
        <template v-if="joinSuccess">
          <div>加入成功！</div>
          <v-btn class="mt-10" color="warning" to="/recruitHome">{{ $t('common.toHome') }}</v-btn>
        </template>
        <template v-else>
          <phoneFrom ref="phoneRef" @handleEnter="handleLogin" :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="color-999 mt-2" style="font-size: 13px;">注：确认即代表加入该企业</div> -->
        </template>
      </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, setToken, setRefreshToken } from '@/utils/auth'
import {
  smsLogin,
  getBaseInfo,
  logout
} from '@/api/common'
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)

// 登录
const handleLogin = async () => {
  const { valid } = await phoneRef.value.phoneForm.validate()
  if (!valid) return
  loginLoading.value = true
  try {
    const params = { ...phoneRef.value.loginData } // 只能验证码登录
    const res = await smsLogin(params)
    setToken(res.accessToken)
    setRefreshToken(res.refreshToken)
    localStorage.setItem('loginType', 'personal') // 不存在时刷新会出现重定向
    getUserBaseInfos(res.userId)
  } catch (error) {
    Snackbar.error('加入失败！ ' + error)
  } finally {
    loginLoading.value = false
  }
}

// 查询人才信息
const showSimpleInput = ref(false)
const getUserBaseInfos = async (userId) => {
  loginLoading.value = true
  try {
    const data = await getBaseInfo({ userId })
    console.log('data', data)
    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 {
    await enterpriseInviteRecordConsent(code)
    joinSuccess.value = true
    Snackbar.success('加入成功')
  } catch (error) {
    Snackbar.error('加入失败！ ' + error)
  } finally {
    logoutFun()
    loginLoading.value = false
  }
}

const logoutFun = async () => {
  if (!getToken()) {
    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()
    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>
