import { operation, route } from "@/router";
import { useStores } from "@/store";
import { useCallback } from "react";

const roleList: any[] = [
  { VIEWER: 1 },
  { USER: 2 },
  { MANAGER: 3 },
  { OWNER: 4 }
]

const usePass = () => {
  const { permissionStore } = useStores();
  const { currentProjectStore } = useStores();

  const isPass = useCallback(
    (key: string, role?: "VIEWER" | "USER" | "MANAGER" | "OWNER", routes?: Array<route | operation>): boolean => {
      let code = currentProjectStore && currentProjectStore.currentProjectInfo.projectRole
      if (role) {
        if (code && roleList.filter(e => e[role])[0][role] <= roleList.filter(e => e[code as string])[0][code]) {
          if (routes) {
            for (let item of routes) {
              if (item.id === key) {
                return true;
              } else if (
                item.type === "page" &&
                item.children?.length &&
                isPass(key, role, item.children)
              ) {
                return true;
              }
            }
          } else {
            for (let item of permissionStore.allRoutes) {
              if (item.type !== "navigate" && item.id === key) {
                return true;
              } else if (
                item.type === "page" &&
                item.children?.length &&
                isPass(key, role, item.children)
              ) {
                return true;
              }
            }
          }
        } else {
          return false
        }
      } else {
        if (routes) {
          for (let item of routes) {
            if (item.id === key) {
              return true;
            } else if (
              item.type === "page" &&
              item.children?.length &&
              isPass(key, role, item.children)
            ) {
              return true;
            }
          }
        } else {
          for (let item of permissionStore.allRoutes) {
            if (item.type !== "navigate" && item.id === key) {
              return true;
            } else if (
              item.type === "page" &&
              item.children?.length &&
              isPass(key, role, item.children)
            ) {
              return true;
            }
          }
        }
      }
      return false;
    },
    [permissionStore.allRoutes, currentProjectStore]
  );

  return isPass;
};

export default usePass;
