<template>
  <div class="box">
    <div class="content">
      <div class="login-content">
        <v-card height="392px" class="carousel mr-3" style="width: 792px; border-radius: 8px;">
          <v-carousel show-arrows="hover" cycle>
            <v-carousel-item v-for="(item, i) in carouselList" :key="i">
              <div style="height: 392px; overflow: hidden;">
                <v-img :src="item.src" cover style="height: 100%; overflow: hidden;"></v-img>
              </div>
            </v-carousel-item>
          </v-carousel>
        </v-card>
        <div class="login-card">
          <div class="login-change" @click="handleChangeLogin">{{ isEnterpriseLogin ? '切换个人登录' : '切换企业登录' }}</div>
          <!-- 企业邮箱登录 -->
          <div v-show="isEnterpriseLogin" class="login-tab">
            <v-tabs v-model="tab1" align-tabs="center" color="primary" class="mb-10">
              <v-tab :value="1">企业邮箱登录</v-tab>
            </v-tabs>
            <passwordFrom ref="entPassRef" placeholder="请输入企业邮箱" :validEmail="true" @handleEnter="handleLogin"></passwordFrom>
          </div>
          <!-- 个人登录 -->
          <div v-show="!isEnterpriseLogin" class="login-tab">
            <v-tabs v-model="tab" align-tabs="center" color="primary" class="mb-10" @update:modelValue="tabChange">
              <v-tab :value="1">验证码</v-tab>
              <v-tab :value="2">账号</v-tab>
              <!-- <v-tab :value="3">微信</v-tab> -->
            </v-tabs>
            <v-window v-model="tab">
                <!-- 验证码登录 -->
              <v-window-item :value="1">
                <phoneFrom ref="phoneRef" @handleEnter="handleLogin"></phoneFrom>
              </v-window-item>
                <!-- 账号密码登录 -->
              <v-window-item :value="2">
                <passwordFrom ref="passRef" @handleEnter="handleLogin"></passwordFrom>
              </v-window-item>
              <!-- <v-window-item :value="3">
                <div v-if="showQrCode" class="d-flex align-center flex-column">
                  <span class="text-decoration-underline">微信扫描二维码进行登录</span>
                  <v-img src="https://minio.citupro.com/dev/menduner/login-qrCode.png" width="150" height="150"></v-img>
                </div>
                <div v-else style="height: 150px; line-height: 150px; text-align: center;">
                  加载中 . . .
                </div>
              </v-window-item> -->
            </v-window>
          </div>
          <div class="font-size-14 tips">
            <span class="float-left color-666 cursor-pointer" v-if="tab === 2" @click="router.push(isEnterpriseLogin ? '/forgotPasswordEnt': '/forgotPassword')">忘记密码</span>
            <span class="float-right color-error cursor-pointer text-decoration-underline" @click="router.push('/register/selected')">还没有登录账户？去注册</span>
          </div>
          <v-btn :loading="loginLoading" color="primary" class="white--text mt-5" min-width="350" @click="handleLogin">
            {{ $t('login.login') }}
          </v-btn>
          <div class="login-tips mt-3">
              {{ $t('login.agreeLogin') }}
              <span class="color" style="cursor: pointer;" @click="router.push('/userAgreement')"> [{{ $t('login.userAgreement') }}] </span>和
              <span class="color" style="cursor: pointer;" @click="router.push('/privacyPolicy')">[{{ $t('login.privacyPolicy') }}]</span>
          </div>
        </div>
      </div>
      <div class="aboutBox">
        <about></about>
      </div>
    </div>
    <navBar v-if="!isMobile" :showLoginBtn="false" class="navBar"></navBar>
  </div>
  <Verify
    ref="verify"
    captchaType="blockPuzzle"
    :imgSize="{ width: '400px', height: '200px' }"
    mode="pop"
    @success="verifySuccess"
  />
</template>

<script setup>
defineOptions({ name: 'login-index' })
import { nextTick, ref, onMounted } from 'vue'
import passwordFrom from './components/passwordPage.vue'
import phoneFrom from '@/components/VerificationCode'
import { useUserStore } from '@/store/user'
import { useRouter } from 'vue-router'
import { useI18n } from '@/hooks/web/useI18n'
import {
  getEnterpriseRegisterApply,
  // socialAuthRedirect,
} from '@/api/common'
import Snackbar from '@/plugins/snackbar'
import Confirm from '@/plugins/confirm'
import navBar from '@/layout/personal/navBar.vue'
import about from '@/views/about/index.vue'
import { useRoute } from 'vue-router'; const route = useRoute()
import Verify from '@/components/Verifition'

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 { t } = useI18n()
const router = useRouter()
const tab = ref(1)
const tab1 = ref(1)
const isEnterpriseLogin = ref(route.query?.entLogin || false)

const handleChangeLogin = () => {
  isEnterpriseLogin.value = !isEnterpriseLogin.value
  nextTick(() => {
    tab.value = isEnterpriseLogin.value ? 2 : 1 // 为了验证邮箱validate
  })
}

// 验证码登录
const phoneRef = ref()
const passRef = ref()
const entPassRef = ref()
const loginLoading = ref(false)
const userStore = useUserStore()

const handleCheckEnterprise = async () => {
  const data = await getEnterpriseRegisterApply(passRef.value.loginData.phone)
  if (data && Object.keys(data).length) {
    // 查看申请状态
    localStorage.setItem('entRegisterData', JSON.stringify(data))
    localStorage.setItem('loginAccount', data.phone)
    router.push({ path: '/recruit/entRegister/inReview', query: { type: 'noLoginToRegister', noLogin: true } })
  }
}

const handleLogin = async () => {
  const { valid } = isEnterpriseLogin.value ? await entPassRef.value.passwordForm.validate() : tab.value === 1 ? await phoneRef.value.phoneForm.validate() : await passRef.value.passwordForm.validate()
  if (!valid) return
  if (!captchaVerification) {
    getCode() // 验证码组件
    return
  }
  
  loginLoading.value = true
  try {
    let params, api = {}
    // if (tab.value === 1) { params = { ...phoneRef.value.loginData }; api = 'handleSmsLogin'}
    // else { params = { ...passRef.value.loginData, captchaVerification }; api = 'handlePasswordLogin'}
    if (isEnterpriseLogin.value) { params = { ...entPassRef.value.loginData, captchaVerification }; api = 'handlePasswordLogin'}
    else { params = tab.value === 1 ? { ...phoneRef.value.loginData, captchaVerification } : { ...passRef.value.loginData, captchaVerification }; api = tab.value === 1 ? 'handleSmsLogin' : 'handlePasswordLogin'}
    
    // 邮箱为企业招聘， 手机号为个人求职
    if (isEnterpriseLogin.value) {
      const pattern = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
      const isEnterprise = pattern.test(params.phone)
      if (!isEnterprise) return // 选中企业登录但输入内容非邮箱
      params.isEnterprise = isEnterprise
    }
    await userStore[api](params)
    // 跳转
    if (params.isEnterprise) return // 企业邮箱登录
    else localStorage.setItem('simpleCompleteDialogHaveBeenShow', true) // 个人登录简易基本信息填写弹窗open-status
    Snackbar.success(t('login.loginSuccess'))
    router.push({ path: '/recruitHome' })

  } catch (err) {
    console.log(err)
    if (!err.code) return
    // 企业注册申请中
    if (err.code === 1100017022) {
      // 密码不安全
      router.push('/forgotPassword?forgot=1')
      return
    }
    if (err.code === 1100021016) {
      handleCheckEnterprise()
      return
    }
    // 登录未注册过的账号跳转注册
    const text = err.code === 1100016002 ? '您的手机号还未注册过' : '您的邮箱还未注册过'
    Confirm('系统提示',  `${text},去注册？`, {
      cancelCallback: true
    }).then(() => {
      localStorage.setItem('loginAccount', isEnterpriseLogin.value ? entPassRef.value.loginData.phone : tab.value === 1 ? phoneRef.value.loginData.phone : passRef.value.loginData.phone)
      router.push(err.code === 1100016002 ? '/register/person?type=noLoginToRegister' : '/register/company?type=noLoginToRegister')
    })
  } finally {
    loginLoading.value = false
  }
}


// const getSocialAuthRedirect = async () => {
//   const params = {
//     type: '34',
//     redirectUri: 'https://www.baidu.com'
//   }
//   const res = await socialAuthRedirect(params)
//   const otherUrl = res?.url
//   if (otherUrl) window.open(otherUrl)
// }

// const showQrCode = ref(false)
const tabChange = (val) => {
  if (val === 3) {
    // getSocialAuthRedirect()
  }
}

// 轮播广告 // 轮播图片
const carouselList = ref([
  { src: 'https://minio.citupro.com/dev/menduner/preferredGroup/IHG-banner-new.gif' },
  { src: 'https://minio.citupro.com/dev/menduner/preferredGroup/SWISS-HOTEL-MANAGEMENT-SCHOOL-MBA.jpg'},
  { src: 'https://minio.citupro.com/dev/menduner/preferredGroup/Hong-Kong-Polytechnic-University-banner.jpg' }
])

// 验证码
const verify = ref()
// 获取验证码
const getCode = async () => {
  // 弹出验证码 // 已开启：则展示验证码；只有完成验证码的情况，才进行登录
  verify.value.show()
}

let captchaVerification = ''
const verifySuccess = (params) => {
  captchaVerification = params.captchaVerification
  handleLogin()
}

</script>

<style lang="scss" scoped>
.box {
  position: relative;
  width: 100%;
  height: 100vh;
  background-image: url('https://minio.menduner.com/dev/menduner/login-banner.png');
  background-size: cover;
  overflow: hidden;
  .navBar {
    position: absolute;
    top: 0;
  }
}
.content {
  width: 100%;
  height: 100%;
  overflow-y: auto;
}
.login-content {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  // height: 84vh;
  height: calc(100vh - 50px);
  margin-top: 50px;
}
.login-change {
  position: absolute;
  top: 0;
  right: 0;
  padding: 15px 44px;
  text-decoration: underline;
  color: orange; 
  cursor: pointer;
  font-weight: 400;
  &:hover {
    text-decoration: underline;
    color: #fbb93e; 
  }
}
.login-card {
  position: relative;
  width: 450px;
  background-color: #fff;
  border-radius: 8px;
  padding: 36px 50px;
  // margin-right: 12px;
}
.left {
  display: flex;
}
.login-tips {
  width: 100%;
  font-size: 12px;
  text-align: center;
}
.tips {
  span:hover {
    text-decoration: underline;
  }
}
.color {
  color: var(--v-primary-base); 
}

.aboutBox {
  width: 100%;
  background-color: #fff;
  // overflow-x: auto;
}
.carousel {
  :deep(.v-window) {
    height: 392px !important;
  }
}
</style>