import type { App } from 'vue';
import { useUserInfo } from '@/stores/userInfo';
import { judgementSameArr } from '@/utils/arrayOperation';
import { nextTick } from 'vue';

/**
 * 用户权限指令
 * @directive 单个权限验证（v-auth="xxx"）
 * @directive 多个权限验证，满足一个则显示（v-auths="[xxx,xxx]"）
 * @directive 多个权限验证，全部满足则显示（v-auth-all="[xxx,xxx]"）
 */

// 判断数组 A 是否完全包含 B
function hasAllPermissions(required: string[], actual: string[]) {
	if (!Array.isArray(required) || required.length === 0) return false;
	return required.every((perm) => actual.includes(perm));
}
export function authDirective(app: App) {
	// 单个权限验证（v-auth="xxx"）
	app.directive('auth', {
		mounted(el, binding) {
			const stores = useUserInfo();
			nextTick(() => {
				const hasPermission = stores.userInfos.authBtnList?.some((v: string) => v === binding.value);
				if (!hasPermission) {
					// ✅ 更安全的做法，确保父节点存在且包含 el
					const parent = el.parentNode;
					if (parent && parent.contains(el)) {
						parent.removeChild(el);
					}
				}
			}).then();
		},
	});
	// 多个权限验证，满足一个则显示（v-auths="[xxx,xxx]"）
	app.directive('auths', {
		mounted(el, binding) {
			const stores = useUserInfo();
			nextTick(() => {
				const requiredPerms = binding.value;
				// 若未传入权限数组，直接隐藏
				if (!Array.isArray(requiredPerms) || requiredPerms.length === 0) {
					el.parentNode?.contains(el) && el.parentNode.removeChild(el);
					return;
				}
				const userPerms = stores.userInfos.authBtnList || [];
				// 是否拥有其中一个权限
				const hasOne = requiredPerms.some((perm: string) => userPerms.includes(perm));
				if (!hasOne) {
					el.parentNode?.contains(el) && el.parentNode.removeChild(el);
				}
			}).then();
		},
	});


	// 多个权限验证，全部满足则显示（v-auth-all="[xxx,xxx]"）
	app.directive('auth-all', {
		mounted(el, binding) {
			nextTick(() => {
				const required = binding.value;
				if (!Array.isArray(required) || required.length === 0) {
					el.parentNode?.contains(el) && el.parentNode.removeChild(el);
					return;
				}

				const stores = useUserInfo();
				const userPerms = stores.userInfos.authBtnList || [];

				const hasAll = hasAllPermissions(required, userPerms);
				if (!hasAll) {
					el.parentNode?.contains(el) && el.parentNode.removeChild(el);
				}
			});
		}
	})
}