import { createApp } from "vue";
import "./style.css";
import App from "./App.vue";
// 引入element-plush
import ElementPlus from "element-plus";
import "@/assets/css/element.scss";
// @ts-ignore
import zhCn from "element-plus/dist/locale/zh-cn.mjs";
import * as ElementPlusIconsVue from "@element-plus/icons-vue";
import "./assets/css/default.scss";
import "./assets/css/reset.scss";
import { createPinia } from "pinia";
import routers from "./routers/index";
import { userInfor } from "./store/user/user";
import { globalState } from "./store";
import globalComponents from "@/util/globalComponents";
import JsonExcel from "vue-json-excel3";
import print from "vue3-print-nb";

let app = createApp(App);
app.use(print);

for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component);
}
app.component("downloadExcel", JsonExcel);
app
  .use(createPinia())
  .use(routers)
  .use(ElementPlus, { locale: zhCn })
  .use(globalComponents)
  .mount("#app");

// 得挂载后才能使用
let userInforState = userInfor();
let globalStateState = globalState();
let closeLoadingShow = () => globalStateState.setLoadingShow(false);

routers.afterEach((to) => {
  globalStateState.setLoadingShow(true, "正在前往");
  if (!userInforState.token && to.path !== "/login") {
    let tempUserInfor = JSON.parse(localStorage.getItem("userInfor") as string);
    let tempToken = localStorage.getItem("token");
    let temoRefreshToken = localStorage.getItem("refreshToken");
    let tempHistoryRouter = localStorage.getItem("historyRouterPath");

    if (tempUserInfor && tempToken && temoRefreshToken) {
      userInforState.setLoginState(tempUserInfor);
      userInforState.setToken(tempToken);
      userInforState.setRefToken(temoRefreshToken);

      // 如果有历史路由，保持历史路由路径，无感刷新页面
      if (tempHistoryRouter) {
        routers.push({ path: tempHistoryRouter as string });
      }
      closeLoadingShow();
    } else {
      routers.replace({ path: "/login" });
      closeLoadingShow();
    }
    return;
  }
  globalStateState.setHistoryRouterPath(to.path);
  closeLoadingShow();
});
