<template>
  <div class="boot">
    <Swipe class="boot__guide" :loop="false" v-if="state.showGuide">
      <SwipeItem>
        <img src="@mobile/assets/images/boot-1080p.png" />
      </SwipeItem>
      <SwipeItem>
        <img src="@mobile/assets/images/guide-1.png" />
      </SwipeItem>
      <SwipeItem>
        <img src="@mobile/assets/images/guide-2.png" @click="skip(onLoad)" />
      </SwipeItem>
    </Swipe>
  </div>
</template>

<script lang="ts" setup>
import { reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Swipe, SwipeItem } from 'vant'
import { showLoading, dialog } from '@/utils/vant'
import { useLogin } from '@/business/login'
import service from '@/services'
import plus from '@/utils/h5plus'

const { logining, initBaseData } = useLogin()
const route = useRoute()
const router = useRouter()
const onLoad = initBaseData(true) // 初始化数据
const countdown = 1  // 倒计时秒数

const state = reactive({
  showGuide: localStorage.getItem('thj_app_showguide') === 'false' ? false : true, // 是否显示引导页
  second: countdown, // 剩余秒数
  currentRate: 100, // 当前进度
  rate: 100, // 目标进度
})

// 倒计时
const timer = window.setInterval(() => {
  state.second--
  state.rate = (100 / countdown) * state.second
  if (state.second <= 0) {
    clearInterval(timer)
    // 判断是否首次打开应用
    if (!state.showGuide) {
      skip(onLoad)
    }
  }
}, 1000)

// 跳过广告
const skip = (promise: Promise<void>) => {
  clearInterval(timer)
  const toast = logining.value ? showLoading() : undefined

  promise.then(() => {
    plus.exitFullSreen()
    localStorage.setItem('thj_app_showguide', 'false')
    const redirect = route.query.redirect
    if (redirect) {
      router.replace(redirect.toString())
    } else {
      router.replace({ name: 'Home' })
    }
  }).catch(() => {
    if (service.isReady) {
      router.replace({ name: 'Home' })
    } else {
      tryInit()
    }
  }).finally(() => {
    toast?.close()
  })
}

// 初始化失败重试
const tryInit = () => {
  dialog({
    message: '加载失败，请稍后再试',
    showCancelButton: plus.hasPlus(),
    cancelButtonText: '退出',
    confirmButtonText: '重试'
  }).then(() => {
    skip(initBaseData(true))
  }).catch(() => {
    plus.quit()
  })
}

plus.setFullSreen()
</script>

<style lang="less" scoped>
@import './index.less';
</style>