import { Local, Session } from '@/utils/storage';
import { CACHE_KEY } from '@/constants/index';

/**
 * 权限校验指令
 * 使用方法：v-hasPermi="['system:user:add']"
 */
export default {
    mounted(el: HTMLElement, binding: any) {
        const { value } = binding;
        // 兼容 Local 存储与 Session 存储，防止因不同分支的存储容器不同而导致读空
        const cacheData = Local.get(CACHE_KEY.PERMS) || Session.get(CACHE_KEY.PERMS);

        // 兼容直接数组形式 [...] 与 对象包裹形式 { data: [...] } 或 { value: [...] }
        let perms: string[] = [];
        if (Array.isArray(cacheData)) {
            perms = cacheData;
        } else if (cacheData && typeof cacheData === 'object') {
            if (Array.isArray(cacheData.data)) {
                perms = cacheData.data;
            } else if (Array.isArray(cacheData.value)) {
                perms = cacheData.value;
            }
        }

        if (value && value instanceof Array && value.length > 0) {
            const hasPermissions = perms.some(permission => {
                return (value as string[]).includes(permission);
            });

            if (!hasPermissions) {
                // 如果没有权限，则移除元素
                el.parentNode && el.parentNode.removeChild(el);
            }
        } else {
            console.error(`[v-hasPermi]: 请设置操作权限标签值, 如 v-hasPermi="['system:user:add']"`);
        }
    }
};
