// 通过子节点找到整个树
export const getTreeIds = (
  tree: any[],
  nodeId: number,
  config?: { children: string; id: string },
) => {
  const { children = 'children', id = 'id' } = config || {};
  // 先拍平数组
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  const toFlatArray = (treeArr: any[], parentId?: any) => {
    return treeArr.reduce((t, _) => {
      const child = _[children];
      return [
        ...t,
        parentId ? { ..._, parentId } : _,
        ...(child && child.length ? toFlatArray(child, _[id]) : []),
      ];
    }, []);
  };
  // 找到所有的id
  const getIds = (flatArray: any[]) => {
    let ids = [nodeId];
    let child = flatArray.find((_) => _[id] === nodeId);
    while (child && child.parentId) {
      ids = [child.parentId, ...ids];
      // eslint-disable-next-line no-loop-func
      child = flatArray.find((_) => _[id] === child.parentId);
    }
    return ids;
  };
  // 返回找到的数据
  return getIds(toFlatArray(tree));
};
