import { App, nextTick } from 'vue';
import { useUserInfo } from '@/stores/userInfo';

// 判断数组 A 是否完全包含 B
function hasAllPermissions(required: string[], actual: string[]) {
	return required.every((perm) => actual.includes(perm));
}

// 判断数组 A 是否有任意一个包含 B
function hasAnyPermission(required: string[], actual: string[]) {
	return required.some((perm) => actual.includes(perm));
}

/**
 * 用户权限指令
 * @directive 1. 单个权限判断（v-permission="'edit'"）
 * @directive 2. 任意权限判断（v-permission="['edit', 'create']"）
 * @directive 3. 全部权限判断（v-permission="{ all: ['edit', 'create'] }"）
 * @directive 4. 任意权限判断（v-permission="{ any: ['edit', 'create'] }"）
 */
export function permissionDirective(app: App) {
	app.directive('permission', {
		mounted(el, binding) {
			nextTick(() => {
				const stores = useUserInfo();
				const userPerms = stores.userInfos.authBtnList || [];

				let hasPermission = false;

				const required = binding.value;

				// 1. 如果是单个权限（string 类型）
				if (typeof required === 'string') {
					hasPermission = userPerms.includes(required);
				}
				// 2. 如果是任意一个权限（数组）
				else if (Array.isArray(required)) {
					hasPermission = hasAnyPermission(required, userPerms);
				}
				// 3. 如果是必须全有权限（对象形式）
				else if (typeof required === 'object') {
					if (required.any) {
						hasPermission = hasAnyPermission(required.any, userPerms);
					} else if (required.all) {
						hasPermission = hasAllPermissions(required.all, userPerms);
					}
				}

				// 没有权限时，移除该元素
				if (!hasPermission) {
					el.parentNode?.contains(el) && el.parentNode.removeChild(el);
				}
			}).then();
		},
	});
}
