import { createApp } from "vue";
import ElementPlus from "element-plus";
import "element-plus/dist/index.css";
import zhCn from "element-plus/es/locale/lang/zh-cn";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import md5 from "md5";
import "./styles/index.css";
import Uploader from "./components/Uploader.vue";
import Certs from "./components/Certs.vue";
import RemoteSearch from "./components/RemoteSearch.vue";

const app = createApp(App);
app.component("RemoteSearch", RemoteSearch);
app.component("Certs", Certs);
app.component("Uploader", Uploader);

let userId = localStorage.userId;
if (userId) {
  store.dispatch("GetBasePermissionData", localStorage.loginAccountId);
  store.dispatch("GetUserPermission", localStorage.loginAccountId);
}

router.beforeEach(async (to, from, next) => {
  if (localStorage.userId) {
    store.commit("changeLogin", true);
    let rolePermission = localStorage.rolePermission?.split(",") || [];
    if (store.state.menuData.length) {
      let path = store.state?.menuData[0]?.items[0].path;
      if (0 === to.matched.length) {
        next(path);
      } else if (to.path == "/login" || to.path == "/") {
        next(path);
      } else if (rolePermission?.indexOf(to.meta.code) == -1) {
        next(path);
      } else {
        next();
      }
    } else {
      if (to.path == "/") {
        next("/voyage/voyageList");
      } else {
        next();
      }
    }
  } else {
    store.commit("changeLogin", false);
    if (to.path == "/login") {
      next();
    } else {
      next("/login");
    }
  }
});
router.afterEach((to, from) => {
  let { title } = to.meta;
  document.title = title;
  store.commit("setCurrentMenuItem", to.path);
  store.commit("changefirstTitle", title);
});

app.directive("auth", {
  mounted(el, bind) {
    let permissions = localStorage.rolePermission?.split(",") || [];
    if (permissions.indexOf(bind.value) == -1) {
      el.parentNode.removeChild(el);
    }
  },
});

app
  .use(router)
  .use(ElementPlus, {
    locale: zhCn,
  })
  .use(store)
  .mount("#app");
