<template>
 <el-radio-group :class="{'widthsize':ischeck}">
       <ElTree 
        ref="treeRef"
        class="hc-tree-node tree-line"  
        :class="ui" :props="ElTreeProps" 
        :data="datas" highlight-current  
        node-key="id" 
        :default-expanded-keys="TreeExpandKey" 
        @node-click="ElTreeClick" 
        @check-change="handleCheckChange"
         :show-checkbox="ischeck"
        :indent="0"
        check-strictly >
        <template #default="{ node, data }">
            <div class="data-custom-tree-node" :id="`${idPrefix}${data['id']}`">
                    <div class="label level-name" v-if="node.level === 1">   
                         <span>{{ node.label }}</span>
                    </div>
                    <div class="label " v-else>
                        <span>{{ node.label }}</span>
                    </div>
            </div>
        </template>
    </ElTree>
 </el-radio-group>
 
  
</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-'
    },
    ischeck:{
      type:Boolean,
      default:false  
    },
     ui: {
        type: String,
        default: ''
    },
})

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

//监听
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','ElTreeCheckChange'])


//节点被点击
const ElTreeClick = async (data,node) => {
    emit('nodeTap', {node, data, keys: [data?.id], key: data?.id})
}
//复选框被选中
const handleCheckChange = async (data,node) => {
      emit('checkChange', {node, data, keys:treeRef.value.getCheckedNodes(false), key: data?.id})
      console.log(treeRef.value.getCheckedNodes(false),'(treeRef.node')
}
</script>

<style lang="scss" scoped>
@import "../../../styles/app/tree.scss";
.widthsize{
    width: 100%;
}
.widthsize .el-tree.hc-tree-node{
    width: 100%;
}
</style>
