import { Node } from '@vue-flow/core';

/**
 * 拓扑布局算法Hook
 * 提供网格、层次、环形三种布局方式
 */
export function useTopoLayout() {
  /**
   * 应用布局算法
   * @param nodes 当前节点列表
   * @param layoutType 布局类型
   * @returns 更新后的节点列表
   */
  const applyLayout = (
    nodes: Node[],
    layoutType: 'grid' | 'hierarchical' | 'circular'
  ): Node[] => {
    const nodesCopy = [...nodes];

    switch (layoutType) {
      case 'grid': {
        // 网格布局
        const cols = Math.ceil(Math.sqrt(nodesCopy.length));
        nodesCopy.forEach((node, idx) => {
          node.position = {
            x: (idx % cols) * 200 + 100,
            y: Math.floor(idx / cols) * 180 + 100,
          };
        });
        break;
      }

      case 'hierarchical': {
        // 层次布局
        const levels = new Map<number, Node[]>();

        // 按level分组
        nodesCopy.forEach((node) => {
          const level = (node.data?.level as number) || 0;
          if (!levels.has(level)) {
            levels.set(level, []);
          }
          levels.get(level)!.push(node);
        });

        // 按层级排列
        Array.from(levels.entries())
          .sort(([a], [b]) => a - b)
          .forEach(([level, levelNodes], levelIdx) => {
            const startX = (levelNodes.length - 1) * -150;
            levelNodes.forEach((node, nodeIdx) => {
              node.position = {
                x: startX + nodeIdx * 300 + 400,
                y: levelIdx * 200 + 100,
              };
            });
          });
        break;
      }

      case 'circular': {
        // 环形布局
        const radius = 300;
        const centerX = 400;
        const centerY = 300;
        const angleStep = (2 * Math.PI) / nodesCopy.length;

        nodesCopy.forEach((node, idx) => {
          const angle = idx * angleStep - Math.PI / 2;
          node.position = {
            x: centerX + radius * Math.cos(angle),
            y: centerY + radius * Math.sin(angle),
          };
        });
        break;
      }
    }

    return nodesCopy;
  };

  return { applyLayout };
}
