<template>
    <ElTree
        :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="`${idPrefix}${data.primaryKeyId}`" class="data-custom-tree-node">
                <div :class="node.level === 1 ? 'level-name' : ''" class="label">
                    <span
                        v-if="(data.type > 0 && data.majorDataType > 0) || (data.type > 0 && data.majorDataType <= 0)"
                        class="hc-tree-node-type"
                    >{{
                        getTreeNodeType(data.type, data.majorDataType)
                    }}</span>
                    <span>{{ node.label }}</span>
                </div>
            </div>
        </template>
    </ElTree>
</template>

<script setup>
import { nextTick, ref, watch } from 'vue'
import { queryTreeList, queryTreeList1 } from '~api/ledger'
import { getTreeNodeType } from '~uti/utils'
import { getArrValue, getObjValue, isArrItem } from 'js-fast-way'
import { useAppStore } from '~src/store'
//参数
const props = defineProps({
    projectId: {
        type: [String, Number],
        default: '',
    },
    contractId: {
        type: [String, Number],
        default: '',
    },
    autoExpandKeys: {
        type: Array,
        default: () => ([]),
    },
    idPrefix: {
        type: String,
        default: 'wbs-tree-',
    },
    isAutoKeys: {
        type: Boolean,
        default: true,
    },
    isAutoClick: {
        type: Boolean,
        default: true,
    },
    classId:{
        type: [String, Number],
        default: '',
    },
})

//事件
const emit = defineEmits(['nodeTap'])
//变量
const ElTreeProps = ref({
    label: 'title',
    children: 'children',
    isLeaf: 'notExsitChild',
})
const useAppState = useAppStore()
const isAutoKeys = ref(props.isAutoKeys)
const TreeExpandKey = ref(props.autoExpandKeys)
const projectId = ref(props.projectId)
const contractId = ref(props.contractId)
const contractInfo = ref(useAppState.getContractInfo)
const classId = ref(props.classId)

//监听
watch(() => [
    props.isAutoKeys,
    props.autoExpandKeys,
    props.projectId,
    props.contractId,
    props.classId,
], ([AutoKeys, expandKeys, UserProjectId, UserContractId, ClassId]) => {
    isAutoKeys.value = AutoKeys
    TreeExpandKey.value = expandKeys
    projectId.value = UserProjectId
    contractId.value = UserContractId
    classId.value = ClassId
})
//获取合同段类型
const getContractTypeKey = () => {
    const { contractType } = contractInfo.value
    if (contractType === 2 || contractType === 3) {
        return '2' ?? '1'
    } else {
        return '1'
    }
}
//树形结构异步加载数据
const defaultExpandedCids = ref([])
const ElTreeLoadNode = async (node, resolve) => {
    let parentId = '', contractIdRelation = '', primaryKeyId = ''
    if (node.level !== 0) {
        const nodeData = getObjValue(node?.data)
        contractIdRelation = nodeData?.contractIdRelation ?? ''
        primaryKeyId = nodeData?.id ?? ''
        parentId = nodeData?.id ?? ''
    }
    //获取数据
    const classifyType = getContractTypeKey()
    console.log(classifyType, 'classifyType')
    const { error, code, data } = await queryTreeList1({
        contractId: contractId.value || '',
        contractIdRelation,
        primaryKeyId,
        parentId,
        classifyType: classifyType,
        classId:classId.value,
       
    })
    //处理数据
    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 (isArrItem(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 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>
