<template>
    <div>
        <a-input-search v-model:value="searchValue" style="margin-bottom: 8px" placeholder="Search" />
        <a-tree :expanded-keys="expandedKeys" :auto-expand-parent="autoExpandParent" :tree-data="list" @select="onSelect"
            @expand="onExpand">
            <template #title="{ title }">
                <span v-if="title.indexOf(searchValue) > -1">
                    {{ title.substr(0, title.indexOf(searchValue)) }}
                    <span style="color: #f50">{{ searchValue }}</span>
                    {{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
                </span>
                <span v-else>{{ title }}</span>
            </template>
        </a-tree>
    </div>
</template>

<script setup lang="ts">
import { categoryStore } from '/@/store/Category'
import { ref, watch, defineEmits } from 'vue';

const emit = defineEmits('getValue')
const list = categoryStore().category
const expandedKeys = ref<(string | number)[]>([]);
const searchValue = ref<string>('');
const autoExpandParent = ref<boolean>(true);
const dataList: any = ref([]);
const onExpand = (keys: string[]) => {
    expandedKeys.value = keys;
    autoExpandParent.value = false;

};
const onSelect = (keys: any, nodes: any) => {
    console.log(nodes, 33)
    console.log(nodes.node.key, 33)
    if (nodes.node.key.length > 1) {
        emit('getValue', {
            label: nodes.node.title,
            id: nodes.node.key
        })
    }

}
watch(searchValue, value => {
    const expanded = dataList.value
        .map((item: any) => {
            if (item.title.indexOf(value) > -1) {
                return getParentKey(item.key, list.value);
            }
            return null;
        })
        .filter((item, i, self) => item && self.indexOf(item) === i);
    expandedKeys.value = expanded;
    searchValue.value = value;
    autoExpandParent.value = true;
});

const getParentKey = (
    key: string | number,
    tree: any,
): string | number | undefined => {
    let parentKey;
    for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node.children) {
            if (node.children.some(item => item.key === key)) {
                parentKey = node.key;
            } else if (getParentKey(key, node.children)) {
                parentKey = getParentKey(key, node.children);
            }
        }
    }
    return parentKey;
};
</script>