import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'
import naive from '@/assets/native-plugin'
import { createRouter, RouteRecordRaw, createWebHashHistory } from 'vue-router'
import Icon from '@/components/icon.vue'
import 'virtual:svg-icons-register'
import piniaPersist from 'pinia-plugin-persist'

const store = createPinia()
store.use(piniaPersist)

// 动态路由
const routes = Object.values(import.meta.glob('./pages/*/route.ts', { eager: true, import: 'default' })) as unknown as RouteRecordRaw[]
routes.push({ path: '/:path(.*)', redirect: '/' })

const app = createApp(App)
const router = createRouter({
  history: createWebHashHistory(),
  routes
})
app.component('Icon', Icon)
// 路由守卫
// router.beforeEach((to, from, next) => {
//   // do something
//   next()
// })
app.use(store)
  .use(naive)
  .use(router)

router.isReady().then(() => {
  const vm = app.mount('#app')
  app.config.errorHandler = (err: any) => {
    if (err.reason === 401) {
      router.replace('/')
    } else {
      console.log('提升', err)
    }
  }
  window.addEventListener('unhandledrejection', (evt) => {
    console.error(evt)
    evt.preventDefault()
    app.config.errorHandler?.(evt, vm, '')
  })
  window.addEventListener('error', (evt) => {
    console.error(evt)
    evt.preventDefault()
    app.config.errorHandler?.(evt.error, vm, '')
  })
})
