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

initAMapApiLoader({
  key: '0c5c83112cafefa77154769b4433c3df',
  securityJsCode: '184c86be3bbd9a8a941bcaaf6b09c7cd' // 新版key需要配合安全密钥使用
})

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

// 动态路由
const routes = Object.values(import.meta.glob('./views/*/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
})
// 路由守卫
// router.beforeEach((to, from, next) => {
//   // do something
//   next()
// })
app.use(store)
  .use(router)
  .use(VueAMap)
  .use(naive)
  .component('Icon', Icon)

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, '')
  })
})
