<template>
  <router-view v-if="isRouterAlive" />
</template>

<script lang="ts" setup>
import { shallowRef, nextTick } from 'vue'
import { useNavigation } from '@/hooks/navigation'
import { dialog } from '@/utils/vant'
import { useLogin } from '@/business/login'
import eventBus from '@/services/bus'

const { userLogout } = useLogin()
const { backHomePage } = useNavigation()
const isRouterAlive = shallowRef(true) // 用于页面重新渲染

const quit = (showLogin = false) => {
  isRouterAlive.value = false
  backHomePage({ tabName: 'home', showLogin }, () => {
    nextTick(() => {
      isRouterAlive.value = true
    })
  })
}

// 接收用户登出通知
eventBus.$on('LogoutNotify', (msg) => {
  userLogout(() => {
    if (msg) {
      dialog({
        message: msg as string,
        showCancelButton: true,
        cancelButtonText: '退出',
        confirmButtonText: '重新登录'
      }).then(() => {
        quit(true)
      }).catch(() => {
        quit()
      })
    } else {
      quit()
    }
  })
})
</script>