<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 { useEnumStore, useErrorInfoStore, useLoginStore } from '@/stores'
import service from '@/services'
import socket from '@/services/socket'

const { getToken } = useLoginStore()
const { getAllEnumList } = useEnumStore()
const { getErrorInfoList } = useErrorInfoStore()
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
  })

  await getAllEnumList().result
  await getErrorInfoList().result

  if (getToken()) {
    // 等待连接交易服务
    await socket.connectTrade().catch((err) => {
      ElMessage.error(err)
      loading.value = false
    })
    // 等待令牌效验
    await checkToken()
    // 等待业务数据初始化
    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>