<template>
  <div class="topic-element-edit">
    <element-resize
      v-model="elemData"
      :class="{ 'element-resize-act': curElement.id === data.id }"
      :active="['b']"
      :move="false"
      :min-height="data.minHeight"
      :fit-parent="['h']"
      @on-click="activeCurElement"
      @resize-over="resizeOver"
      @change="sizeChange"
    >
      <div :id="data.id" :class="classes" :data-type="data.type">
        <component :is="compName" :data="data"></component>
      </div>
      <!-- topic-number -->
      <topic-number
        title="点击选中当前编辑框"
        @click="activeCurElement"
      ></topic-number>
    </element-resize>
  </div>
</template>

<script>
import { mapState, mapMutations, mapActions } from "vuex";
import { objAssign } from "../../card/plugins/utils";
import { checkElementisCovered } from "../store";

import EditPaneBox from "../elements/pane-box/ElemPaneBoxEdit.vue";
import EditPaperStruct from "../elements/paper-struct/ElemPaperStruct";

import ElementResize from "../../card/components/common/ElementResize";
import TopicNumber from "../../card/components/common/TopicNumber";

export default {
  name: "TopicElementEdit",
  components: {
    EditPaneBox,
    EditPaperStruct,
    ElementResize,
    TopicNumber,
  },
  props: {
    data: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      elemData: {
        x: 0,
        y: 0,
        w: 0,
        h: 0,
        init: false,
        isCovered: false,
      },
    };
  },
  computed: {
    ...mapState("paper-export", ["curElement"]),
    elementName() {
      return this.data.type.toLowerCase().replace("_", "-");
    },
    compName() {
      return `edit-${this.elementName}`;
    },
    classes() {
      return [
        "topic-design",
        "element-item",
        `element-item-${this.elementName}`,
        {
          "element-item-error": this.elemData.isCovered,
        },
      ];
    },
  },
  created() {
    this.init();
  },
  methods: {
    ...mapMutations("paper-export", ["setCurElement"]),
    ...mapActions("paper-export", ["modifyElement", "rebuildPages"]),
    init() {
      this.elemData = objAssign(this.elemData, this.data);
    },
    activeCurElement() {
      this.setCurElement(this.data);
    },
    sizeChange() {
      this.elemData.isCovered = checkElementisCovered(
        this.data.id,
        this.data.type
      );
      this.modifyElement(Object.assign({}, this.curElement, this.elemData));
    },
    resizeOver() {
      this.modifyElement(Object.assign({}, this.curElement, this.elemData));
      // 注意：当前组件并没有实时更新元件的尺寸信息，只是在rebuildPages时统一更新。
      this.$nextTick(() => {
        this.rebuildPages();
      });
    },
  },
};
</script>
