import { defineStore } from "pinia";
import { computed, ref } from "vue";

export interface AuthMenuTree {
  /** 菜单ID **/
  snowFlakeId: string;
  /** 父菜单id **/
  parentId: string;
  /** 路由名称 **/
  name: string;
  /** 菜单路径 **/
  path: string;
  /** 重定向到其他页面 **/
  redirect: string;
  /** 类型 **/
  type: SelectNodeVo<"dir" | "menu" | "btn">;
  /** 菜单图标 **/
  icon: string;
  /** 外部链接点击跳转网址 **/
  link: string;
  /** 是否全屏展示 **/
  isFull: SelectNodeVo<
    0 | 1,
    {
      boolVal: boolean;
    }
  >;
  /** 是否缓存 **/
  isKeepAlive: SelectNodeVo<
    0 | 1,
    {
      boolVal: boolean;
    }
  >;
  /** 备注 **/
  remark: string;
  /** 按钮权限 **/
  btnList: SelectNodeVo<string>[];
  /** 子项 **/
  children?: AuthMenuTree[];
}

const allBreadcrumbList = (
  menuList: AuthMenuTree[],
  parent: SelectNodeVo<string>[] = [],
  result: {
    [key: string]: SelectNodeVo<string>[];
  } = {}
) => {
  for (const item of menuList) {
    result[item.path] = [
      ...parent,
      { value: item.path, label: item.name, extData: { icon: item.icon } },
    ];
    if (item.children)
      allBreadcrumbList(item.children, result[item.path], result);
  }
  return result;
};

export const usePermissionStore = defineStore("permission", () => {
  const authMenuList = ref<AuthMenuTree[]>([]);
  const initAuthMenuList = (list: AuthMenuTree[]) => {
    authMenuList.value = list;
  };
  const clearAuthMenu = () => {
    authMenuList.value = [];
  };
  const breadcrumbList = computed(() => allBreadcrumbList(authMenuList.value));
  return {
    initAuthMenuList,
    authMenuList,
    breadcrumbList,
    clearAuthMenu,
  };
});
