import type { CategoryVO } from '@/api/warehouse/productCategory/types';

interface TreeNode extends CategoryVO {
  children?: TreeNode[];
}

/**
 * 构造树型结构数据
 * @param {Array} data 数据源
 * @param {string} id id字段 默认 'id'
 * @param {string} parentId 父节点字段 默认 'parentId'
 * @param {string} children 孩子节点字段 默认 'children'
 */
export const handleTree = (data: TreeNode[], id = 'id', parentId = 'parentId', children = 'children'): TreeNode[] => {
  const config = {
    id,
    parentId,
    children
  };

  const childrenListMap = new Map();
  const nodeIds = new Set();
  const tree: TreeNode[] = [];

  for (const item of data) {
    const pId = item[config.parentId];
    if (childrenListMap.has(pId)) {
      childrenListMap.get(pId).push(item);
    } else {
      childrenListMap.set(pId, [item]);
    }
    nodeIds.add(item[config.id]);
  }

  for (const item of data) {
    if (!nodeIds.has(item[config.parentId])) {
      tree.push(item);
    }
  }

  for (const [, children] of childrenListMap) {
    for (const node of children) {
      if (childrenListMap.has(node[config.id])) {
        node[config.children] = childrenListMap.get(node[config.id]);
      }
    }
  }

  return tree;
} 