<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">
        <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>
            <div style="font-size: 13px;text-align: left;" class="mb-2"><span style="color: red;">*</span> 请输入要加入的企业邮箱及密码</div>
            <passwordFrom
              ref="entPassRef"
              placeholder="请输入企业邮箱"
              :isCounter="true"
              :validEmail="true"
              style="text-align: left;"
              @handleEnter="handleLogin"
            ></passwordFrom>
            <v-btn :loading="loginLoading" color="warning" class="white--text mt-3" min-width="350" @click="handleLogin" :style="{'width': isMobile ? '100%' : '350px' }">
              {{ $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>
  <Verify
    ref="verify"
    captchaType="blockPuzzle"
    :imgSize="{ width: '400px', height: '200px' }"
    mode="pop"
    @success="verifySuccess"
  />
</template>

<script setup>
defineOptions({ name: 'inviteConfirmEnt'})
import { useRouter } from 'vue-router'; const router = useRouter()
import { ref, onMounted } 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 passwordFrom from '@/views/login/components/passwordPage.vue'
import Verify from '@/components/Verifition'
import { getToken } from '@/utils/auth'
import { useUserStore } from '@/store/user'
import {
  logoutToken,
  passwordLogin
} 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 entPassRef = ref()
// 获取验证码
const verify = ref()
const getCode = async () => {
  // 弹出验证码 // 已开启：则展示验证码；只有完成验证码的情况，才进行登录
  verify.value.show()
}
const captchaStr = ref('')
const verifySuccess = (params) => {
  captchaStr.value = params.captchaVerification
  handleLogin()
}

// const entBaseInfo = ref()
// // 获取当前登录的企业用户信息
// const getLoginEnterpriseInfo = async () => {
//   try {
//     const result = await getEnterprisingUserInfo()
//     entBaseInfo.value = result
    
//     // 是否为企业账号管理员
//     // const isAdmin = result.userType === '1'
//   } catch (error) {
//     console.error('error', error)
//   }
// }

const loginLoading = ref(false)
const handleLogin = async () => {
  const { valid } = await entPassRef.value.passwordForm.validate()
  if (!valid) return
  const params = {
    ...entPassRef.value.loginData,
    captchaVerification: captchaStr.value,
    isEnterprise: true,
  }
  params.account = params.phone

  if (!params.captchaVerification) {
    getCode() // 验证码组件
    return
  }
  loginLoading.value = true
  try {
    const res = await passwordLogin(params)
    const obj = res ? { ...res, type: 'emailLogin', onlySetToken: true } : {}
    await useUserStore().changeRole(obj)
    await join()

  } catch (error) {
    Snackbar.error(error?.msg || error)
  } finally {
    captchaStr.value = ''
    loginLoading.value = false
  }
}

// 执行加入操作
const join = async () => {
  try {
    loginLoading.value = true
    await enterpriseInviteRecordConsent({ code })
    Snackbar.success('加入成功')
    joinSuccess.value = true
  } catch (error) {
    Snackbar.error(error?.msg || error)
  } finally {
    captchaStr.value = ''
    loginLoading.value = false
    logoutFun()
  }
}

const quickRegister = ref(false)
const handleRegister = () => {
  router.push('/register/selected')
}

const logoutFun = async () => {
  if (!getToken(1)) {
    localStorage.clear()
    return
  }
  try {
    await await logoutToken(getToken(1))
    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>
