import Vue from 'vue'
import { loadRoutes, loadGuards, setAppOptions } from '@vue2-client/utils/routerUtil'
import { loadInterceptors } from '@vue2-client/utils/request'
import guards from '@vue2-client/router/guards'
import interceptors from '@vue2-client/utils/axios-interceptors'
import { getConfigByName } from '@vue2-client/services/api/common'
import { hiPrintPlugin } from '@vue2-client/plugins/HiPrintPlugin'
import LoggerPlugin from '@vue2-client/base-client/plugins/LoggerPlugin'
import { isMicroAppEnv } from '@vue2-client/utils/microAppUtils'

/**
 * 启动引导方法
 * 应用启动时需要执行的操作放在这里
 * @param router 应用的路由实例
 * @param store 应用的 vuex.store 实例
 * @param i18n 应用的 vue-i18n 实例
 * @param message 应用的 message 实例
 */
async function bootstrap ({ router, store, i18n, message }) {
  Vue.$store = store
  // 获取系统配置
  if (store) {
    // microApp 环境下作为子应用不获取webConfig
    if (!isMicroAppEnv()) {
      await getConfigByName('webConfig', undefined, res => {
        localStorage.setItem(process.env.VUE_APP_WEB_CONFIG_KEY, JSON.stringify(res))
        if (res?.setting) {
          Vue.$store.commit('setting/setSetting', res?.setting)
        }
      })
    }
    if (process.env.VUE_APP_SYSTEM_NAME && process.env.VUE_APP_SYSTEM_NAME === 'af-his') {
      await getConfigByName('componentStyles', undefined, res => {
        localStorage.setItem(process.env.VUE_APP_WEB_STYLES_KEY, JSON.stringify(res))
      })
    }
  }
  // 设置应用配置
  setAppOptions({ router, store, i18n })
  // 加载 axios 拦截器
  loadInterceptors(interceptors, { router, store, i18n, message })
  // 注册 Logger 插件（在任何地方都可以使用 this.$logger）
  Vue.use(LoggerPlugin)
  if (router) {
    // 加载路由
    loadRoutes()
    // 加载路由守卫
    loadGuards(guards, { router, store, i18n, message })
    // 加载通用插件
    Vue.use(hiPrintPlugin)
  }
}

export default bootstrap
