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

<script setup>
import {ref, watch} from "vue";
import dataFillQuery from '~api/data-fill/query';
import {getArrValue, getObjValue} from "js-fast-way"
import {useAppStore} from "~src/store";

//参数
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);
const useAppState = useAppStore()
const contractInfo = ref(useAppState.getContractInfo);
const {contractType} = contractInfo.value;
const classifyType = ref(contractType === 2 ? '2' : '1')

//监听
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,
        classifyType: classifyType.value
    })
    const resData = getArrValue(data)
    if (resData.length > 0 && node.level === 0) {
        defaultExpandedArr.push(resData[0]?.primaryKeyId)
    }
    //自动展开
    defaultExpandedCids.value = defaultExpandedArr
    resolve(resData)
}

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

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