import { TypeZ4Tree } from '../Z4organization/type'

// 树结构 通过最后一级id得到前面的id或者名称

export function treeLastIdFindFatherFu(
  tree: TypeZ4Tree[],
  targetId: string,
  returnType: 'id' | 'name'
): string[] {
  let pathNodes: TypeZ4Tree[] = []

  // 递归遍历函数
  const traverse = (nodes: TypeZ4Tree[], currentPath: TypeZ4Tree[]): boolean => {
    for (const node of nodes) {
      const newPath = [...currentPath, node]

      if (node.id === targetId) {
        pathNodes = newPath
        return true
      }

      if (node.children?.length) {
        const found = traverse(node.children, newPath)
        if (found) return true
      }
    }
    return false
  }

  traverse(tree, [])

  // 根据返回类型转换结果
  return returnType === 'id' ? pathNodes.map(n => n.id) : pathNodes.map(n => n.name)
}
