<template>
    <ElTree class="hc-tree-node tree-line" :props="ElTreeProps" :load="ElTreeLoadNode" lazy highlight-current accordion node-key="primaryKeyId"
            :default-expanded-keys="defaultExpandedCids" @node-click="ElTreeClick" :indent="0">
        <template #default="{ node, data }">
            <div class="data-custom-tree-node" :id="`${idPrefix}${data['primaryKeyId']}`">
                <div class="label" :class="node.level === 1?'level-name':''">{{ node.label }}</div>
            </div>
        </template>
    </ElTree>
</template>

<script setup>
import {ref,nextTick,watch} from "vue";
import firstApi from '~api/other/first-item';
import {isItem,getArrValue,getObjValue} from "vue-utils-plus"
//参数
const props = defineProps({
    projectId: {
        type: [String,Number],
        default: ''
    },
    contractId: {
        type: [String,Number],
        default: ''
    },
    autoExpandKeys: {
        type: Array,
        default: () => ([])
    },
    idPrefix: {
        type: String,
        default: 'first-tree-'
    },
    isAutoKeys: {
        type: Boolean,
        default: true
    },
    isAutoClick: {
        type: Boolean,
        default: true
    },
})

//变量
const ElTreeProps = ref({
    label: 'title',
    children: 'children',
    isLeaf: 'notExsitChild'
})

const isAutoKeys = ref(props.isAutoKeys)
const TreeExpandKey = ref(props.autoExpandKeys)
const projectId = ref(props.projectId);
const contractId = ref(props.contractId);

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

//树形结构异步加载数据
const defaultExpandedCids = ref([])
const ElTreeLoadNode = async (node, resolve) => {
    //获取数据
    const { contractIdRelation, primaryKeyId, id } = getObjValue(node?.data);
    const {error, code, data} = await firstApi.queryContractWbsTreeByFirstInfo({
        contractId: contractId.value || '',
        contractIdRelation: contractIdRelation || '',
        primaryKeyId: primaryKeyId || '',
        parentId: node.level !== 0 ? id : ''
    })
    //处理数据
    if (!error && code === 200) {
        let clickKey = '', defaultExpandedArr = [];
        const keys = TreeExpandKey.value || []
        const resData = getArrValue(data)
        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
        resolve(resData)
        //最后一个，执行点击
        if (props.isAutoClick && clickKey) {
            await nextTick(() => {
                document.getElementById(`${props.idPrefix}${clickKey}`)?.click()
            })
        }
    } else {
        resolve([])
    }
}

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

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

//处理自动展开的节点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 "../../../styles/app/tree.scss";
</style>
