/* eslint-disable import/prefer-default-export */
import { Tree, TreeNode } from '@sc/tree';

// 展开所有的树节点
export function expandAllTreeNode(treeData: TreeNode[]): void {
  treeData.forEach(item => {
    item.getCtx().expanded = true;
  });
}

// ElTree节点结构
export interface IElTreeNode {
  id: string;
  label: string;
  icon?: string;
  children?: IElTreeNode[];
}

// 获取其及其子项所有ELTree节点
const getElTreeData = (node: TreeNode): IElTreeNode => {
  const data: IElTreeNode = {
    id: node.ID,
    label: node.name,
  };
  const children = node.getCtx().children();
  if (children.length > 0) {
    const subNodes = [];
    for (const c of children) {
      subNodes.push(getElTreeData(c));
    }
    data.children = subNodes;
  }
  return data;
};

// 将@sc/tree里的树结构数据 转换 为el-tree里需要的树结构
export const toElTreeData = (tree: Tree): IElTreeNode[] => {
  const elTreeData: IElTreeNode[] = [];
  const roots = tree.getRoots();
  if (roots.length > 0) {
    roots.forEach(root => {
      elTreeData.push(getElTreeData(root));
    });
  }
  return elTreeData;
};

const setMap = (map: { [ID: string]: boolean }, node: TreeNode) => {
  if (node.getCtx().expanded === true) map[node.ID] = true;
  return map;
};

// 获取树展开收起的映射表
export const getExpandMap = (nodes: TreeNode[]) => {
  return nodes.reduce(setMap, {});
};
