import { computed } from 'vue'
import { useRoute } from 'vue-router'

import { usePermissionStore } from '@/store'

export const usePermission = () => {
	const route = useRoute()
	const permissionStore = usePermissionStore()

	// 默认使用当前路由声明的菜单编码，页面内按钮通常只需要传 buttonCode。
	const currentMenuCode = computed(() => route.meta.menuCode)

	const canAccessMenu = (menuCode?: string) => permissionStore.hasMenuAccess(menuCode)

	const canAccessButton = (buttonCode: string, menuCode = currentMenuCode.value) =>
		permissionStore.hasButtonAccess(menuCode, buttonCode)

	// 页面初始化时可主动预加载按钮权限，v-permission 指令也会按需兜底加载。
	const ensureCurrentPageButtons = async () => {
		if (!currentMenuCode.value) return []
		return permissionStore.ensureButtonPermissions(currentMenuCode.value)
	}

	return {
		currentMenuCode,
		canAccessMenu,
		canAccessButton,
		ensureCurrentPageButtons
	}
}
