<script setup lang="ts">
import { ref, watch } from "vue";
import { useRequest } from "vue-request";
import { myRequest } from "@/requests/request.ts";
import { menuData, userinfo } from "@/store/store.ts";
import router, { routes } from "@/router/router.ts";
import _ from "lodash";

export const menuUpdate = () => {
  const currentPath = ref("/");
  const { data: menuList } = useRequest(
    () => myRequest(`/api/menu`, userinfo.token),
    {
      refreshDeps: [() => userinfo.token],
      ready: () => Boolean(userinfo.token),
    },
  );
  // 没有菜单信息，返回首页
  if (!menuList.value) {
    currentPath.value = window.location.href.split("#")[1];
    if (currentPath.value === "/") {
      router.push("/");
    }
  }
  // 获取菜单后更新路由
  watch(menuList, () => {
    router.clearRoutes();
    menuData.data = [];
    _.get(menuList, "value.data", [
      { name: "首页", icon: "home", path: "/" },
    ]).map((e: sysMenu) => {
      menuData.data.push({
        name: e.name,
        icon: e.icon,
        path: e.path,
        menu_id: e.menu_id,
        route_only: e.route_only,
        detail: e.detail,
      });
      // 菜单是最后登录的页面
      if (e.path === currentPath.value) {
        menuData.default = e.menu_id;
      }
      // 菜单存在二级菜单，添加二级菜单路由
      if (e.detail && e.detail.length > 0) {
        e.detail.map((m) => {
          if (routes.filter((item) => item.path === m.path).length > 0) {
            router.addRoute(routes.filter((item) => item.path === m.path)[0]);
          }
          if (m.path === currentPath.value) {
            menuData.default = m.menu_id;
          }
        });
      } else {
        if (routes.filter((item) => item.path === e.path).length > 0) {
          router.addRoute(routes.filter((item) => item.path === e.path)[0]);
        }
      }
    });
    // router.addRoute(routes.filter((item) => item.path === "/234")[0]);
    // 路由添加全局匹配页面
    router.addRoute(routes.filter((item) => item.path === "/:catchAll(.*)")[0]);
    console.log(currentPath.value);
    if (menuList.value.length > 0) {
      router.push(currentPath.value);
    }
  });
};
</script>

<template></template>

<style scoped></style>
