<template>
  <div
    class="flex flex-col items-center pt-50 bg-[url('~/assets/img/login/login_bg.png')] bg-no-repeat bg-bottom min-h-screen bg-contain"
  >
    <img src="~/assets/img/logo.png" class="w-109 h-57" alt="" srcset="" />
    <span class="text-black-3 mt-40 text-2xl font-semibold">登录到 逍遥游</span>
    <span class="text-black-6 mt-5 text-base">探寻新视野，趣游山水间</span>
    <div class="w-full pt-20 px-15">
      <van-form label-width="50">
        <van-field
          style="--van-cell-value-font-size: 16px"
          v-model="formData.phoneNumber"
          placeholder="请输入手机号"
          type="tel"
          size="large"
          :rules="[{ required: true, message: '请输入手机号' }]"
        >
          <template #label>
            <div @click="countryCodeOption.show = true">
              <span>+{{ countryCode }}</span>
              <span class="iconfont icon-caret-down"></span>
            </div>
          </template>
        </van-field>
        <van-field
          v-model="formData.captchaCode"
          placeholder="请输入图形证码"
          type="tel"
          maxlength="4"
          style="--van-cell-value-font-size: 16px"
          size="large"
          :rules="[{ required: true, message: '请输入图形证码' }]"
        >
          <template #button>
            <div class="h-36 w-110">
              <img
                v-if="captchaImage"
                class="box-border w-full h-full"
                :src="captchaImage"
                fit="contain"
                @click="getCaptchaInfo"
              />
            </div>
          </template>
        </van-field>
        <van-field
          v-model="formData.smsCode"
          placeholder="请输入短信验证码"
          type="tel"
          maxlength="4"
          size="large"
          style="--van-cell-value-font-size: 16px"
          :rules="[{ required: true, message: '请输入短信验证码' }]"
        >
          <template #button>
            <div @click="handleGetSmsCode" class="text-primary text-base py-5">
              {{ smsBtnText }}
            </div>
          </template>
        </van-field>
        <van-button
          :disabled="isLoginBtnDisabled"
          size="large"
          style="background: #fa8446; margin-top: 30px"
          color="#fff"
          round
          class="w-full"
          @click="handleLogin"
          :loading="isSubmiting"
        >
          登录
        </van-button>
      </van-form>
    </div>

    <van-popup v-model:show="countryCodeOption.show" position="bottom">
      <div class="h-[600px] bg-white">
        <van-index-bar>
          <template v-for="item in Object.keys(countryCodeOption.listMap)">
            <van-index-anchor :index="item" />
            <van-cell
              v-for="subItem in countryCodeOption.listMap[item]"
              :key="subItem"
              :title="`${subItem.country}(${subItem.countryCode})`"
              @click="handleChangeCountryCode(subItem)"
            />
          </template>
        </van-index-bar>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { setIntervalImmediately } from '@/utils/index'

definePageMeta({
  layout: false
})

const route = useRoute()

let captchaUUID = ''
const defatultSecond = 60
const countryCode = ref('86')
const captchaImage = ref('')

const formData = reactive({
  phoneNumber: '',
  captchaCode: '',
  smsCode: ''
})

const smsCountDown = ref(defatultSecond)
const isCountDown = computed(() => smsCountDown.value < defatultSecond)

const smsBtnText = computed(() => {
  if (isCountDown.value) {
    return `重新获取(${smsCountDown.value})`
  } else {
    return '获取验证码'
  }
})
const isLoginBtnDisabled = computed(() => {
  return (
    !formData.phoneNumber ||
    formData.captchaCode.trim().length != 4 ||
    formData.smsCode.trim().length != 4
  )
})

async function getCaptchaInfo() {
  const { data } = await request('/website/web/captchaImage')
  captchaUUID = data.uuid
  captchaImage.value = `data:image/jpg;base64,${data.img}`
}

async function handleGetSmsCode() {
  if (isCountDown.value) return
  if (!formData.phoneNumber) {
    showToast('请输入手机号')
    return
  }
  if (!formData.captchaCode) {
    showToast('请输入图形验证码')
    return
  }
  try {
    await request('/website/web/validateCaptchaAndSendSms', {
      query: {
        uuid: captchaUUID,
        countryCode: countryCode.value,
        code: formData.captchaCode,
        phoneNumber: formData.phoneNumber
      }
    })
    startCountDown()
  } catch (error) {}
}

function startCountDown() {
  smsCountDown.value = defatultSecond
  const timer = setIntervalImmediately(() => {
    smsCountDown.value--
    if (smsCountDown.value <= 0) {
      smsCountDown.value = defatultSecond
      clearInterval(timer)
    }
  }, 1000)
}

const isSubmiting = ref(false)
async function handleLogin() {
  try {
    isSubmiting.value
    const { data } = await request('/website/web/doLoginBySms', {
      method: 'post',
      body: {
        ...formData,
        loginMoblie: formData.phoneNumber,
        countryCode: countryCode.value
      }
    })
    useAuthStore().setToken(data.tokenData)
    useUserInfoStore().getUserInfo()
    showSuccessToast('登录成功')

    await navigateTo({
      path: route.query.redirect || '/',
      query: route.query,
      replace: true
    })
  } finally {
    isSubmiting.value = false
  }
}

// 选择国家
const countryCodeOption = reactive({
  show: false,
  listMap: {}
})
async function getAllCountryCode() {
  const { data } = await request('/website/web/list')
  countryCodeOption.listMap = data
}

function handleChangeCountryCode(country) {
  console.log(country)
  countryCodeOption.show = false
  countryCode.value = country.countryCode
}

onMounted(() => {
  getCaptchaInfo()
  getAllCountryCode()
})
</script>

<style lang="scss" scoped></style>
