import { cloneDeep, isEmpty } from "lodash";
import { nanoid } from "nanoid";
import { Background, ICompKeys, Layout } from "../../typings";
import { mapValuesDeep } from "@/utils";

export class DesignComp {
  // declare pid: string; // pid 作为前端临时数据，不存储到服务器，在初始化时关联
  declare $el: HTMLElement; // $el 映射dom
  id = nanoid();
  title = "";
  thumbnail = "";
  compKey: ICompKeys = "Text";
  value: any = undefined;
  layout: Layout = {size: [200, 200]};
  background: Background = {};
  children: Record<string, any> & { default?: string[] } = {};

  constructor(data?: Partial<DesignComp>) {
    if (!data) return;
    if (data instanceof DesignComp) return data;
    const fromData = Object.fromEntries(
      Object.entries(data).filter(
        ([, value]) => value !== null && value !== undefined
      )
    );
    Object.assign(this, cloneDeep(fromData));
  }

  getChildIds() {
    return mapValuesDeep(
      this.children,
      (v) => typeof v === "string",
      (v: string) => v
    );
  }

  isPostioned() {
    return this.layout.position === "absolute";
  }
  isTransformed() {
    return !isEmpty(this.layout.transform);
  }
  isFullWidth() {
    const w = this.layout.size?.[0];
    return !w || w === 750;
  }

  translate(x: number, y: number) {
    this.layout.transform || (this.layout.transform = {});
    x && (this.layout.transform.x = x);
    y && (this.layout.transform.y = y);
  }
  getW() {
    return this.layout.size?.[0] || 0;
  }
  getH() {
    return this.layout.size?.[1] || 0;
  }
  getBoundRect() {
    const out = {x:0, y: 0, w: 0, h:0}
    if (!this.$el) return out;
    const r= this.$el.getBoundingClientRect();
    out.w = r.width;
    out.h = r.height;
    out.x = r.left;
    out.y = r.top;
    return out;
 }

  setH(height: number) {
    if (!this.layout.size) this.layout.size = [];
    this.layout.size[1] = height;
  }
  setW(w: number) {
    if (!this.layout.size) this.layout.size = [];
    this.layout.size[0] = w;
  }
  setSize(w: number, h: number) {
    if (!this.layout.size) this.layout.size = [];

    this.layout.size[0] = w;
    this.layout.size[1] = h;
  }
}
