<template>
  <div class="card-design">
    <!-- actions -->
    <div class="design-action">
      <div class="design-logo">
        <h1>
          <i class="el-icon-d-arrow-left" title="退出" @click="toExit"></i>
          答题卡制作
        </h1>
      </div>

      <div class="action-part">
        <div class="action-part-title"><h2>基本设置</h2></div>
        <div class="action-part-body">
          <page-prop-edit @init-page="initPageData"></page-prop-edit>
        </div>
      </div>
      <div class="action-part">
        <div class="action-part-title"><h2>插入元素</h2></div>
        <div class="action-part-body">
          <div class="type-list">
            <div
              v-for="(item, index) in ELEMENT_LIST"
              :key="index"
              class="type-item"
              draggable="true"
              @dragstart="dragstart(item)"
            >
              <el-button><i class="el-icon-plus"></i>{{ item.name }}</el-button>
            </div>
          </div>
          <p class="tips-info">提示：拖动插入元素</p>
        </div>
      </div>
    </div>

    <div class="design-main">
      <!-- menus -->
      <div class="design-control">
        <div class="control-left tab-btns">
          <el-button
            v-for="(page, pageNo) in pages"
            :key="pageNo"
            :type="curPageNo === pageNo ? 'primary' : 'default'"
            @click="swithPage(pageNo)"
            >第{{ pageNo + 1 }}页</el-button
          >
        </div>
        <div class="control-right">
          <el-button
            type="success"
            :loading="isSubmit"
            :disabled="!pages.length"
            @click="toPreview"
            >预览</el-button
          >
          <el-button
            v-if="showSaveBtn"
            type="primary"
            :loading="isSubmit"
            :disabled="canSave || !pages.length"
            @click="toSave"
            >暂存</el-button
          >
          <el-button type="primary" :loading="isSubmit" @click="toSubmit"
            >提交</el-button
          >
        </div>
      </div>

      <!-- edit body -->
      <div class="design-body">
        <div
          v-if="curPage.locators"
          :class="[
            'page-box',
            `page-box-${cardConfig.pageSize}`,
            `page-box-${curPageNo % 2}`,
          ]"
        >
          <!-- locator -->
          <div class="page-locator page-locator-top">
            <div
              v-for="elem in curPage.locators.top"
              :id="elem.id"
              :key="elem.id"
              class="page-locator-item"
            ></div>
          </div>
          <div class="page-locator page-locator-bottom">
            <div
              v-for="elem in curPage.locators.bottom"
              :id="elem.id"
              :key="elem.id"
              class="page-locator-item"
            ></div>
          </div>
          <!-- inner edit area -->
          <div class="page-main-inner">
            <div
              :class="['page-main', `page-main-${curPage.columns.length}`]"
              :style="{ margin: `0 -${curPage.columnGap / 2}px` }"
            >
              <div
                v-for="(column, columnNo) in curPage.columns"
                :key="columnNo"
                class="page-column"
                :style="{ padding: `0 ${curPage.columnGap / 2}px` }"
              >
                <div
                  :id="[`column-${curPageNo}-${columnNo}`]"
                  class="page-column-main"
                >
                  <div v-if="column.elements.length" class="page-column-body">
                    <topic-element-edit
                      v-for="element in column.elements"
                      :key="element.id"
                      class="page-column-element"
                      :data-h="element.h"
                      :data="element"
                    ></topic-element-edit>
                  </div>
                  <div v-else class="page-column-body">
                    <div
                      v-if="cardConfig.showForbidArea"
                      class="page-column-forbid-area"
                    >
                      <p>该区域严禁作答</p>
                    </div>
                  </div>
                </div>
                <page-number
                  type="text"
                  :total="pages.length * 2"
                  :current="curPageNo * 2 + columnNo + 1"
                ></page-number>
              </div>
            </div>
          </div>
          <!-- side edit erea -->
          <div class="page-main-side">
            <free-element-preview
              v-for="element in curPage.sides"
              :key="element.id"
              class="page-side-element"
              :data="element"
            ></free-element-preview>
          </div>
          <!-- outer edit area -->
          <div class="page-main-outer">
            <page-number
              type="rect"
              :total="pages.length"
              :current="curPageNo + 1"
            ></page-number>
          </div>
        </div>
      </div>
    </div>

    <!-- all topics -->
    <div class="topic-list">
      <div
        :class="['page-box', `page-box-${cardConfig.pageSize}`, 'page-box-0']"
      >
        <div class="page-main-inner">
          <div
            :class="['page-main', `page-main-${cardConfig.columnNumber}`]"
            :style="{ margin: `0 -${cardConfig.columnGap / 2}px` }"
          >
            <div
              class="page-column"
              :style="{ padding: `0 ${cardConfig.columnGap / 2}px` }"
            >
              <div id="topic-column" class="page-column-main">
                <div class="page-column-body">
                  <!-- topic element -->
                  <topic-element-preview
                    v-for="element in topics"
                    :key="element.id"
                    class="page-column-element"
                    :data="element"
                  ></topic-element-preview>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- element-prop-edit -->
    <element-prop-edit ref="ElementPropEdit"></element-prop-edit>
    <!-- right-click-menu -->
    <right-click-menu @inset-topic="insetNewTopic"></right-click-menu>
  </div>
</template>

<script>
import { mapState, mapMutations, mapActions } from "vuex";
import {
  getElementModel,
  getCardHeadModel,
  ELEMENT_LIST,
  TOPIC_LIST,
} from "../elementModel";
import { CARD_VERSION } from "../enumerate";
import TopicElementEdit from "./TopicElementEdit";
import TopicElementPreview from "./TopicElementPreview";
import FreeElementPreview from "./FreeElementPreview";
import PagePropEdit from "./PagePropEdit";
import ElementPropEdit from "./ElementPropEdit";
import RightClickMenu from "./RightClickMenu";
import PageNumber from "./PageNumber";
import { getPageInitElements } from "../pageModel";
// test auto build
import { buildCardFromPaperSimpleStruct } from "../autoBuild/simplePaperCard";

export default {
  name: "CardDesign",
  components: {
    TopicElementEdit,
    TopicElementPreview,
    FreeElementPreview,
    PagePropEdit,
    ElementPropEdit,
    RightClickMenu,
    PageNumber,
  },
  props: {
    content: {
      type: Object,
      default() {
        return {
          pages: [],
          cardConfig: {},
        };
      },
    },
    showSaveBtn: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      ELEMENT_LIST,
      TOPIC_LIST,
      topicList: [],
      columnWidth: 0,
      isSubmit: false,
      canSave: false,
    };
  },
  computed: {
    ...mapState("card", [
      "cardConfig",
      "paperSimpleStruct",
      "pageDefaultElems",
      "topics",
      "pages",
      "curElement",
      "curPage",
      "curPageNo",
    ]),
  },
  mounted() {
    this.initCard();
  },
  beforeDestroy() {
    this.initState();
  },
  methods: {
    ...mapMutations("card", [
      "addPage",
      "setCurPage",
      "setCurElement",
      "setCardConfig",
      "setOpenElementEditDialog",
      "setCurDragElement",
      "setPages",
      "setTopics",
      "setInsetTarget",
      "setPageDefaultElems",
      "initState",
      "setPaperSimpleStruct",
    ]),
    ...mapActions("card", [
      "resetTopicSeries",
      "removePage",
      "addElement",
      "modifyCardHead",
      "modifyElement",
      "rebuildPages",
      "initTopicsFromPages",
    ]),
    async initCard() {
      const { cardConfig, pages, paperSimpleStruct } = this.content;
      this.setCardConfig(cardConfig);
      this.setPaperSimpleStruct(paperSimpleStruct);
      const pageDefaultElems = getPageInitElements(cardConfig);
      this.setPageDefaultElems(pageDefaultElems);

      if (pages && pages.length) {
        this.setPages(pages);
        this.initTopicsFromPages();
        this.resetTopicSeries();
        this.setCurPage(0);
      } else {
        this.initPageData();
      }
      this.addWatch();
    },
    initPageData() {
      if (this.paperSimpleStruct) {
        const elementTypePreSetInfo = {
          FILL_QUESTION: {
            pageSize: this.cardConfig.pageSize,
            columnNumber: this.cardConfig.columnNumber,
          },
        };
        const elements = buildCardFromPaperSimpleStruct(
          this.paperSimpleStruct,
          elementTypePreSetInfo
        );
        this.setTopics([...this.pageDefaultElems.elements, ...elements]);
      }
      this.resetTopicSeries();
      this.$nextTick(() => {
        this.rebuildPages();
        this.setCurPage(0);
      });
    },
    addNewTopic(item) {
      let element = getElementModel(item.type);
      element.w = document.getElementById("topic-column").offsetWidth;

      this.setCurElement(element);
      this.$refs.ElementPropEdit.open();
      // to elementPropEdit/ElementPropEdit open topic edit dialog
    },
    insetNewTopic({ id, type }) {
      console.log(id, type);
      this.setInsetTarget({ id, type });
      if (type === "FILL_QUESTION") {
        this.topicList = this.TOPIC_LIST;
      } else {
        this.topicList = this.TOPIC_LIST.filter(
          (item) => item.type !== "FILL_QUESTION"
        );
      }
      this.$refs.TopicSelectDialog.open();
    },
    // 元件编辑
    dragstart(element) {
      this.setCurDragElement(getElementModel(element.type));
    },
    addWatch() {
      this.$watch("cardConfig", (val) => {
        const element = getCardHeadModel(val);
        this.modifyCardHead(element);
        this.$nextTick(() => {
          this.rebuildPages();
        });
      });
    },
    swithPage(pindex) {
      if (this.curPageNo === pindex) return;
      this.setCurPage(pindex);
      this.setCurElement({});
    },
    // save
    getCardData(model = "") {
      // title:暂时未使用
      const data = {
        title: this.cardConfig.cardTitle,
        pageSize: this.cardConfig.pageSize,
        content: model,
      };
      return data;
    },
    checkElementCovered() {
      let elements = [];
      this.pages.forEach((page) => {
        page.columns.forEach((column) => {
          column.elements.forEach((element) => {
            if (element.isCovered) {
              elements.push(element.id);
            }
          });
        });
      });
      return elements.length;
    },
    checkCardValid() {
      if (this.checkElementCovered()) {
        this.$message.error("题卡中存在被遮挡的元件，请注意调整！");
        return false;
      }

      return true;
    },
    getCardJson() {
      // 防止页面未渲染完成，各试题高度未及时更新，保存数据有误的问题
      return new Promise((resolve) => {
        setTimeout(() => {
          const data = JSON.stringify(
            {
              version: CARD_VERSION,
              cardType: "PAPER",
              cardConfig: this.cardConfig,
              paperSimpleStruct: this.paperSimpleStruct,
              pages: this.pages,
            },
            (k, v) => (k.startsWith("_") ? undefined : v)
          );
          resolve(data);
        }, 100);
      });
    },
    async toPreview() {
      if (this.isSubmit) return;
      this.isSubmit = true;
      const model = await this.getCardJson();
      const datas = this.getCardData(model);
      this.$emit("on-preview", datas);
    },
    async toSave() {
      if (!this.checkCardValid()) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      const model = await this.getCardJson();
      const datas = this.getCardData(model);
      this.$emit("on-save", datas);
    },
    toSubmit() {
      if (this.isSubmit) return;
      if (!this.checkCardValid()) return;

      this.$emit("on-submit", {
        cardConfig: this.cardConfig,
        pages: this.pages,
        paperSimpleStruct: this.paperSimpleStruct,
      });
    },
    toExit() {
      this.$emit("on-exit");
    },
    loading() {
      this.isSubmit = true;
    },
    unloading() {
      this.isSubmit = false;
    },
  },
};
</script>
