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

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

export const roleMap = {
  VIEWER: '查看者',
  USER: '研究员',
  MANAGER: '管理员',
  OWNER: '所有者',
}

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;
