import { ObjectDirective } from 'vue';
import { usePermission } from '@/hooks/web/usePermission';

/** 支持v-permission直接传入string, string[]，以及兼容原来的方法 */
export const permission: ObjectDirective = {
  mounted(el: HTMLButtonElement, binding) {
    const val = binding.value;
    if (val === undefined) return;

    let permissionVal: string[] = [];
    if (typeof val === 'string') {
      permissionVal = [val];
    } else if (val instanceof Array) {
      permissionVal = val;
    }
    const { hasPermission } = usePermission();
    if (!hasPermission(permissionVal)) {
      el.remove();
      return;
    }
    const { action, effect } = val;

    if (!hasPermission(action)) {
      if (effect == 'disabled') {
        el.disabled = true;
        el.style['disabled'] = 'disabled';
        el.classList.add('is-disabled');
      } else {
        el.remove();
      }
    }
  },
};
