/**
 * 对选中的组件进行缩放
 * 如果操作的是group组件，递归缩放子元素
 *
 * @param projectStore 项目store
 * @param type 缩放类型
 * @param moveX x轴移动距离
 * @param moveY y轴移动距离
 * @param pathPrefix 路径前缀
 * @param elements 选中的组件
 * @param parentKey 父组件key
 * @returns void
 *
 */

import { CustomElement } from "#/project";

export const scaleAction = ({
  projectStore,
  type,
  moveX,
  moveY,
  pathPrefix = "",
  elements,
  parentKey,
}: {
  projectStore: any;
  type: string;
  moveX: number;
  moveY: number;
  elements: CustomElement[];
  pathPrefix?: string;
  parentKey?: string;
}) => {
  // 对选中的组件进行缩放
  elements.forEach((item, index) => {
    let { x, y, width, height } = item.container.props || {};

    switch (type) {
      case "top-left":
        width -= moveX;
        height -= moveY;
        if (!parentKey) {
          x += moveX;
          y += moveY;
        }
        break;
      case "top-center":
        height -= moveY;
        if (!parentKey) {
          y += moveY;
        }
        break;
      case "top-right":
        width += moveX;
        height -= moveY;
        if (!parentKey) {
          y += moveY;
        }
        break;
      case "left-center":
        width -= moveX;
        if (!parentKey) {
          x += moveX;
        }
        break;
      case "right-center":
        width += moveX;
        break;
      case "bottom-left":
        width -= moveX;
        height += moveY;
        if (!parentKey) {
          x += moveX;
        }
        break;
      case "bottom-center":
        height += moveY;
        break;
      case "bottom-right":
        width += moveX;
        height += moveY;
        break;
    }

    if (width < 10 || height < 10) return;

    const prefix = pathPrefix ? `${pathPrefix}[${index}].` : "";

    projectStore.updateElement(
      parentKey || item.key,
      prefix + "container.props.x",
      Math.round(x)
    );
    projectStore.updateElement(
      parentKey || item.key,
      prefix + "container.props.y",
      Math.round(y)
    );
    projectStore.updateElement(
      parentKey || item.key,
      prefix + "container.props.width",
      Math.round(width)
    );
    projectStore.updateElement(
      parentKey || item.key,
      prefix + "container.props.height",
      Math.round(height)
    );
    // 如果是group组件，递归缩放子元素
    if (item.componentType === "group") {
      scaleAction({
        projectStore,
        type,
        moveX,
        moveY,
        pathPrefix: `children`,
        elements: item.children || [],
        parentKey: item.key,
      });
    }
  });
};
