import { nextTick } from 'vue'
import { createLineTreeDecorators, type LineTreeDecorators } from './lineTreeUtils'

export { createLineTreeDecorators, type LineTreeDecorators }

export function findNodeById(nodes: any[], id: string): any | null {
    for (const node of nodes) {
        if (node.id === id) return node
        if (node.children?.length) {
            const found = findNodeById(node.children, id)
            if (found) return found
        }
    }
    return null
}

export async function waitForSingleTreeRef(treRef: any, maxRetries = 20) {
    for (let i = 0; i < maxRetries; i++) {
        await nextTick()
        if (treRef?.treeRef) return treRef.treeRef
        await new Promise(resolve => setTimeout(resolve, 50))
    }
    return null
}

export async function selectTreeNode(
    treRef: any,
    node: any | undefined,
    options?: { level?: number; onSelect?: (node: any) => void }
) {
    if (!node) return false
    const treeInstance = await waitForSingleTreeRef(treRef)
    if (!treeInstance) return false

    await nextTick()
    expandTreeNodePath(treeInstance, node.id)
    treeInstance.setCurrentKey(node.id)
    options?.onSelect?.(node)
    return true
}

/** 展开到目标节点的全部祖先，保证深层节点可见 */
export function expandTreeNodePath(treeInstance: any, nodeId: string) {
    const target = treeInstance.getNode?.(nodeId)
    if (!target) return

    let parent = target.parent
    while (parent && parent.level > 0) {
        parent.expanded = true
        parent = parent.parent
    }
}

export function bootstrapWithTemplate(
    template: boolean,
    loadFn: () => void,
    fetchTemplate: () => Promise<any>,
    onPolicy: (data: any) => void
) {
    if (template) {
        fetchTemplate()
            .then(res => {
                onPolicy(res.data)
                loadFn()
            })
            .catch(() => loadFn())
    } else {
        loadFn()
    }
}

export function mapUserTreeNodes(data: any[], icon = 'el-icon-User', color = 'royalblue') {
    return data.map(item => ({ ...item, icon, color }))
}
