<template>
  <el-dialog
    class="element-prop-edit edit-dialog"
    :visible.sync="openElementEditDialog"
    :title="title"
    top="10vh"
    width="640px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :before-close="cancel"
    append-to-body
    destroy-on-close
  >
    <component
      :is="curEditComponent"
      ref="ElementPropEditComp"
      :key="curElement.id"
      :instance="curElement"
      @modified="modified"
    ></component>

    <div slot="footer">
      <el-button type="primary" :disabled="loading" @click="submit"
        >确认</el-button
      >
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { mapState, mapMutations, mapActions } from "vuex";
import { getElementName } from "../elementModel";
import EditComposition from "../elements/composition/EditComposition";
import EditExplain from "../elements/explain/EditExplain";
import EditFillLine from "../elements/fill-line/EditFillLine";
import EditFillQuestion from "../elements/fill-question/EditFillQuestion";
import EditText from "../elements/text/EditText";
import EditImage from "../elements/image/EditImage";
import EditLine from "../elements/line/EditLine";
import EditLines from "../elements/lines/EditLines";
import EditGrids from "../elements/grids/EditGrids";

export default {
  name: "ElementPropEdit",
  components: {
    EditComposition,
    EditExplain,
    EditFillLine,
    EditFillQuestion,
    EditText,
    EditImage,
    EditLine,
    EditLines,
    EditGrids,
  },
  data() {
    return { loading: false };
  },
  computed: {
    ...mapState("card", ["curElement", "openElementEditDialog"]),
    title() {
      return this.curElement.type
        ? getElementName(this.curElement.type)
        : "属性编辑";
    },
    curEditComponent() {
      if (!this.curElement.type) return;
      let type = this.curElement.type.toLowerCase().replace("_", "-");
      if (type.indexOf("line-") === 0) type = "line";
      return `edit-${type}`;
    },
  },
  methods: {
    ...mapMutations("card", ["setOpenElementEditDialog"]),
    ...mapActions("card", [
      "addElement",
      "modifyElement",
      "modifyElementChild",
      "rebuildPages",
    ]),
    cancel() {
      this.setOpenElementEditDialog(false);
    },
    open() {
      this.setOpenElementEditDialog(true);
    },
    submit() {
      if (this.loading) return;
      this.loading = true;
      setTimeout(() => {
        this.loading = false;
      }, 500);
      this.$refs.ElementPropEditComp.submit();
    },
    modified(element) {
      this.cancel();
      // 编辑试题
      // 属性存在的条件：parent:大题的小题，container:题目内的子元素
      if (this.curElement["_edit"]) {
        if (element["container"]) {
          this.modifyElementChild(element);
        } else {
          this.modifyElement(element);
        }
      } else {
        this.addElement(element);
      }
      this.$nextTick(() => {
        this.rebuildPages();
      });
    },
  },
};
</script>
