<template>
  <div class="boot">
    <Swipe class="boot__guide" :loop="false" v-if="guidePage">
      <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" />
      </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 } from '@/utils/vant'
import { initBaseData } from '@/business/common'
import { useAuth } from '@/business/auth'
import service from '@/services'
import socket from '@/services/socket'
import plus from '@/utils/h5plus'

const route = useRoute()
const router = useRouter()
const { login } = useAuth(true)
const guidePage = localStorage.getItem('thj_app_guide') === 'false' ? false : true // 是否显示引导页
const countdown = 1  // 倒计时秒数

const state = reactive({
  second: countdown, // 剩余秒数
  currentRate: 100, // 当前进度
  rate: 100, // 目标进度
})

// 初始化数据
const loadData = (async () => {
  // 等待服务初始化
  await service.onReady()
  // 等待连接交易服务
  await socket.connectTrade()
  // 等待业务数据初始化
  await initBaseData()
})()

// 等待加载数据
const autoLogin = async (loading = false) => {
  const toast = loading ? showLoading() : undefined
  const complete = () => {
    toast?.clear()
    localStorage.setItem('thj_app_guide', 'false')
    plus.exitFullSreen()
  }

  await loadData.catch(() => {
    complete()
    router.replace({ name: 'UserLogin' })
  })

  login().then(() => {
    const redirect = route.query.redirect
    if (redirect) {
      router.replace(redirect.toString())
    } else {
      router.replace({ name: 'Home' })
    }
  }).catch(() => {
    router.replace({ name: 'UserLogin' })
  }).finally(() => {
    complete()
  })
}

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

// 跳过广告
const skip = () => {
  clearInterval(timer)
  autoLogin(true)
}

plus.setFullSreen()
</script>

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