import api from "@/axios";
import { usePermissionStore, type AuthMenuTree } from "@/stores/permission";
import { useUserStore } from "@/stores/user";
import { message } from "@/utils";
import { flatMap, isEmpty, omit } from "lodash-es";
import { type Component } from "vue";
import router from "@/router";
import { LOGIN_ROUTER } from "@/config/constant";
import { type RouteRecordRaw } from "vue-router";

const modules: Record<string, () => Promise<Component>> =
  import.meta.glob<Component>("@/views/**/*.vue");

export const initDynamicRouter = async () => {
  const userStore = useUserStore();
  const permissionStore = usePermissionStore();

  //获取我授权的menu
  // const resp = await api.get<AuthMenuTree[]>("/management/auth/myAuthMenu");
  // if (isEmpty(resp.data)) {
  //   message.warning("您没有任何权限");
  //   userStore.resetUserInfo();
  //   await router.replace(LOGIN_ROUTER.path);
  //   return Promise.reject("当前用户暂无授权权限，请联系管理员进行添加");
  // }
  const removeEmptyChildren = (data: AuthMenuTree[]) => {
    return data.map((item) => {
      if (item.type.value === "dir") {
        //继续递归
        item.children = removeEmptyChildren(item.children!);
      } else if (item.type.value === "menu") {
        //如果是菜单 直接删除children树形
        delete item.children;
      }
      return item;
    });
  };
  // permissionStore.initAuthMenuList(
  //   removeEmptyChildren(resp.data as AuthMenuTree[])
  // );
  //扁平化路由 提取children
  // const flatAuthMenu = flatMenuList(resp.data as AuthMenuTree[]);
  // 动态添加路由
  // flatAuthMenu.forEach((item) => {
  //   const route: RouteRecordRaw = {
  //     name: item.snowFlakeId,
  //     path: item.path,
  //     redirect: item.redirect,
  //     meta: {
  //       btnList: item.btnList,
  //       title: item.name,
  //       icon: item.icon,
  //       isFixed: false,
  //       isKeepAlive: item.isKeepAlive.extData?.boolVal ?? false,
  //       isFull: item.isFull.extData?.boolVal ?? false,
  //       remark: item.remark,
  //     },
  //     component: modules[`/src/views${item.path}/index.vue`],
  //     children: [],
  //   };
  //   if (item.isFull.extData?.boolVal) {
  //     //全屏路由添加到根路由下
  //     router.addRoute(route);
  //   } else {
  //     //非全屏路由添加到layout下
  //     router.addRoute("layout", route);
  //   }
  // });
};

const flatMenuList = (
  menuList: AuthMenuTree[]
): Omit<AuthMenuTree, "children">[] =>
  flatMap(menuList, (item) => [
    omit(item, "children"),
    ...(item.children ? flatMenuList(item.children) : []),
  ]);
