import type { App } from 'vue'
import type { RouteRecordRaw } from 'vue-router'
import { createRouter, createWebHistory } from 'vue-router'
import remainingRouter from './modules/remaining'

// 创建路由实例
const router = createRouter({
  history: createWebHistory(), // createWebHashHistory URL带#，createWebHistory URL不带#
  strict: true,
  routes: remainingRouter as RouteRecordRaw[],
  scrollBehavior: () => ({ left: 0, top: 0 })
})


// 监听页面刷新事件
window.addEventListener('beforeunload', () => {
  // 可以在这里做一些清理工作
  sessionStorage.setItem('shouldRedirectToHome', 'true')
})

// 页面加载完成后检查是否需要重定向
router.isReady().then(() => {
  if (sessionStorage.getItem('shouldRedirectToHome')) {
    sessionStorage.removeItem('shouldRedirectToHome')
    router.push('/index') // 或者你的主页路径
  }
})

export const resetRouter = (): void => {
  const resetWhiteNameList = ['Redirect', 'Login', 'NoFind', 'Root']
  router.getRoutes().forEach((route) => {
    const { name } = route
    if (name && !resetWhiteNameList.includes(name as string)) {
      router.hasRoute(name) && router.removeRoute(name)
    }
  })
}

export const setupRouter = (app: App<Element>) => {
  app.use(router)
}

export default router
