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 enLocale from "element-ui/lib/locale/lang/en";

import baseStores from "@/store";
import baseRoutes from "@/router";
import baseTabs from "@/tabs";
import BaseApi from '@/api/base/BaseApi';
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, PageTable, Util, UsualConfig, Validate} from "@/libs";

import "@/styles/index.scss";

import Uploader from "@/common/Uploader.vue";
import SelectorTree from "@/common/SelectorTree.vue";
import OptionHistory from "@/common/OptionHistory.vue";

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

// 全局注册实例配置(实际配置)
Vue.prototype.$config = config;

// 全局实例配置 (为了IDE提示)
Vue.mixin({
  data() {
    return {
      $config: config
    }
  }
});

/**
 *
 * 主要启动函数
 * @param  {{init: function(home:Vue):void, el: string, stores:{},routes:[], tabs: {Object}, config: {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 || config.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;

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

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

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

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

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