import type { App } from 'vue'
import { createRouter, createWebHashHistory } from 'vue-router'
import { staticRoutes } from './routes/staticRoutes'
import { configureNProgress } from './utils/utils'
import { setupBeforeEachGuard } from './guards/beforeEach'
import { setupAfterEachGuard } from './guards/afterEach'

// 创建路由实例
export const router = createRouter({
  history: createWebHashHistory(),
  routes: staticRoutes, // 静态路由
  scrollBehavior: () => ({ left: 0, top: 0 }) // 滚动行为
})

// 处理路由错误（Chunk 加载失败等）
router.onError((error) => {
  const pattern =
    /Loading chunk (\d+) failed|Failed to fetch dynamically imported module|Couldn't resolve component/
  const isChunkLoadFailed = error.message && pattern.test(error.message)

  if (isChunkLoadFailed) {
    const key = '__route_chunk_reload__'
    const hasReloaded = sessionStorage.getItem(key)

    if (!hasReloaded) {
      console.warn('检测到 chunk 加载失败，尝试刷新页面...')
      sessionStorage.setItem(key, '1')
      window.location.reload()
    } else {
      console.error('页面刷新后仍然无法加载组件，请联系管理员')
      sessionStorage.removeItem(key)
    }
  } else {
    console.error('[路由错误]:', error)
  }
})

// 初始化路由
export function initRouter(app: App<Element>): void {
  configureNProgress() // 顶部进度条
  setupBeforeEachGuard(router) // 路由前置守卫
  setupAfterEachGuard(router) // 路由后置守卫
  app.use(router)
}
