<template>
    <ElTree class="hc-tree-node tree-line" :class="ui" ref="ElTreeRef" :props="ElTreeProps" :load="ElTreeLoadNode" lazy show-checkbox accordion node-key="primaryKeyId"
            :default-expanded-keys="defaultExpandedCids" :indent="0" @check-change="ElTreeCheckChange">
    </ElTree>
</template>

<script setup>
import {ref,watch} from "vue";
import dataFillQuery from '~api/data-fill/query';
import {getArrValue,getObjValue} from "vue-utils-plus"

//参数
const props = defineProps({
    projectId: {
        type: [String,Number],
        default: ''
    },
    contractId: {
        type: [String,Number],
        default: ''
    },
    ui: {
        type: String,
        default: ''
    },
})

//变量
const ElTreeRef = ref(null)
const ElTreeProps = ref({
    label: 'title',
    children: 'children',
    isLeaf: 'notExsitChild'
})
const projectId = ref(props.projectId);
const contractId = ref(props.contractId);

//监听
watch(() => [
    props.projectId,
    props.contractId
], ([UserProjectId, UserContractId]) => {
    projectId.value = UserProjectId
    contractId.value = UserContractId
})

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

//树形结构异步加载数据
const defaultExpandedCids = ref([])
const ElTreeLoadNode = async (node, resolve) => {
    let defaultExpandedArr = [];
    let contractIdRelation = '', parentId = '', primaryKeyId = '';
    if (node.level !== 0) {
        const nodeData = getObjValue(node?.data);
        contractIdRelation = nodeData?.contractIdRelation || ''
        parentId = contractIdRelation ? nodeData?.primaryKeyId : nodeData?.id
        primaryKeyId = nodeData?.id || ''
    }
    //获取数据
    const { data } = await dataFillQuery.queryWbsTreeData({
        contractId: contractId.value || '',
        contractIdRelation,
        primaryKeyId,
        parentId
    })
    const resData = getArrValue(data)
    if (resData.length > 0 && node.level === 0) {
        defaultExpandedArr.push(resData[0]?.primaryKeyId)
    }
    //自动展开
    defaultExpandedCids.value = defaultExpandedArr
    resolve(resData)
}

//节点勾选
const ElTreeCheckChange = (data, checked, indeterminate) => {
    emit('change', {data, checked, indeterminate})
}
</script>

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