import { createApp } from "vue";

import ElementPlus from "element-plus";
import "element-plus/dist/index.css";
import locale from "element-plus/lib/locale/lang/zh-cn";

import * as ElementPlusIconsVue from "@element-plus/icons-vue";

import bgui from "@/bg-ui";
import "@/bg-ui/index.scss";

import msgSdk from "./msg-sdk/index.js";

import App from "./App.vue";

import router from "./router";
import { generateRoutes } from "./router/index.js";

import "../src/assets/css/font.css";
import "../src/assets/css/index.css";
import "../src/assets/item.css";

import store from "@/store";

import i18n from "./i18n/i18n.js";

import axios from "./request/http.js";

const createVue = createApp(App);
createVue.use(ElementPlus, { locale });

function getMsgAppid() {
  axios.get(`/apaas/system/v5/message/account`).then((res) => {
    if (res.data.code == 200) {
      createVue.use(msgSdk, {
        requestUrl: "https://msg.wodcloud.com", // 请求地址
        appID: decodeURIComponent(escape(window.atob(res.data.data.app_id))), // 应用id
        secretKey: decodeURIComponent(escape(window.atob(res.data.data.secret_key))), // 应用密钥
        userId: "",
        userType: "",
        roleId: "",
        organization: "",
      });
    }
  });
}

// getMsgAppid()

for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  createVue.component(key, component);
}

createVue.config.globalProperties.$axios = axios;

import menu from "./router/function.js";

//获取用户信息
function getUser() {
  return axios.get(`/apaas/system/v5/user/getUserInfo`);
}

//获取用户菜单信息
function getMenu(search) {
  return axios.get(`/apaas/system/v5/menu/user/tree?search=${search}`);
}

//处理菜单成为对象
function getMenuObj(menu, parentRowPath, menuObj) {
  menu.forEach((e, idx) => {
    e.rowPath = parentRowPath + "." + idx;
    menuObj[e.path] = e;
    if (e.children && e.children.length) {
      getMenuObj(e.children, e.rowPath, menuObj);
    }
  });
}

Promise.all([getUser(), getMenu("dadb2d3f-e263-48d1-9389-42acb9ea49f8")])
  .then((res) => {
    if (res[0].data.code == 200 && res[1].data.code == 200) {
      //已登录则记录菜单和用户信息
      let data = (res[1].data.data && res[1].data.data[0].children) || [];
      store.commit("setUserInfo", res[0].data.data);

      // if (res[0].data.data.userType == 1) {//超管
      store.commit("setMenu", data);
      menu.menuToRouter(data);
      store.commit("setRoute", data);

      //存储菜单对象信息
      let menuObj = {};
      getMenuObj(data, "", menuObj);
      store.commit("setMenuObj", menuObj);

      // }
    }
    generateRoutes();

    createVue.use(ElementPlus).use(store).use(router).use(i18n).use(bgui);
    createVue.mount("#app");
  })
  .catch(() => {
    createVue.use(ElementPlus).use(store).use(router).use(i18n).use(bgui);
    createVue.mount("#app");
  });

//后期加入权限处理，参考msg/ui
