import { createRouter, createWebHistory } from "vue-router";
import { commonRoutes } from "@/router/common";
import useStore from "@/store/index";
import { storeToRefs } from "pinia";

const routes = commonRoutes;
const router = createRouter({
  history: createWebHistory("/"),
  routes,
  scrollBehavior(to, form, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    } else {
      return { top: 0 };
    }
  },
});

router.beforeEach(async (to, from, next) => {
  const { useUserStore } = useStore();
  const { isLogin, token } = storeToRefs(useUserStore);
  // 若已获取到 token，则认为已登录，修正 isLogin
  if (!isLogin.value && token && token.value) {
    useUserStore.$patch({ isLogin: true });
  }
  if (!isLogin.value && to.name !== "login") {
    ElMessage.error("暂未登录");
    next({ name: "login" });
    return;
  }

  next();
});

export default router;
