import { TopicType } from "@/enum";
import { MindMapProjectInfo, TopicItem, HierarchyResult } from "@/types";

const DEFAULT_NODE_WIDTH = 100;
const DEFAULT_NODE_HEIGHT = 30;
const HORIZONTAL_SPACING = 50;
const VERTICAL_SPACING = 50;

function traverseHierarchy(
  node: TopicItem,
  x: number,
  y: number,
  direction: 'left' | 'right',
  depth: number = 0
): HierarchyResult {
  // 计算节点和子节点的尺寸及位置
  const width = node.fixedWidth ? node.width : DEFAULT_NODE_WIDTH;
  const height = node.fixedWidth ? node.height : DEFAULT_NODE_HEIGHT;

  let totalWidth = width;
  let totalHeight = height;
  let children: HierarchyResult[] = [];

  if (node.children && node.children.length > 0) {
    const childSpacing = (direction === 'left' ? -1 : 1) * (width / 2 + HORIZONTAL_SPACING);
    let currentY = y + height + VERTICAL_SPACING;

    children = node.children.map((childNode, index) => {
      const childX = x + childSpacing * (index + 1); // 根据方向和索引调整子节点的 x 坐标
      return traverseHierarchy(childNode, childX, currentY, direction, depth + 1);
    });

    // 计算子节点的总宽度和总高度
    totalWidth = Math.max(...children.map(child => child.totalWidth), width);
    totalHeight += VERTICAL_SPACING + children.map(child => child.totalHeight).reduce((a, b) => a + b, 0);
  }

  return {
    id: node.id,
    x,
    y,
    data: node,
    width,
    height,
    children,
    totalWidth,
    totalHeight
  };
}

export function getFishbone<T>(
  root: TopicItem,
  direction: 'left' | 'right' = 'left'
): T {
  return traverseHierarchy(root, 0, 0, direction) as T;
}
