import type { App } from "vue";
import { useUserStoreWithOut } from "@/stores/useUserStore";

/** 判断权限的指令 directive */
export function hasPermi(app: App<Element>) {
  app.directive("hasPermi", (el, binding) => {
    const { value } = binding;

    if (value && value instanceof Array && value.length > 0) {
      const hasPermissions = hasPermission(value);

      if (!hasPermissions) {
        el.parentNode && el.parentNode.removeChild(el);
      }
    } else {
      throw new Error("权限错误");
    }
  });
}

/** 判断权限的方法 function */
const all_permission = "*:*:*";
export const hasPermission = (permission: string[]) => {
  const userStore = useUserStoreWithOut();
  return (
    userStore.permissions.has(all_permission) ||
    permission.some((permission) => userStore.permissions.has(permission))
  );
};
