<template>
    <ElTree class="hc-tree-node" :props="ElTreeProps" :data="datas" highlight-current accordion node-key="hierarchy"
            :default-expanded-keys="TreeExpandKey" :current-node-key="currentNodeKey" @node-click="ElTreeClick">
        <template #default="{ node, data }">
            <div class="data-custom-tree-node" :id="`${idPrefix}${data['hierarchy']}`">{{ node.label }}</div>
        </template>
    </ElTree>
</template>

<script setup>
import {ref,watch,nextTick} from "vue";
const props = defineProps({
    datas: {
        type: Array,
        default: () => ([])
    },
    autoExpandKeys: {
        type: Array,
        default: () => ([])
    },
    idPrefix: {
        type: String,
        default: 'tree-data-'
    }
})

//变量
const ElTreeProps = ref({
    label: 'name',
    children: 'treeList'
})

const TreeExpandKey = ref(props.autoExpandKeys)

//监听
watch(() => [
    props.autoExpandKeys,
], ([expandKeys]) => {
    TreeExpandKey.value = expandKeys
    setTreeNodeClick()
})

nextTick(() => {
    setTreeNodeClick()
});

//设置选中
const currentNodeKey = ref('')
const setTreeNodeClick = () => {
    const keys = TreeExpandKey.value
    if (keys.length > 0) {
        currentNodeKey.value = keys[keys.length - 1]
    } else {
        currentNodeKey.value = ''
    }
}

//事件
const emit = defineEmits(['nodeTap'])

//节点被点击
const ElTreeClick = async (data,node) => {
    let autoKeysArr = []
    await getNodeExpandKeys(node, autoKeysArr)
    const autoKeys = autoKeysArr.reverse()
    const key = getNodeKeys(autoKeys)
    emit('nodeTap', {node, data, keys: autoKeys, key})
}

const getNodeKeys = (keys) => {
    if (keys.length > 0) {
        return keys[keys.length - 1]
    } else {
        return ''
    }
}

//处理自动展开的节点KEY
const getNodeExpandKeys = async (node, newKeys) => {
    const parent = node?.parent ?? []
    const hierarchy = node?.data?.hierarchy ?? ''
    if (hierarchy) {
        newKeys.push(hierarchy)
        await getNodeExpandKeys(parent, newKeys)
    }
}
</script>

<style lang="scss" scoped>
.data-custom-tree-node {
    position: relative;
    display: flex;
    align-items: center;
    width: 100%;
    color: var(--ui-TC);
}
</style>
