import { router } from "@/router";
import { permission } from "@/store/permission";
import { DataScope, RoleLevel, roleLevel } from "@/store/role";
import { Scene } from "@/store/scene";
import { user } from "@/store/user";
import { App } from "vue";

// 操作某个场景 查看是否有权限
export const operateIsPermissionByScene = (scene: Scene) => {
  return true;
  // return (
  //   [RoleLevel.admin, RoleLevel.systemAdmin].includes(roleLevel.value) ||
  //   user.value.info.cameraSns.includes(scene.snCode)
  // );
};

// 查看某个操作是否有权限
export const operateIsPermissionByPath = (...operate: string[]) => {
  // if (import.meta.env.DEV) {
  //   return true;
  // }
  const routeName = router.currentRoute.value.name as string;
  const currentRoleName = `${routeName}:${operate.join(":")}`;
  return permission.value.find((item) => item.resourceKey === currentRoleName);
};

// 查看某个数据操作是否有权限操作
export const operateIsPermissionByDept = (data: any[]) => {
  const permission = operateIsPermissionByPath(...data.slice(1));
  if (!permission) {
    return false;
  } else {
    // 4 5 只有相同depId才能操作
    const sameDeptScopes = [DataScope.personCreate, DataScope.selfInner];
    return (
      !sameDeptScopes.includes((permission as any).dataScope) ||
      data[0].deptId === user.value.info.deptId
    );
  }
};

const argsCover = (value: string | string[] | string[][]): string[][] => {
  if (!Array.isArray(value)) {
    return [[value]];
  } else if (value.length > 0 && !Array.isArray(value[0])) {
    return [value as string[]];
  } else {
    return value as string[][];
  }
};

export const permissionSetup = (app: App) => {
  app.directive("pscene", (el, binding) => {
    const value = argsCover(binding.value) as any;
    value.every((data: any[]) => operateIsPermissionByScene(data[0])) ||
      (el.parentNode && el.parentNode.removeChild(el));
  });
  app.directive("pdscene", (el, binding) => {
    const value = argsCover(binding.value) as any;
    value.every((data: any[]) => operateIsPermissionByScene(data[0])) ||
      el.classList.add("disable");
  });
  app.directive("ppath", (el, binding) => {
    const value = argsCover(binding.value) as any;
    value.every((data: any) => operateIsPermissionByPath(...data)) ||
      (el.parentNode && el.parentNode.removeChild(el));
  });
  app.directive("pdpath", (el, binding) => {
    const value = argsCover(binding.value) as any;
    value.every((data: any) => operateIsPermissionByPath(...data)) ||
      el.classList.add("disable");
  });
  app.directive("pdept", (el, binding) => {
    const value = argsCover(binding.value) as any;
    value.every(operateIsPermissionByDept) ||
      (el.parentNode && el.parentNode.removeChild(el));
  });
  app.directive("pddept", (el, binding) => {
    const value = argsCover(binding.value) as any;
    value.every(operateIsPermissionByDept) || el.classList.add("disable");
  });
};
