import { createRouter, createWebHashHistory } from 'vue-router'
import { useUserStore } from "@/stores/user.js";
import { routes } from "./routes.js"
const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 路由守卫 - 登录验证
router.beforeEach((to, from, next) => {
  // 显示 loading
  const loadingEl = document.getElementById('app-loading');
  if (loadingEl) loadingEl.style.display = 'flex';

  const userStore = useUserStore();
  let token = userStore.authToken || sessionStorage.getItem("authToken") || "";
  if (!token) {
    if (to.path === '/login' || to.meta.nopermission) {
      next();
    } else {
      next('/login')
    }
  } else {
    if (to.path === "/login") {
      next("/");
    } else {
      next();
    }
  }
})

router.afterEach(() => {
  // 隐藏 loading
  const loadingEl = document.getElementById('app-loading');
  if (loadingEl) loadingEl.style.display = 'none';
})

export default router
