<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>
          <div v-if="showCompanySelect">
            <companySelect ref="companySelectRef" :list="enterpriseList" v-model="enterpriseId"></companySelect>
            <v-btn :loading="loginLoading" color="warning" class="white--text mt-3" min-width="350" @click="join(enterpriseId)" :style="{'width': isMobile ? '100%' : '350px' }">
              {{ $t('common.confirm') }}
            </v-btn>
          </div>
          <div v-show="!showCompanySelect">
            <phoneFrom ref="phoneRef" @handleEnter="handleClick()" :style="{'width': isMobile ? '100%' : '350px' }"></phoneFrom>
            <v-btn :loading="loginLoading" color="warning" class="white--text mt-3" min-width="350" @click="handleConfirmJoin" :style="{'width': isMobile ? '100%' : '350px' }">
              {{ quickRegister ? $t('login.register') : $t('common.confirmJoin') }}
            </v-btn>
            <div class="mt-3" style="font-size: 13px;text-align: center;">
              <div>注：请使用已经申请好的企业账户加入集团</div>
              <div style="color: red; cursor: pointer;">
                <span
                  v-if="quickRegister"
                  @click="quickRegister = false"
                >
                  已有企业账号，去登录
                </span>
                <span
                  v-else
                  @click="handleRegister"
                >
                  没有企业账号？去注册
                </span>
              </div>
            </div>
          </div>
        </template>
      </div>
    </div>
  </div>
</template>

<script setup>
defineOptions({ name: 'inviteConfirmEnt'})
import { useRouter } from 'vue-router'; const router = useRouter()
import { ref, onMounted, reactive } from 'vue'
import { useRoute } from 'vue-router'; const route = useRoute()
import { enterpriseInviteRecordConsent, getEnterpriseInfoByCode } from '@/api/recruit/enterprise/enterpriseInvite.js'
import Snackbar from '@/plugins/snackbar'
import { getUserBindEnterpriseList, getUserRegisterEnterpriseApply } from '@/api/personal/user'
import companySelect from '@/views/login/components/companySelect.vue'
import phoneFrom from '@/components/VerificationCode'
import { getToken, setToken, setRefreshToken } from '@/utils/auth'
import { smsLogin, logout, switchLoginOfEnterprise, logoutToken } from '@/api/common'

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 showCompanySelect = ref(false)
let phoneParams = reactive({})
const enterpriseId = ref('')

const handleConfirmJoin = async () => {
  phoneParams = { ...phoneRef.value.loginData }
  const { valid } = await phoneRef.value.phoneForm.validate()
  if (!valid) return
  loginLoading.value = true
  try {
    const res = await smsLogin(phoneParams)
    setToken(res.accessToken)
    setRefreshToken(res.refreshToken)
    localStorage.setItem('loginType', 'personal') // 不存在时刷新会出现重定向
    quickRegister.value ? getApplyInfo() : getEnterpriseList()
    // if (quickRegister.value) getApplyInfo()
    // else getEnterpriseList()
  } catch (error) {
    Snackbar.error('查询用户数据失败')
  } finally {
    loginLoading.value = false
  }
}

const companySelectRef = ref()
const enterpriseList = ref([])
const getEnterpriseList = async() => {
  try {
    loginLoading.value = true
    enterpriseList.value = []
    const data = await getUserBindEnterpriseList() // 申请通过才有数据，否则空数组
    if (!data?.length) {
      // Snackbar.warning('未查询到该用户下存在企业')
      getApplyInfo()
      return
    }
    if (data.length > 1) {
      showCompanySelect.value = true
      enterpriseList.value = data
    } else {
      join(data[0].enterpriseId)
    }
  } catch (error) {
    Snackbar.error('查询用户企业失败')
    logoutFun()
  } finally {
    loginLoading.value = false
  }
}

// 查看用户是否有在申请中的数据
const getApplyInfo = async () => {
  const data = await getUserRegisterEnterpriseApply()
  const bool = data && Object.keys(data).length // 已经有数据说明已经申请过了
  const path = bool ? '/recruit/enterprise/register/inReview' : '/recruit/enterprise/register'
  router.push({ path })
  if (!bool) Snackbar.warning('未查询到该用户下存在企业，请优先提交企业申请')
}

// 执行加入操作
const join = async (enterpriseId) => {
  if (!enterpriseId) return Snackbar.warning('请选择要加入的企业')
  if (enterpriseInfo.value?.id === enterpriseId) return Snackbar.error('您在尝试加入自己的企业邀请，此操作不被允许！')
  try {
    loginLoading.value = true
    await logout() // changeRole // 先退出个人登录
    const data = await switchLoginOfEnterprise({ enterpriseId })
    setToken(data.accessToken)
    localStorage.setItem('currentRole', 'enterprise')
    await enterpriseInviteRecordConsent(code)
    Snackbar.success('加入成功')
    joinSuccess.value = true
  } catch (error) {
    Snackbar.error('加入失败! ' + error)
  } finally {
    loginLoading.value = false
    logoutFun()
  }
}

const quickRegister = ref(false)
const handleRegister = () => {
  quickRegister.value = true
}

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

const enterpriseInfo = ref({})
// 根据邀请码获取企业信息
const getEnterpriseInfo = async () => {
  try {
    const data = await getEnterpriseInfoByCode({ code })
    enterpriseInfo.value = data
  } catch (error) {
    console.error('error', 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>
