/** v-hasRole 角色权限处理 */
import type { Directive } from 'vue';
import { useAuthStore } from '@/store/modules/auth';

const hasRole: Directive<HTMLElement, string[] | string> = {
  mounted(el, { value }) {
    const SUPER_ADMIN = 'superadmin';
    const authStore = useAuthStore();
    const roles = authStore.userInfo.roles;

    if (value) {
      let roleFlag: string[] = [];
      if (typeof value === 'string') {
        // 定义在jsx的语法中，接收到的是字符串
        const matched = value.match(/\[(.*)]/);
        if (matched && matched[1]) {
          roleFlag = matched[1].split(',').map(s => s.trim().replace(/^['"]|['"]$/g, ''));
        }
      } else if (Array.isArray(value)) {
        roleFlag = value;
      }

      const hasRoles = roles.some(role => {
        return SUPER_ADMIN === role || roleFlag.includes(role);
      });

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

export default hasRole;
