import { TypeI5Tree } from '../I5organization/data'

export type I2AddInfoType = {
  id: string
  txt: '新增' | '编辑'
  acInfo: TypeI5Tree
}

// 通过id获取 树的obj
export const treeResIdFu = (list: any, id: string) => {
  // 每次进来使用find遍历一次
  let res = list.find((item: any) => item.id === id)

  if (res) {
    return res
  } else {
    for (let i = 0; i < list.length; i++) {
      if (list[i].children instanceof Array && list[i].children.length > 0) {
        res = treeResIdFu(list[i].children, id)

        if (res) return res
      }
    }

    return null
  }
}

// -------------------树结构的搜索过滤-------------------
export const filterTreeByName = (tree: TypeI5Tree[], searchTemp: string): TypeI5Tree[] => {
  const searchKey = searchTemp.toUpperCase()

  const dfs = (node: TypeI5Tree): TypeI5Tree | null => {
    // 先递归处理子节点（深度优先）
    const filteredChildren = (node.children?.map(dfs).filter(Boolean) as TypeI5Tree[]) || []

    // 判断当前节点是否匹配或子节点有匹配项

    const txt = node.name.toUpperCase() + (node.num || '').toUpperCase()

    const isSelfMatch = txt.includes(searchKey)

    // console.log('pppppppp', isSelfMatch, searchKey, node.num)

    const hasChildMatch = filteredChildren.length > 0

    if (isSelfMatch || hasChildMatch) {
      return {
        ...node,
        children: hasChildMatch ? filteredChildren : undefined
      }
    }
    return null
  }

  return tree.map(dfs).filter(Boolean) as TypeI5Tree[]
}
