<template>
  <div
    class="paper-side-edit"
    @drop.prevent="dropInnerElement($event)"
    @dragover.prevent
    @dragleave.prevent
  >
    <div class="column-side-body">
      <box-element-edit
        v-for="element in data"
        :key="element.key"
        :data="element"
        @resize-over="elementResizeOver"
      ></box-element-edit>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions, mapMutations } from "vuex";
import BoxElementEdit from "./BoxElementEdit";

const defaultProp = {
  FILL_FIELD: {
    mode: "side",
    w: 40,
    h: 400,
  },
  TEXT: {
    mode: "side",
    h: 100,
  },
};

export default {
  name: "PaperSideEdit",
  components: { BoxElementEdit },
  props: {
    data: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    return {};
  },
  computed: {
    ...mapState("paper-export", ["curDragElement"]),
  },
  methods: {
    ...mapMutations("paper-export", ["setCurDragElement"]),
    ...mapActions("paper-export", ["addSideElement", "modifySideElement"]),
    dropInnerElement(e) {
      let { offsetY: y } = e;
      const { offsetTop } = this.getOffsetInfo(e.target || e.srcElement);
      const maxWidth = this.$el.offsetWidth;

      let curElement = {
        ...this.curDragElement,
        x: 0,
        y: y + offsetTop,
        w: Math.min(this.curDragElement.w, maxWidth),
      };
      curElement = Object.assign(
        curElement,
        defaultProp[this.curDragElement.type] || {}
      );

      this.setCurDragElement({});
      this.addSideElement(curElement);
    },
    getOffsetInfo(dom, endParentClass = "paper-side-edit") {
      let parentNode = dom;
      let offsetTop = 0,
        offsetLeft = 0;
      while (!parentNode.className.includes(endParentClass)) {
        offsetTop += parentNode.offsetTop;
        offsetLeft += parentNode.offsetLeft;
        parentNode = parentNode.offsetParent;
      }
      return {
        offsetLeft,
        offsetTop,
      };
    },
    elementResizeOver(element) {
      this.modifySideElement(element);
    },
  },
};
</script>
