<template>
    <HcLazyTree ref="ElTreeRef"
                :autoExpandKeys="autoExpandKeys"
                :defaultCheckedKeys="defaultExpandedCids"
                :hProps="ElTreeProps"
                @load="ElTreeLoadNode"
                @nodeTap="ElTreeClick"
    />
</template>

<script setup>
import {ref, watch} from "vue";
import {getArrValue} from "js-fast-way"
import samplingApi from "~api/tentative/material/sampling";

//参数
const props = defineProps({
    projectId: [String, Number],
    contractId: [String, Number],
    wbsId: [String, Number],
    tenantId: [String, Number],
    wbsType: [String, Number],
    autoExpandKey: {
        type: Array,
        default: () => ([])
    },
})

//变量
const ElTreeRef = ref(null)
const ElTreeProps = ref({
    label: 'title',
    children: 'children',
    // isLeaf: 'hasChildren'
    isLeaf: function (data) {
          return !data.hasChildren;
    },
})

const projectId = ref(props.projectId);
const contractId = ref(props.contractId);

const wbsTempId = ref(props.wbsId)
const tenant_id = ref(props.tenantId)
const wbs_type = ref(props.wbsType)

const autoExpandKeys = ref(props.autoExpandKey)

//监听
watch(() => [
    props.projectId,
    props.contractId,
    props.wbsId,
    props.tenantId,
    props.wbsType,
    props.autoExpandKey,
], ([pid, cid, wbs_id, tid, type, keys]) => {
    projectId.value = pid
    contractId.value = cid
    wbsTempId.value = wbs_id
    tenant_id.value = tid
    wbs_type.value = type
    autoExpandKeys.value = keys
})

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

//树形结构异步加载数据
const defaultExpandedCids = ref([])
const ElTreeLoadNode = async ({node, item, level}, resolve) => {
    let parentId = '0';
    if (level !== 0) {
        parentId = item?.id
    }
    //获取数据
    const {data} = await samplingApi.queryLazyTree({
        wbsId: wbsTempId.value,
        tenantId: tenant_id.value,
        projectId: projectId.value,
        parentId,
        wbsType: wbs_type.value
    })
    resolve(getArrValue(data))
    emit('nodeLoading')
}

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