import type { Directive } from 'vue';

// 检查权限的通用方法
export const checkPermission = (value: string): boolean => {
  const permissionsData = localStorage.getItem('USER_PERMISSIONS');
  const permissionList = permissionsData ? JSON.parse(permissionsData) : [];
  return permissionList.includes(value);
};

// 暴露的权限检查方法
export const hasPermission = (value: string): boolean => {
  if (!value) return false;
  return checkPermission(value);
};

// 权限指令
export const permission: Directive = {
  mounted(el: HTMLElement, binding) {
    const { value } = binding;
    if (typeof value === 'string' && value) {
      const hasPermission = checkPermission(value);
      if (!hasPermission) {
        el.remove();
      }
    }
  },
};

/**
 * 解析权限值为具体权限对象（数据总览-数据权限页面设置的权限值）
 * @param permissionValue: number 权限值, 例如 31
 * @returns
 */
export const parsePermission = (permissionValue: number) => ({
  read: (permissionValue & 1) !== 0,
  write: (permissionValue & 2) !== 0,
  delete: (permissionValue & 4) !== 0,
  import: (permissionValue & 8) !== 0,
  export: (permissionValue & 16) !== 0,
});
