import "./base";
import Vue from "vue";
import Vuex from "vuex";
import VueRouter from "vue-router";

import zhLocale from "element-ui/lib/locale/lang/zh-CN";

import baseStores from "@/store";
import baseRoutes from "@/router";
import baseTabs from "@/tab";
import plugin from "@/plugin";
import TabView from "@/plugin/TabView";
import service from "@/service";
import Locale from "@/locale/locale";
import config from "@/config.js";

import { Ajax, CacheService, PageTable, Util } from "@/libs";

import "@/styles/index.scss";

import Uploader from "@/common/Uploader.vue";
import TimeLine from "@/common/TimeLine.vue";
import SelectorTree from "@/common/SelectorTree.vue";
import HandleHistory from "@/common/HandleHistory.vue";

Vue.use(plugin);
Vue.locale("zh-CN", Object.assign(zhLocale, Locale["zh-CN"]));

/**
 * 主要启动函数
 * @param {Object} cfg 启动的配置
 */
function bootstrap(cfg) {
  cfg.stores = Object.assign(baseStores, cfg.stores);
  cfg.tabs = Object.assign(baseTabs, cfg.tabs);

  let routeMap = new Map();
  baseRoutes.forEach(route => {
    routeMap.set(route.path, route)
  })
  if (cfg.routes) {
    cfg.routes.forEach(route => {
      routeMap.set(route.path, route)
    })
  }
  cfg.routes = []
  routeMap.forEach((value, key) => {
    cfg.routes.push(value)
  })

  //合并配置
  Object.assign(config, cfg.config);

  //初始化方法
  config.init = cfg.init;

  //构造状态机
  const store = new Vuex.Store({
    modules: cfg.stores
  });

  //路由器
  const router = new VueRouter({
    routes: cfg.routes
  });

  //选项卡
  const tabView = new TabView({
    views: cfg.tabs
  });

  //启动websocket服务
  service.WebSocketService.bootstrap();

  //设置ajax基本路径
  Ajax.defaults.baseURL = config.ajaxUrl;

  //挂在元素
  const el = cfg.el;

  //组成配置对象
  let base = {
    el,
    asd: {},
    router,
    store,
    tabView,
    render: h => h("router-view")
  };

  return new Vue(base);
}

//导出公共组件
export { Uploader, TimeLine, SelectorTree, HandleHistory };

//导出lib库
export { Ajax, Util, PageTable };

//导出 配置,服务,国际化,路由,状态机,缓存服务
export { config, service, Locale, CacheService };

//全局启动对象
export default { bootstrap, config };
