<script setup>
// items内容：
//   name - 名称
//   icon - 图标
//   command - 触发函数
//   url - 链接URL
//   target - 链接目标类型
//   disabled - 是否禁用
//   visible - 是否显示
//   separator <boolean> 是否为分隔线
//   active <boolean> 是否已选中
//   code|key - 菜单键值
//   items - 子菜单内容，格式为：[subItem1, subItem2, ...]
//

import PanelMenu from "primevue/panelmenu";
import {ref, watch} from "vue";

const expandedKeys = ref(null)
const props = defineProps(["items"])

const processItems = () => {
	props.items.forEach(item => {
		item._level = 1

		// implement name attribute
		if (typeof item.name === "string") {
			item.label = item.name
		}

		// implement code attribute
		if (typeof item.code === "string") {
			item.key = item.code
		}

		if (typeof item.key !== "string") {
			console.error("'TMenuAccordion' menu item", item, "must contains a 'key' or 'code' properity")
		}

		if (item.items instanceof Array) {
			item.items.forEach(subItem => {
				if (typeof subItem.name === "string") {
					subItem.label = subItem.name
				}

				if (typeof subItem.code === "string") {
					subItem.key = subItem.code
				}
			})
		}

		if (typeof item.active === "boolean" && item.active && typeof item.key === "string") {
			expandedKeys.value = {
				[item.key]: true
			}
		}
	})
}

if (props.items instanceof Array) {
	processItems()
}

watch(() => props.items, () => {
	processItems()
})

const emits = defineEmits(["change"])

const onPanelOpen = e => {
	props.items.forEach(item => {
		if (item !== e.item) {
			item.active = false
		}
	})

	if (expandedKeys.value !== null && typeof expandedKeys.value === "object" && typeof e.item.key === "string") {
		expandedKeys.value = {
			[e.item.key]: true
		}
	}

	emits("change", {value: e.item})
}

const onPanelClose = e => {
	emits("change", {value: null})
}

</script>

<template>
	<PanelMenu :model="items" v-model:expandedKeys="expandedKeys" :multiple="false" @panelOpen="onPanelOpen"
			   @panelClose="onPanelClose">
		<template #item="{ item, props, active }">
			<div v-if="item.label=='-'" class="bg-gray-100 dark:bg-gray-700 h-0.5 -ml-4 my-2">
			</div>
			<a
				v-if="item.label !='-'" v-ripple class="cursor-pointer text-surface-700 dark:text-surface-0 px-4 py-2 relative"
				:class="{'t-active-item': item.active, 'inline-block w-full':item._level == 1}" v-bind="{...props.action, 'aria-hidden': false}"
				:href="(typeof item.url === 'string' && item.url.length > 0) ? item.url : null"
			>
				<span :class="item.icon" v-if="item.icon"/>
				<span class="ml-2">{{ item.label }}</span>

				<span class="absolute top-2.5 right-4" v-if="item.items && item.items.length > 0">
						<i class="pi pi-angle-up" v-if="active"></i>
						<i class="pi pi-angle-down" v-if="!active"></i>
					</span>
			</a>
		</template>
	</PanelMenu>
</template>

<style scoped>
.t-active-item, :deep(.p-panelmenu-header-active a) {
	color: var(--p-primary-color);
}
</style>