<template>
  <div class="boot">
    <el-button :loading="loading" v-if="loading">正在初始化...</el-button>
    <el-button @click="initService" v-else>重试</el-button>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { initBaseData, checkToken } from '@/business/common'
import { sessionData } from '@/stores'
import service from '@/services'
import eventBus from '@/services/bus'
import socket from '@/services/socket'

const route = useRoute()
const router = useRouter()
const loading = ref(false)

const initService = async () => {
  loading.value = true

  // 等待服务初始化
  await service.onReady().catch((err) => {
    ElMessage.error(err)
    loading.value = false
  })

  if (sessionData.getLoginInfo('Token')) {
    // 等待连接交易服务
    await socket.connectTrade().catch((err) => {
      ElMessage.error(err)
      loading.value = false
    })

    // 等待令牌效验
    await checkToken().catch(() => {
      eventBus.$emit('LogoutNotify')
    })

    // 等待业务数据初始化
    await initBaseData().catch((err) => {
      ElMessage.error(err)
      loading.value = false
    })
  }

  // 路由跳转
  const redirect = route.query.redirect
  if (redirect) {
    router.replace(redirect.toString())
  } else {
    router.replace('/')
  }
}

initService()
</script>

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