/** v-hasPermission 操作权限处理 */
import type { Directive } from 'vue';
import { useAuthStore } from '@/store/modules/auth';

const hasPermission: Directive<HTMLElement, string | string[]> = {
  mounted(el, { value }) {
    const ALL_PERMISSION = '*:*:*';
    const authStore = useAuthStore();
    const permissions = authStore.userInfo.permissions;
    if (value) {
      let permissionFlag: string[] = [];
      // 如果直接在jsx的语法中写v-hasPermission=['code']，接收到的是字符串,建议使用withDirectives
      if (typeof value === 'string') {
        const matched = value.match(/\[(.*)]/);
        if (matched && matched[1]) {
          permissionFlag = matched[1].split(',').map(s => s.trim().replace(/^['"]|['"]$/g, ''));
        }
      } else if (Array.isArray(value)) {
        permissionFlag = value;
      }

      const hasPermissions = permissions.some(permission => {
        return ALL_PERMISSION === permission || permissionFlag.includes(permission);
      });

      if (!hasPermissions) {
        el.parentNode?.removeChild(el);
      }
    } else {
      throw new Error(`请设置操作权限标签值`);
    }
  }
};

export default hasPermission;
