<template>
    <ElTree class="hc-tree-node tree-line" :props="ElTreeProps" :data="datas" highlight-current accordion node-key="id" :default-expanded-keys="TreeExpandKey" @node-click="ElTreeClick" :indent="0">
        <template #default="{ node, data }">
            <div class="data-custom-tree-node" :id="`${idPrefix}${data['id']}`">{{ 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: 'project-tree-data-'
    },
})

//变量
const ElTreeProps = ref({label: 'title', children: 'children'})
const TreeExpandKey = ref(props.autoExpandKeys)

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

nextTick(() => {
    setTreeNodeClick(props.autoExpandKeys)
})

//设置选中
const setTreeNodeClick = (keys) => {
    TreeExpandKey.value = keys
    if (keys.length > 0) {
        const byId = `${props.idPrefix}${keys[0]}`
        let timer = setInterval(() => {
            document.getElementById(byId)?.click()
            clearInterval(timer);
        }, 800);
    }
}

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

//节点被点击
const ElTreeClick = async (data,node) => {
    emit('nodeTap', {node, data, keys: [data?.id], key: data?.id})
}
</script>

<style lang="scss" scoped>
@import "../../../styles/app/tree.scss";
</style>
