<template>
  <div class="login-box">
    <div class="login-content" :style="{height: loginType ? '492px' : '430px'}">
      <div class="login-header mt-1 ml-1">
        <div class="left">
          <div ref="phone" :class="['left-qrCode', {'phone-switch': isPhone}]" @click="handlePhone">
            <div class="switch-tip">
              {{ isPhone ? $t('login.smsOrPassword') : $t('login.scanWeChatCode') }}
            </div>
          </div>
          <div v-if="loginType" class="loginType">
            <span>{{ $t('login.enterpriseLogin') }}</span>
            <v-tooltip :text="$t('login.switchToPersonalLogin')" location="start">
              <template v-slot:activator="{ props }">
                <v-btn
                  class="ml-0"
                  color="#fffff"
                  size="x-small"
                  icon="mdi-swap-vertical"
                  variant="plain"
                  v-bind="props"
                  to="/login"
                  @click="switchToPersonalLogin"
                >
                </v-btn>
              </template>
            </v-tooltip>
            <!-- <span class="mdi mdi-swap-vertical ml-4"></span> -->
          </div>
        </div>
        <div class="right mr-2 mt-3" v-if="showClose">
          <v-icon color="grey" size="30">mdi-close</v-icon>
        </div>
      </div>
      <div class="login-content-box mt-5">
        <div v-if="!isPhone" class="login-tab">
          <v-tabs v-model="tab" align-tabs="center" color="primary">
            <v-tab :value="1">{{ $t('login.smsLogin') }}</v-tab>
            <v-tab :value="2">{{ $t('login.passwordLogin') }}</v-tab>
          </v-tabs>
          <div v-if="loginType" class="mt-9">
            <!-- 企业选择 -->
            <companySelect ref="companySelectRef" v-model="enterpriseId"></companySelect>
          </div>
          <v-window v-model="tab" :class="{'mt-9': !loginType}">
              <!-- 验证码登录 -->
            <v-window-item :value="1">
              <phoneFrom ref="phoneRef" :phoneDisabled="Boolean(loginType)" @handleEnter="handleLogin"></phoneFrom>
            </v-window-item>
              <!-- 账号密码登录 -->
            <v-window-item :value="2">
              <passwordFrom ref="passRef" :phoneDisabled="Boolean(loginType)" @handleEnter="handleLogin"></passwordFrom>
            </v-window-item>
          </v-window>
        </div>
        <div v-else>
          <!-- 微信扫码登录 -->
          <div v-if="loginType" class="mt-9">
            <companySelect v-model="enterpriseId"></companySelect>
          </div>
          <qr-code></qr-code>
        </div>
        <v-btn v-if="!isPhone" :loading="loginLoading" color="primary" class="white--text mt-5" min-width="350" @click="handleLogin">
          {{ tab === 1 ? $t('login.loginOrRegister') : $t('login.login') }}
        </v-btn>
        <div class="login-tips mt-3">
          {{ $t('login.agreeLogin') }}
          <span class="color" style="cursor: pointer;" @click="handleToUserAgreement">[{{ $t('login.userAgreement') }}]</span>
          <span class="color" style="cursor: pointer;" @click="handlePrivacyPolicy">[{{ $t('login.privacyPolicy') }}]</span>
        </div>
      </div>
    </div>
  </div>
  <!-- <CtDialog :visible="showCompanySelect" title="选择企业" :footer="true" widthType="" @submit="handleSubmit">
    <div  style="min-height: 10px">
      <autocompleteUI></autocompleteUI>
    </div>
  </CtDialog> -->
</template>

<script setup>
import { ref } from 'vue'
import { getUserBindEnterpriseListByPhone } from '@/api/personal/user'
import passwordFrom from './components/passwordPage.vue'
import phoneFrom from '@/components/VerificationCode'
import qrCode from './components/qrCode.vue'
import companySelect from './components/companySelect.vue'

import { useUserStore } from '@/store/user'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from '@/hooks/web/useI18n'
import Snackbar from '@/plugins/snackbar'
defineOptions({ name: 'login-index' })

const { t } = useI18n()
const router = useRouter()
const route = useRoute()
const loginType = ref(route.query?.loginType - 0 || null)
const enterpriseId = ref('')

const phone = ref()
let isPhone = ref(false)
const handlePhone = () => {
  isPhone.value = !isPhone.value
  phone.value.style.backgroundPosition = isPhone.value ? '0 -80px' : '0 0'
}
const tab = ref(1)
const showClose = ref(false)

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

const companySelectRef = ref()
const beforeHandleLogin = async (params) => {
  const data = await getUserBindEnterpriseListByPhone({ phone: params.phone}) // 申请通过才会数据，否则空数组
  if (companySelectRef.value.item?.items) companySelectRef.value.item.items = data
  // localStorage.setItem('companyInfo', JSON.stringify(data))
  const bool = Boolean(data?.length)
  if (!bool) Snackbar.warning(t('login.loginFailed'))
  return bool
}
const handleLogin = async () => {
  localStorage.removeItem('currentRole')
  const { valid } = tab.value ? await phoneRef.value.phoneForm.validate() : await passRef.value.passwordForm.validate()
  if (!valid) return
  loginLoading.value = true
  try {
    const type = loginType.value
    let params, api = {}
    if (tab.value === 1) { params = { ...phoneRef.value.loginData }; api = 'handleSmsLogin'}
    else { params = { ...passRef.value.loginData }; api = 'handlePasswordLogin'}
    // 企业登录
    if (type === 330) {
      const bool = await beforeHandleLogin(params); if (!bool) return
      params.loginType = type; params.enterpriseId = enterpriseId.value
    }
    // await userStore.handlePasswordLogin({ ...passRef.value.loginData, type }) //tab.value === 1
    // await userStore.handleSmsLogin({ ...phoneRef.value.loginData, type })
    await userStore[api](params)
    Snackbar.success(t('login.loginSuccess'))
    const path = type === 330 ? '/recruit/enterprise' : '/recruitHome'
    router.push({ path })
  }
  finally {
    loginLoading.value = false
  }
}

// 隐私、用户协议
const handleToUserAgreement = () => {
  router.push({ path: '/userAgreement' })
}
const handlePrivacyPolicy = () => {
  router.push({ path: '/privacyPolicy' })
}

const switchToPersonalLogin = () => {
  loginType.value = 0
  Snackbar.success(t('common.switchSuccessful'))
}
</script>

<style lang="scss" scoped>
.loginType {
  position: absolute;
  top: 16px;
  right: 0;
  // width: 100%;
  color: #fff;
  padding: 4px 15px 4px 32px;
  border-radius: 8px 0 0 8px;
  // background-color: #ffba5d;
  background-color: #fa9c3e;
  font-size: 16px;
}
.login-box {
  position: relative;
  width: 100%;
  height: 100%;
  background-image: url('https://www.mendunerhr.com/images/userfiles/92d7e4a755e2428b94aab3636d5047f3/images/recruitment/adImages/2018/11/1920x940.jpg');
  background-size: cover;
}
.login-content {
  position: absolute;
  top: 50%;
  left: 50%;
  translate: -50% -50%;
  width: 450px;
  // height: 430px;
  background-color: #fff;
  border-radius: 10px;
}
.login-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 40px;
}
.login-content-box {
  padding: 0 50px;
}
.left {
  display: flex;
}
.left-qrCode {
  position: absolute;
  left: 8px;
  top: 8px;
  width: 40px;
  height: 40px;
  cursor: pointer;
  background: url('../../assets/login.png') 0 0/40px auto no-repeat;
}
.left-qrCode:hover {
  background-position: 0 -40px !important;
}
.left-qrCode.phone-switch {
  background-position: 0 -80px !important;
}
.left-qrCode.phone-switch:hover {
  background-position: 0 -120px !important;
}
.switch-tip {
  position: absolute;
  left: 60px;
  top: 4px;
  padding: 0 14px;
  border-radius: 4px;
  font-size: 12px;
  color: var(--color-666);
  line-height: 32px;
  text-align: center;
  background-color: #fff;
  box-shadow: 0 6px 13px 0 rgba(0,0,0,.1);
  white-space: nowrap;
  &::before {
    content: '';
    position: absolute;
    left: -5px;
    top: 50%;
    transform: translateY(-50%) rotate(45deg);
    width: 10px;
    height: 10px;
    background-color: #fff;
    box-shadow: 0 6px 13px 0 rgba(0,0,0,.1);
  }
}
.login-tips {
  width: 100%;
  font-size: 12px;
  text-align: center;
}

.color {
  color: var(--v-primary-base); 
}
</style>