<template>
	<div class="menu-tree" style="display: flex; flex-direction: column">
		<menu-tree-item v-for="menu of menuList" :key="menu.id" :menu="menu" :permissions="permissionMap" @update:permissions="updatePermission" />
	</div>
</template>

<script lang="ts" setup>
import requestMenu from '../../../../api/system/menu'
import { SystemMenu } from '../../../../entity/system/system-menu'
import { onMounted, reactive, watch } from 'vue'
import { AccountRolePermission } from '../../../../entity/account/account-role'
import MenuTreeItem from './MenuTreeItem.vue'

let props = defineProps<{ permissions: Array<AccountRolePermission> }>()
/**
 * 更改父容器组件
 */
const emit = defineEmits<{ (e: 'update:permissions', permissions: Array<AccountRolePermission>): void }>()

const menuList = reactive<Array<SystemMenu>>([])

/**
 * 权限列表，用于展示以及比对
 */
const permissionMap = reactive<{ [key: string]: AccountRolePermission }>({})

function updatePermission(menuCode: string, permission: string) {
	permissionMap[menuCode] = <AccountRolePermission>{
		fkMenuCode: menuCode,
		permissionValue: permission
	}
	emit('update:permissions', Object.values(permissionMap))
}

watch(
	() => props.permissions,
	() => {
		const result: { [key: string]: AccountRolePermission } = {}
		for (let permission of props.permissions) {
			result[permission.fkMenuCode] = permission
		}
		Object.assign(permissionMap, result)
	},
	{ deep: true }
)

onMounted(async () => {
	let { data } = await requestMenu.menuList()
	Object.assign(menuList, data)
	// menuList.value = data
})
</script>
<script lang="ts">
export default {
	name: 'MenuTree'
}
</script>

<style scoped>
.menu-tree {
	display: flex;
	flex-direction: column;
}
</style>
