import 'current-script-polyfill' // 修复ie11报堆栈溢出的问题
import _vue from 'vue'
import VueRouter from 'vue-router'
import VueMeta from 'vue-meta'
import PortalVue from 'portal-vue'
import App from './app.vue'
import routerReady from '@/common/router-ready'
import axios from './common/services/axios-instance'
import { fireReady as fireRouterReady } from './common/router-ready'
import { fireReady as fireAppReady } from './common/app-ready'

// frame要先导入，因为别的模块会引用sd-frame这个路由
import './frame/index-normalize-route'
// 导入各个业务模块
import './modules'

import routerService from './common/services/router-service'
import asyncComponent from './common/services/async-component'
import store from './common/store'
import i18n from './i18n/fallback'

// 这样就能通过ts类型检查，原因尚不明确
const Vue = _vue

Vue.config.productionTip = false

Vue.use(VueRouter)
Vue.use(VueMeta)
Vue.use(PortalVue)

const sd404 = asyncComponent(() =>
  import(/* webpackChunkName: "src-error" */ '@/common/pages/sd-404.vue')
)
const sd404InFrame = asyncComponent(() =>
  import(/* webpackChunkName: "src-error" */ '@/common/pages/sd-404-in-frame.vue')
)
routerService.route('/sd-frame').child('*', {
  component: sd404InFrame,
})
routerService.route('/*', {
  component: sd404,
})

const router = new VueRouter({
  // @ts-ignore
  routes: routerService.export(),
})
routerReady((router) => {
  router.beforeEach((to, from, next) => {
    // 首页或登录页不重定向，防止重复跳转
    if (to.path === '/' || to.path === '/audit-home' || to.path === '/sd-login') {
      next()
      return false
    }
    // 判断导航权限
    axios({
      url: 'api/xcoa-mobile/v1/iam-menu/findMenuRole?path=' + to.fullPath,
      method: 'get',
    }).then((res) => {
      if (res.data) {
        next()
      } else {
        next('/sd-home')
      }
    })
    next()
  })
})
// 发出routerReady的通知，可以在其他模块中注册router的钩子
fireRouterReady(router)

// eslint-disable-next-line vue/require-name-property
const vueInstance = new Vue({
  i18n,
  store,
  router,
  render: (h) => h(App),
}).$mount('#app')

fireAppReady(vueInstance)
