<template>
  <div class="boot">
    <div class="boot-skip" v-if="state.second > 0">
      <Circle v-model:current-rate="state.currentRate" :rate="state.rate" :speed="100" :stroke-width="60"
        @click="skip(onLoad)">
        <span>{{ state.second }}</span>
      </Circle>
    </div>
    <div class="boot-wrapper">
      <Button v-if="state.showGuide" @click="skip(onLoad)">跳过引导页</Button>
    </div>
  </div>
</template>

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

const { loading, initBaseData } = useLogin()
const route = useRoute()
const router = useRouter()
const countdown = 5  // 倒计时秒数

const state = reactive({
  showGuide: plus.hasPlus() && localStorage.getItem('app_showguide') === '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 = loading.value ? showLoading() : undefined

  promise.then(() => {
    localStorage.setItem('app_showguide', 'false')
    const redirect = route.query.redirect
    if (redirect) {
      router.replace(redirect.toString())
    } else {
      router.replace({ path: '/' })
    }
  }).catch((err) => {
    if (service.isReady) {
      router.replace({ path: '/' })
    } 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()
onUnmounted(() => plus.exitFullSreen())
</script>

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