<template>
  <div class="box" :style="{'background-image': 'url(' + logoBgUrl + ')'}">
    <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 :model-value="0">
            <v-carousel-item v-for="(item, i) in carouselList" :key="i" @click="handleClick(item)">
              <div style="height: 392px; overflow: hidden;" :class="{'cursor-pointer': item.link}">
                <v-img :src="item.img" :lazy-src="item.src" cover style="height: 100%; overflow: hidden;">
                  <template v-slot:placeholder>
                    <v-row align="center" class="fill-height ma-0" justify="center">
                      <v-progress-circular color="grey-lighten-5" indeterminate></v-progress-circular>
                    </v-row>
                  </template>
                </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="请输入企业邮箱" :isCounter="true" :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-${tab === 3 ? 6 : 9}`" @update:modelValue="tabChange">
              <v-tab :value="2">账号</v-tab>
              <v-tab :value="1">验证码</v-tab>
              <v-tab :value="3">微信扫码</v-tab>
            </v-tabs>
            <v-window v-model="tab">
                <!-- 验证码登录 -->
              <v-window-item :value="1">
                <phoneFrom ref="phoneRef" openVerify @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 position-relative">
                  <v-img :src="qrCodeUrl" width="200" height="200"></v-img>
                  <span class="color-666 font-size-13 mt-3">请使用微信扫描二维码登录“门墩儿”</span>
                  <span v-if="remainderZhShow" class="color-warning font-size-13 mt-1">请在{{ remainderZhShow }}内扫码授权登录</span>

                  <div v-if="qrCodeDisabled" class="disabledBox">
                    <div class="disabledContent">
                      <div class="color-666">请重新刷新二维码</div>
                      <v-btn color="primary" class="mt-5" elevation="0" @click="disabledClick">点击刷新</v-btn>
                    </div>
                  </div>
                </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">
            <span v-if="tab === 2" class="float-left tips color-666 cursor-pointer" @click="router.push(isEnterpriseLogin ? '/forgotPasswordEnt': '/forgotPassword')">忘记密码</span>
            <span v-if="tab !== 3" class="float-right color-error cursor-pointer border-bottom-error" @click="router.push('/register/selected')">还没有登录账户？去注册</span>
          </div>
          <v-btn v-if="tab !== 3" :loading="loginLoading" color="primary" class="white--text mt-5" min-width="350" @click.stop="handleLogin">
            {{ $t('login.login') }}
          </v-btn>
          <div class="login-tips mt-3" v-if="tab !== 3">
              <v-icon v-if="isAgree" size="25" color="primary" class="mr-1" @click="isAgree = !isAgree">mdi-check-circle</v-icon>
              <v-icon v-else size="25" color="grey" class="mr-1" @click="isAgree = !isAgree">mdi-circle-outline</v-icon>
              {{ $t('login.agreeLogin') }}
              <span class="color" style="cursor: pointer;" @click="windowOpen('/userAgreement')"> [{{ $t('login.userAgreement') }}] </span>和
              <span class="color" style="cursor: pointer;" @click="windowOpen('/privacyPolicy')">[{{ $t('login.privacyPolicy') }}]</span>
          </div>
        </div>
      </div>
      <div class="aboutBox">
        <about :showBanner="false"></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,
  getWebContent
  // 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'
import { useMallStore } from '@/store/mall'
import { generateUUID } from '@/utils/index'
import { getWeXinLoginQrCode, checkWeXinLoginAuthorize } from '@/api/common/qrcodeLogin'

const isMobile = ref(false)
onMounted(async () => {
  await useMallStore().getMallDiyTemplate()
  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 logoBgUrl = ref('')
const preferred = ref({})
const carouselList = ref([])

const getSystemWebContent = async () => {
  const data = await getWebContent()
  logoBgUrl.value = data.pcLoginBackground && data.pcLoginBackground.length ? data.pcLoginBackground[0].img : 'https://minio.menduner.com/dev/menduner/login-bgc.jpg'
  carouselList.value = data.pcLoginCarousel || []
  preferred.value = data.appPreferredGroup || {}
}
getSystemWebContent()

const handleClick = (item) => {
  if (!item.link) return
  if (item.link.includes('http')) return window.open(item.link)

  // 优选集团
  if (preferred.value && Object.keys(preferred.value).length > 0 && preferred.value[item.link]) window.open(`/recruit/personal/advertisement/${item.link}`)
  else window.open(`/recruit/personal/company/details/${item.link}?key=briefIntroduction`)
}

const { t } = useI18n()
const router = useRouter()
const tab = ref(2) // 密码登录
const tab1 = ref(1)
const isAgree = ref(false)
const isEnterpriseLogin = ref(route.query?.entLogin || false)

const handleChangeLogin = () => {
  isEnterpriseLogin.value = !isEnterpriseLogin.value
  nextTick(() => {
    // tab.value = isEnterpriseLogin.value ? 2 : 1 // 为了验证邮箱validate，企业邮箱登录时需要tab
    tab.value = 2 // 为了验证邮箱validate，企业邮箱登录时需要tab=2
  })
}

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

const handleCheckEnterprise = async () => {
  const data = await getEnterpriseRegisterApply(entPassRef.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 (!isAgree.value) return Snackbar.warning('请阅读并勾选底部协议')
  
  loginLoading.value = true
  try {
    let params, api = {}
    if (isEnterpriseLogin.value) { params = { ...entPassRef.value.loginData }; api = 'handlePasswordLogin'}
    else { params = tab.value === 1 ? { ...phoneRef.value.loginData } : { ...passRef.value.loginData }; api = tab.value === 1 ? 'handleSmsLogin' : 'handlePasswordLogin'}
    if (!params.captchaVerification && captchaStr.value) params.captchaVerification = captchaStr.value
    if (!params.captchaVerification) {
      getCode() // 验证码组件
      return
    }

    // 邮箱为企业招聘， 手机号为个人求职
    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)
    captchaStr.value = '' // 清空人机验证
    if (tab.value === 1) phoneRef.value.clearCaptcha() // 清空人机验证
    if (!err.code || (err?.message && err.message.includes('timeout'))) 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')
    }).catch(() => {})
  } finally {
    loginLoading.value = false
  }
}

// 微信扫码-小程序授权登录
const qrCodeUrl = ref(null)
const showQrCode = ref(true)
const qrCodeDisabled = ref(true )
const query = ref({
  clientId: null
})

const remainder = ref(0)
const remainderZhShow = ref('')
const remainderTimer = ref(null)
const abortController = ref(null)
const formatDuration = (time) => {
  var seconds = Math.floor(time / 1000)
  var minutes = Math.floor(seconds / 60)
  var remainingSeconds = seconds % 60
  minutes = minutes.toString().padStart(2, '0')
  remainingSeconds = remainingSeconds.toString().padStart(2, '0')
  return `${minutes}分${remainingSeconds}秒`
}
const remainderCalc = () => {
  remainder.value -= 1000
  remainderZhShow.value = formatDuration(remainder.value)
  if (remainder.value <= 0) {
    qrCodeDisabled.value = true
    // 取消所有正在进行的请求
    if (abortController.value) {
      abortController.value.abort() 
      abortController.value = null
    }
    handleAuthorize(true)
  }
}
// 初始化倒计时
const countdownTime = 60000 * 5 // 倒计时五分钟
const initIntervalFun = () => {
  remainder.value = countdownTime // 初始倒计时时间
  if (remainderTimer.value) clearInterval(remainderTimer.value); remainderTimer.value = null // 每一次点击都清除上一个轮询
  // 倒计时计算
  remainderCalc()
  remainderTimer.value = setInterval(() => { remainderCalc() }, 1000)
}

// 轮巡查询是否授权成功
const handleAuthorize = async (stop) => {
  // 二维码失效停止请求
  if (stop) return
  try {
    abortController.value = new AbortController()
    const signal = abortController.value.signal
    const data = await checkWeXinLoginAuthorize(query.value, signal)
    if (!data) return
    query.value.clientId = data.clientId

    // 等待扫码授权中
    if (data.status === '0' || !data.appMdeAuthLoginRespVO || !Object.keys(data.appMdeAuthLoginRespVO).length) {
      handleAuthorize()
      return
    }
    
    // 授权成功，返回登录信息
    await userStore.handleWeXinQrCodeLogin(data.appMdeAuthLoginRespVO)
    router.push('/')
  } catch (error) {
    console.log(error, 'error')
  }
}

// 小程序二维码获取
const getSocialAuthRedirect = async () => {
  showQrCode.value = false
  try {
    const data = await getWeXinLoginQrCode(query.value)
    qrCodeUrl.value = URL.createObjectURL(data)
    qrCodeDisabled.value = false
    showQrCode.value = true
    initIntervalFun()
    handleAuthorize()
  } catch {
    showQrCode.value = false
  }
}

// 二维码过期重新生成
const disabledClick = () => {
  qrCodeDisabled.value = false
  query.value.clientId = generateUUID()
  getSocialAuthRedirect()
}

const tabChange = (val) => {
  if (val === 3) {
    if (abortController.value) {
      abortController.value.abort()
      abortController.value = null
    }
    query.value.clientId = generateUUID()
    getSocialAuthRedirect()
  }
}

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

const captchaStr = ref('')
const verifySuccess = (params) => {
  captchaStr.value = params.captchaVerification
  handleLogin()
}

const windowOpen = (url) => {
  if (url) window.open(url)
}
</script>

<style lang="scss" scoped>
.disabledBox {
  position: absolute;
  top: 0;
  left: 0;
  background: rgb(255 255 255 / 90%);
  height: 100%;
  width: 100%;
}
.disabledContent {
  height: 90%;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.box {
  position: relative;
  width: 100%;
  height: 100vh;
  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: 78vh;
  // height: calc(100vh - 50px);
  margin-top: 50px;
}
.login-change {
  position: absolute;
  top: 0;
  right: 0;
  margin: 15px 44px;
  border-bottom: 1px solid orange;
  color: orange; 
  cursor: pointer;
  font-weight: 400;
  &:hover {
    color: #fbb93e; 
  }
}
.login-card {
  position: relative;
  width: 450px;
  background-color: #fff;
  border-radius: 8px;
  padding: 36px 50px;
  height: 392px;
}
.left {
  display: flex;
}
.login-tips {
  width: 100%;
  font-size: 12px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.tips:hover {
  border-bottom: 1px solid #666;
}
.color {
  color: var(--v-primary-base); 
}

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