import { CompUI } from "@/modules/editor/components/CompUI";
import { addCacheToMap } from "@/modules/editor/components/CompUI/defines/createCompId";
import { set } from "lodash";
import { DesignComp } from "../DesignComp";

export function dataTransform(data: any) {
  data.compMap || (data.compMap = {});
  const compMap: Record<string, DesignComp> = data.compMap;

  // 遍历content中的每一个Comp, 包括Comp.children里的Comp
  deepEachComp(data.content, (paths, comp) => {
    set(data.content, paths.join("."), comp.id);
    compMap[comp.id] = comp;
    if (!comp.children) {
      comp.children = CompUI[comp.compKey].createComp({
        compKey: comp.compKey,
      }).children;
      addCacheToMap(compMap);
    }
  });

  if (!compMap.root) {
    compMap.root = CompUI.Page.createComp({
      id: "root",
      compKey: "Page",
      layout: data.pageStyle,
      children: {
        default: data.content,
      },
    });
  }

  return data;
}

function deepEachComp(
  obj: any,
  itemFn: (paths: string[], comp: DesignComp) => void,
  paths: string[] = []
) {
  if (isComp(obj)) {
    deepEachComp(obj.children, itemFn, [...paths, "children"]);
    itemFn(paths, obj);
  } else if (obj instanceof Array) {
    obj.forEach((item, i) =>
      deepEachComp(item, itemFn, [...paths, i.toString()])
    );
  } else if (obj instanceof Object) {
    Object.entries(obj).map(([key, item]) => {
      deepEachComp(item, itemFn, [...paths, key]);
    });
  }
}

function isComp(obj: any): obj is DesignComp {
  if (obj instanceof Object && obj.compKey) {
    return true;
  } else {
    return false;
  }
}
