interface TreeItem {
  children: TreeItem[];
}

interface FilterTreeProps<T> {
  /** 数节点 */
  nodes: T[];
  /** 搜索关键字 */
  value: string;
  /** 要匹配的字段名 */
  key: string;
}

/**
 * 过滤树状结构，返回值仍然是一棵树
 */
export const filterTree = <T extends TreeItem>(data: FilterTreeProps<T>): T[] => {
  const { nodes, value, key } = data;
  if (!value) {
    return nodes;
  }
  return nodes.reduce((acc, node) => {
    const nodeMatches = node[key].includes(value);
    const filteredChildren = node.children ? filterTree({ nodes: node.children, value, key }) : [];

    if (nodeMatches || filteredChildren.length > 0) {
      acc.push({
        ...node,
        children: filteredChildren.length > 0 ? filteredChildren : nodeMatches ? node.children : [],
      });
    }
    return acc;
  }, [] as T[]);
};
