<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { useRoute, useRouter, RouteRecordRaw } from "vue-router";
import MenuItem from "./MenuItem.vue";
import type { RouteRecordRawWithMeta } from "~/router/routes.d";
// import { asyncFilteredRoutes } from "~/router/index";

const modules: Record<string, { default: RouteRecordRaw }> = import.meta.glob(
  "~/router/routes/manage/*.ts",
  { eager: true }
);

const constantRoutes: RouteRecordRaw[] = [];
const asyncRoutes: RouteRecordRaw[] = [];
Object.keys(modules).forEach((path) => {
  const arr = path.split("/");
  const filename = arr[arr.length - 1];
  if (filename?.startsWith("_")) constantRoutes.push(modules[path].default);
  else asyncRoutes.push(modules[path].default);
});

const asyncFilteredRoutes = [...asyncRoutes];

const router = useRouter();
const route = useRoute();

// const allRoutes = computed(() => {
//   const routes = asyncFilteredRoutes as unknown as RouteRecordRawWithMeta[];
//   return routes.sort((a, b) => a.meta.sort - b.meta.sort);
// });
const allRoutes = computed(() => {
  const routes: RouteRecordRawWithMeta[] = JSON.parse(
    sessionStorage.getItem("routes") as string
  );
  return routes.sort((a, b) => a.meta.sort - b.meta.sort);
});
console.log("allRoutes :>> ", allRoutes);
const index = computed(() => {
  const reservedMatched = [...route?.matched].reverse();
  for (const r of reservedMatched) {
    if (!r.meta.hidden)
      return (r?.redirect as { name: string })?.name ?? r.name;
    else return r.meta?.selected || "/";
  }
  return "/";
});
</script>

<template>
  <el-menu class="w-full border_right_none" :default-active="index" text-color="#000">
    <MenuItem v-for="route in allRoutes" :key="route.name" :item="route" />
  </el-menu>
</template>

<style lang="scss" scoped>
.border_right_none {
  border-right: none;
}
</style>
