<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-tab">
            <v-tabs v-model="tab" align-tabs="center" color="primary" class="mb-10">
              <v-tab :value="0">老师手机验证码登录</v-tab>
            </v-tabs>
            <phoneFrom ref="phoneRef" openVerify @handleEnter="handleLogin"></phoneFrom>
          </div>
          <div class="font-size-14">
            <span class="float-right color-error cursor-pointer border-bottom-error" @click="router.push('/register/school')">还没有登录账户？去注册</span>
          </div>
          <v-btn :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-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 :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 { ref } from 'vue'
import phoneFrom from '@/components/VerificationCode'
import { useUserStore } from '@/store/user'
import { useRouter } from 'vue-router'
import { useI18n } from '@/hooks/web/useI18n'
import { getWebContent } 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 Verify from '@/components/Verifition'

// 获取轮播图、背景图
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(0)
const isAgree = ref(false)


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


const handleLogin = async () => {
  const { valid } = await phoneRef.value.phoneForm.validate()
  if (!valid) return
  if (!isAgree.value) return Snackbar.warning('请阅读并勾选底部协议')

  const params = {
    ...phoneRef.value.loginData,
    chooseRole: false,
    schoolRegister: true
  }
  
  loginLoading.value = true
  try {
    if (!params.captchaVerification && captchaStr.value) params.captchaVerification = captchaStr.value
    if (!params.captchaVerification) {
      getCode() // 验证码组件
      return
    }

    await userStore.handleSmsLogin(params)
    // Snackbar.success(t('login.loginSuccess'))
  } catch (err) {
    console.log(err)
    captchaStr.value = '' // 清空人机验证

    if (!err.code || (err?.message && err.message.includes('timeout'))) return

    // 登录未注册过的账号跳转注册
    const text = err.code === 1100016002 ? '您的手机号还未注册过' : '您的邮箱还未注册过'
    Confirm('系统提示',  `${text},去注册？`, {
      cancelCallback: true
    }).then(() => {
      localStorage.setItem('flameLoginAccount', phoneRef.value.loginData.phone)
      router.push('/register/school')
    }).catch(() => {})
  } finally {
    loginLoading.value = false
  }
}


// 获取验证码
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>
.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;
}
.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>