import { watch } from 'vue';
import { hasPermission } from '@/utils/hasPermissionUtil';

export function registerPermission(app) {
  app.directive('permission', {
    mounted(el, binding, vnode) {
      // 一开始不显示权限关联的node节点
      el._preDisplay = el.style.display;
      el.style.display = 'none';

      const handlePermission = key => {
        if (hasPermission(key)) {
          el.style.display = el._preDisplay;
          delete el._preDisplay;
        } else {
          if (binding.value?.type === 'tabs') {
            // 针对tabs标签页类型做特殊处理
            if (vnode?.props?.id) {
              const tabsHtml = el.parentNode.parentNode.parentNode
                .querySelector('.ant-tabs-nav')
                ?.querySelector('.ant-tabs-nav-wrap')
                ?.querySelector('#' + vnode.props.id.replace('panel', 'tab'));
              tabsHtml?.parentNode && tabsHtml?.parentNode?.remove();
            }
          } else {
            el.parentNode && el.parentNode.removeChild(el);
          }
        }
      };

      if (typeof binding.value?.key === 'function') {
        el._handlePermission = watch(
          () => binding.value.key(),
          () => {
            const key = binding.value.key();
            if (key) {
              handlePermission(key);
            }
          },
          {
            immediate: true,
          },
        );
      } else {
        handlePermission(binding.value?.key);
      }
    },
    beforeUnmount(el) {
      el._handlePermission && el._handlePermission();
    },
  });
}
