<script lang="ts" setup>
import { computed, ref } from 'vue';
import { clone } from '@pureadmin/utils';
import type { ElTreeV2 } from 'element-plus';
import { useRenderIcon } from '@/components/ReIcon/src/hooks';
import { deleteChildren, extractPathList } from '@/utils/tree';
import { usePermissionStoreHook } from '@/store/modules/permission';
import type { TreeNode } from 'element-plus/es/components/tree-v2/src/types';
import NodeTree from '@iconify-icons/ri/node-tree';

defineOptions({
	name: 'MenuTree',
});

interface treeNode extends TreeNode {
	meta: {
		title: string;
	};
}

const query = ref('');
const dataProps = ref({
	value: 'uniqueId',
	children: 'children',
});
const treeRef = ref<InstanceType<typeof ElTreeV2>>();
const menusTree = clone(usePermissionStoreHook().wholeMenus, true);

const menusData = computed(() => {
	return deleteChildren(menusTree);
});

const expandedKeys = extractPathList(menusData.value);

const onQueryChanged = (query: string) => {
	(treeRef as any).value!.filter(query);
};

const filterMethod = (query: string, node: treeNode) => {
	return $t(node.meta.title)!.indexOf(query) !== -1;
};
</script>

<template>
	<el-card shadow="never">
		<template #header>
			<div class="card-header">
				<span class="font-medium">
					菜单树结构（采用 Element Plus 的
					<el-link :icon="useRenderIcon(NodeTree)" href="https://element-plus.gitee.io/zh-CN/component/tree-v2.html" style="margin: 0 5px 4px 0; font-size: 16px" target="_blank"> Tree V2 </el-link>
					组件并支持国际化）
				</span>
			</div>
			<el-link class="mt-2" href="https://github.com/pure-admin/vue-pure-admin/blob/main/src/views/able/menu-tree.vue" target="_blank"> 代码位置 src/views/able/menu-tree.vue </el-link>
		</template>
		<el-input v-model="query" class="mb-4" clearable placeholder="请输入关键字查找" @input="onQueryChanged" />
		<el-tree-v2 ref="treeRef" :data="menusData" :default-expanded-keys="expandedKeys" :filter-method="filterMethod" :height="500" :props="dataProps" show-checkbox>
			<template #default="{ data }">
				<span>{{ $t(data.meta.title) }}</span>
			</template>
		</el-tree-v2>
	</el-card>
</template>
