<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(init())" />
      </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 countdown = 1  // 倒计时秒数

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

const init = () => initBaseData(true) // 初始化数据
const onLoad = state.showGuide ? Promise.resolve() : init()

// 倒计时
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((err) => {
    if (service.isReady) {
      router.replace({ name: 'Home' })
    } else {
      tryInit(err)
    }
  }).finally(() => {
    toast?.close()
  })
}

// 初始化失败重试
const tryInit = (message: string) => {
  dialog({
    message,
    showCancelButton: plus.hasPlus(),
    cancelButtonText: '退出',
    confirmButtonText: '重试'
  }).then(() => {
    skip(init())
  }).catch(() => {
    plus.quit()
  })
}

plus.setFullSreen()
</script>

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