<template>
  <div class="right-click-menu">
    <div
      v-if="visible"
      ref="RightMenuBody"
      v-clickoutside="close"
      class="right-menu-body"
      :style="styles"
    >
      <ul>
        <li @click="toEdit">
          <i class="el-icon-edit-outline"></i>
          {{ IS_CONTAINER_ELEMENT ? "编辑元素" : "编辑大题" }}
        </li>
        <li v-if="IS_CONTAINER_ELEMENT" class="li-danger" @click="toDelete">
          <i class="el-icon-delete"></i>删除元素
        </li>
        <li
          v-if="IS_CONTAINER_ELEMENT && IS_EXPLAIN"
          @click="toCopyExplainElement"
        >
          <i class="el-icon-copy-document"></i> 复制元素
        </li>
        <li v-if="IS_EXPLAIN && curCopyElement" @click="toPasteExplainElement">
          <i class="el-icon-document-copy"></i> 粘贴元素
        </li>
        <template v-if="IS_EXPLAIN">
          <li @click="toCopyChildren">
            <i class="el-icon-circle-plus-outline"></i> 新增答题区
          </li>
          <li
            v-if="showDeleteChildBtn"
            class="li-danger"
            @click="toDeleteChildren"
          >
            <i class="el-icon-delete"></i> 删除答题区
          </li>
        </template>
      </ul>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations, mapActions } from "vuex";
import { deepCopy } from "../plugins/utils";
import { fetchSameSerialNumberChildrenPositionInfo } from "../store/card";
import Clickoutside from "element-ui/src/utils/clickoutside";

export default {
  name: "RightClickMenu",
  directives: { Clickoutside },
  data() {
    return {
      visible: false,
      showDeleteChildBtn: false,
      curCopyElement: null,
      styles: {
        position: "fixed",
        zIndex: 3000,
      },
    };
  },
  computed: {
    ...mapState("card", ["curElement", "topics"]),
    IS_CONTAINER_ELEMENT() {
      return !!this.curElement.container;
    },
    IS_EXPLAIN() {
      return (
        this.curElement.type === "EXPLAIN" ||
        (this.curElement.container &&
          this.curElement.container.type === "EXPLAIN")
      );
    },
  },
  mounted() {
    this.init();
  },
  beforeDestroy() {
    document.oncontextmenu = null;
    document.removeEventListener("mouseup", this.docMouseUp);
  },
  methods: {
    ...mapMutations("card", ["setOpenElementEditDialog"]),
    ...mapActions("card", [
      "actElementById",
      "removeElement",
      "removeElementChild",
      "pasteExplainElementChild",
      "rebuildPages",
      "copyExplainChildren",
      "deleteExplainChildren",
      "topicMoveUp",
    ]),
    init() {
      // 注册自定义右键事件菜单
      document.oncontextmenu = function () {
        return false;
      };
      document.addEventListener("mouseup", this.docMouseUp);
    },
    close() {
      this.visible = false;
    },
    show() {
      this.visible = true;
    },
    docMouseUp(e) {
      if (e.button === 2) {
        this.rightClick(e);
      }
    },
    rightClick(e) {
      const id = this.getRelateElementId(e.target);
      if (!id) return;

      this.actElementById(id);
      let curElement = this.curElement;
      const TYPES = ["EXPLAIN", "COMPOSITION"];
      if (
        TYPES.includes(curElement.type) ||
        (curElement.container && TYPES.includes(curElement.container.type))
      ) {
        if (curElement.container) {
          const pos = this.topics.findIndex(
            (item) => item.id === curElement.container.id
          );
          curElement = this.topics[pos];
        }
        const positionInfos = fetchSameSerialNumberChildrenPositionInfo(
          curElement,
          this.topics
        );
        this.showDeleteChildBtn = positionInfos.length >= 2;
      }
      this.show();

      this.$nextTick(() => {
        const { x: clickLeft, y: clickTop } = e;
        const { offsetWidth: menuWidth, offsetHeight: menuHeight } =
          this.$refs.RightMenuBody;

        const { innerWidth: wWidth, innerHeight: wHeight } = window;

        let menuLeft = clickLeft,
          menuTop = clickTop;
        if (menuWidth + clickLeft > wWidth) {
          menuLeft = clickLeft - menuWidth;
        }
        if (menuHeight + clickTop > wHeight) {
          menuTop = clickTop - menuHeight;
        }

        this.styles = Object.assign({}, this.styles, {
          top: menuTop + "px",
          left: menuLeft + "px",
        });
      });
    },
    getRelateElementId(dom) {
      let parentNode = dom;
      while (
        !(
          (parentNode["id"] && parentNode["id"].includes("element-")) ||
          parentNode.className.includes("page-column-body") ||
          parentNode.className.includes("card-design")
        )
      ) {
        parentNode = parentNode.parentNode;
      }
      const elementType = parentNode.getAttribute("data-type");
      const unValidElement = ["TOPIC_HEAD", "CARD_HEAD"];

      return parentNode["id"] &&
        elementType &&
        !unValidElement.includes(elementType)
        ? parentNode["id"]
        : null;
    },
    toEdit() {
      this.curElement._edit = true;
      this.close();
      this.setOpenElementEditDialog(true);
    },
    toDelete() {
      this.close();
      this.$confirm("确定要删除当前元素吗?", "提示", {
        type: "warning",
      })
        .then(() => {
          this.removeSelectElement();
        })
        .catch(() => {});
    },
    toCopyChildren() {
      this.close();
      this.copyExplainChildren(this.curElement);
      this.toRebuildPages();
    },
    toDeleteChildren() {
      this.close();
      this.deleteExplainChildren(this.curElement);
      this.toRebuildPages();
    },
    removeSelectElement() {
      if (!this.curElement["container"]) return;
      this.removeElementChild(this.curElement);
      this.toRebuildPages();
    },
    toCopyExplainElement() {
      this.close();
      this.curCopyElement = deepCopy(this.curElement);
    },
    toPasteExplainElement() {
      this.close();
      const id = this.curElement.container
        ? this.curElement.container.id
        : this.curElement.id;
      const pasteElement =
        this.curCopyElement.container.id === id
          ? Object.assign({}, this.curCopyElement, {
              y: this.curCopyElement.y + 20,
            })
          : this.curCopyElement;

      this.pasteExplainElementChild({
        curElement: this.curElement,
        pasteElement,
      });
      this.toRebuildPages();
    },
    toMoveUpTopic() {
      this.close();
      this.topicMoveUp(this.curElement.parent.id);
      this.toRebuildPages();
    },
    toMoveDownTopic() {
      this.close();
      const curTopicPos = this.topicSeries.findIndex(
        (item) => item.id === this.curElement.parent.id
      );
      this.topicMoveUp(this.topicSeries[curTopicPos + 1].id);
      this.toRebuildPages();
    },
    toInsetTopic() {
      this.close();
      this.$emit("inset-topic", {
        id: this.curElement.parent.id,
        type: this.curElement.type,
      });
    },
    toRebuildPages() {
      this.$nextTick(() => {
        this.rebuildPages();
      });
    },
  },
};
</script>
