<template>
    <ElTree key="primaryKeyId" ref="ElTreeRef" :autoExpandKeys="autoExpandKeys"
            :default-expanded-keys="defaultExpandedCids"
            :indent="0"
            :load="ElTreeLoadNode" :props="ElTreeProps"
            accordion class="hc-tree-node tree-line"
            highlight-current lazy
            node-key="primaryKeyId" @node-click="ElTreeClick">
        <template #default="{ node, data }">
            <div :id="`test-tree-${data['primaryKeyId']}`" class="data-custom-tree-node">
                <!--树组件，节点名称-->
                <div :class="node.level === 1?'level-name':''" class="label">
                    <span>{{ node.label }}</span>
                </div>
            </div>
        </template>
    </ElTree>
</template>

<script setup>
import {ref, nextTick, watch} from "vue";
import {isItem, getArrValue} from "vue-utils-plus"
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'
})

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, resolve) => {
    let parentId = '0';
    if (node.level !== 0) {
        parentId = node?.data?.id
    }
    //获取数据
    const {error, code, data} = await samplingApi.queryLazyTree({
        wbsId: wbsTempId.value,
        tenantId: tenant_id.value,
        projectId: projectId.value,
        parentId,
        wbsType: wbs_type.value
    })
    //处理数据
    if (!error && code === 200) {
        let clickKey = '', defaultExpandedArr = [];
        const keys = autoExpandKeys.value || []
        const resData = getArrValue(data)
        for (let i = 0; i < resData.length; i++) {
            resData[i].hasChildren = !resData[i].hasChildren
        }
        if (keys.length > 0) {
            let lastKey = keys[keys.length - 1];
            for (const item of resData) {
                //自动展开
                if (isItem(keys, item?.primaryKeyId)) {
                    defaultExpandedArr.push(item?.primaryKeyId)
                }
                //最后一个，选中点击
                if (item?.primaryKeyId === lastKey) {
                    clickKey = item?.primaryKeyId
                }
            }
        } else if (node.level === 0) {
            defaultExpandedArr.push(resData[0]?.primaryKeyId)
        }
        //自动展开
        defaultExpandedCids.value = defaultExpandedArr
        if (node.level === 0) {
            emit('nodeLoading')
            if (resData.length <= 0) {
                window?.$message?.warning('该项目未使用试验系统，无法获取数据')
            }
        }
        resolve(resData)
        //最后一个，执行点击
        if (clickKey) {
            await nextTick(() => {
                document.getElementById(`test-tree-${clickKey}`)?.click()
            })
        }
    } else {
        if (node.level === 0) {
            emit('nodeLoading')
        }
        resolve([])
    }
}

//节点被点击
const ElTreeClick = async (data, node) => {
    let autoKeysArr = []
    await getNodeExpandKeys(node, autoKeysArr)
    const autoKeys = autoKeysArr.reverse()
    emit('nodeTap', {node, data, keys: autoKeys})
}

//处理自动展开的节点KEY
const getNodeExpandKeys = async (node, newKeys) => {
    const parent = node?.parent ?? []
    const primaryKeyId = node?.data?.primaryKeyId ?? ''
    if (primaryKeyId) {
        newKeys.push(primaryKeyId)
        await getNodeExpandKeys(parent, newKeys)
    }
}

</script>

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