import { computed, ref } from "vue";
import { defineStore } from "pinia";
import { constantRoutes } from "@/router/route";

const isSidebarRoute = (route) =>
  route.path !== "/" &&
  route.meta?.layout !== false &&
  !route.meta?.hidden &&
  route.meta?.title;

const buildRoutePath = (parentPath, routePath) => {
  if (routePath.startsWith("/")) {
    return routePath;
  }

  return parentPath ? `${parentPath}/${routePath}` : `/${routePath}`;
};

// isChild是否需要返回child
const normalizeMenuRoute = (route, parentPath = "") => {
  const fullPath = buildRoutePath(parentPath, route.path);
  const children = (route.children || [])
    .filter((child) => child.meta?.title && !child.meta?.hidden)
    .map((child) => normalizeMenuRoute(child, fullPath));

  return {
    path: fullPath,
    title: route.meta?.title || "",
    iconName: route.meta?.icon || "Document",
    hidden: Boolean(route.meta?.hidden),
    children,
  };
};

export const useRouteStore = defineStore("route", () => {
  // 当前页面完整路由
  const currentPath = ref("/");

  // 设置当前页面完整路由
  const setCurrentPath = (path) => {
    currentPath.value = path || "/";
  };

  // 主路由
  const allMainRoutes = constantRoutes
    .filter(isSidebarRoute)
    .map((route) => normalizeMenuRoute(route, ""));

  const mainRoutes = allMainRoutes.slice(0, 8);

  const moreMainRoutes = allMainRoutes.slice(8);

  const activeMainRoute = computed(() =>
    allMainRoutes.find((route) => currentPath.value.startsWith(route.path)),
  );

  const sideRoutes = computed(() => activeMainRoute.value?.children || []);

  const activeSideRoute = computed(() =>
    sideRoutes.value.find((route) => currentPath.value.startsWith(route.path)),
  );

  return {
    constantRoutes,
    currentPath,
    setCurrentPath,
    mainRoutes,
    moreMainRoutes,
    activeMainRoute,
    sideRoutes,
    activeSideRoute,
  };
});
