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: 'YOUR_KEY',
  securityJsCode: 'securityJsCode' // 新版key需要配合安全密钥使用
  // Loca:{
  //  version: '2.0.0'
  // } // 如果需要使用loca组件库，需要加载Loca
})

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