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

function firstWalk(node: TopicItem): HierarchyResult {
  const root: HierarchyResult = {
    x: 0,
    y: 0,
    totalHeight: 0,
    totalWidth: 0,
    width: node.width,
    height: node.height,
    id: node.id,
    data: node,
    children: [],
  };

  root.children = node.children?.map((child) => firstWalk(child)) || [];

  return root;
}

// 设置宽高
function secondWalk(
  node: HierarchyResult,
  pageSetting: MindMapProjectInfo["pageSetting"]
) {
  let totalHeight = node.height;
  let totalWidth = 0;
  if (node.children?.length) {
    node.children.forEach((c: HierarchyResult, index) => {
      const childSize = secondWalk(c, pageSetting);
      const offsetY = node.data.type === TopicType.main ? pageSetting.branchY :  pageSetting.subTopicY;
      // 总的高度 = 自身高度 + 子节点的高度 + 节点之间的距离
      totalHeight += childSize.height + offsetY;
      
      const offsetX = index < node.children.length - 1 ? pageSetting.branchX : 0;
      totalWidth += childSize.width + offsetX;
    });
  }
  node.totalHeight = totalHeight;
  node.totalWidth =  Math.max(totalWidth, node.width);

  return {
    height: totalHeight,
    width: Math.max(totalWidth, node.width),
  };
}

function thirdWalk(node: HierarchyResult, pageSetting: MindMapProjectInfo['pageSetting']) {
  let startX = node.x + node.width / 2 - node.totalWidth / 2;
  // const offsetX = node.data.type === TopicType.main ? pageSetting.branchX : pageSetting.subTopicX;
  // const offsetY = node.data.type === TopicType.main ? pageSetting.branchY : pageSetting.subTopicY;
  node.children.forEach((child) => {
    child.y = node.y + node.height + pageSetting.branchY;
    if(node.children.length === 1) {
      child.x = startX + node.totalWidth / 2 - child.width / 2;
    } else {
      child.x = startX + child.totalWidth / 2 - child.width / 2;
    }
    startX += child.totalWidth + pageSetting.branchX;
    thirdWalk(child, pageSetting);
  });
}


export const getOrganization = <K>(
  topic: TopicItem,
  pageSetting: MindMapProjectInfo["pageSetting"]
): K => {
  const root = firstWalk(topic);
  secondWalk(root, pageSetting);
  thirdWalk(root, pageSetting);
  console.log(root);
  return root as K;
};
