import { createApp } from "vue";
import App from "./App.vue";
// 注入路由
import router from "./router";
import { getToken, cleanSession } from "@/utils/auth";
import { store, key } from "@/store";
import * as ElIconModules from "@element-plus/icons-vue";
//全局添加组件
// 全局注入ui组件库,按需引入迁移到vite.config.ts配置
import ElementPlus from "element-plus";
import "element-plus/dist/index.css";
import { CopyData, resetForm } from "./utils/common";
import LqConfirm from "./utils/LqConfirm";

//引入按钮权限
import { permission } from "./directives/permission";

// 国际
import i18n from "@/lang/index";

//注册svg图标脚本
import "virtual:svg-icons-register";
import GlobalComponents from "./global-components";

const whiteList = ["/login"]; //白名单
// 设置路由导航守卫
router.beforeEach(async (to, from, next) => {
  //设置标题
  if (to.meta.title) {
    document.title = String(to.meta.title);
  } else {
    document.title = import.meta.env.VITE_APP_TITLE;
  }
  //获取token
  let token = getToken();
  if (token) {
    if (to.path === "/login" || to.path === "/") {
      next({ path: "/" });
    } else {
      if (store.state.menu.menuList.length == 1) {
        try {
          await store.dispatch("user/getInfo");
          await store.dispatch("menu/getMenuList", router);
          next({ ...to, replace: true });
        } catch (error) {
          cleanSession();
          next({ path: "/login" });
        }
      } else {
        next();
      }
    }
  } else {
    //判断是否在白名单中
    if (whiteList.indexOf(to.path) !== -1) {
      //存在白名单，放行
      next();
    } else {
      //不存在，登录
      next({ path: "/login" });
    }
  }
});

const app = createApp(App);
Object.keys(ElIconModules).forEach((key) => {
  app.component(key, ElIconModules[key as keyof typeof ElIconModules]);
});
app.use(store, key);
app.use(router);
app.use(ElementPlus);
app.use(i18n);
app.mount("#app");
//注册
app.directive("permission", permission);

GlobalComponents(app);

//清空表单
app.config.globalProperties.$resetForm = resetForm;
//对象复制
app.config.globalProperties.$objCoppy = CopyData;
//确定弹框
app.config.globalProperties.$lqconfirm = LqConfirm;
