<template>
  <div class="paper-template-design card-design paper-page">
    <!-- 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 TOPIC_LIST"
              :key="index"
              class="type-item"
              @click="addNewTopic(item.type)"
            >
              <el-button><i class="el-icon-plus"></i>{{ item.name }}</el-button>
            </div>
          </div>
          <p class="tips-info">提示：点击创建编辑结构</p>
        </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)"
            >{{ PAGE_TYPE[page.pageType] }}</el-button
          >
        </div>
        <div class="control-right">
          <el-button
            type="success"
            :loading="isSubmit"
            :disabled="!pages.length"
            @click="toPreview"
            >预览</el-button
          >
          <el-button type="primary" :loading="isSubmit" @click="toSubmit"
            >提交</el-button
          >
        </div>
      </div>

      <!-- edit body -->
      <div class="design-body">
        <div
          v-if="curPage.id"
          :class="[
            'page-box',
            `page-box-${curPage.pageSize}`,
            `page-box-${pageTypeType(curPage.pageType)}`,
          ]"
        >
          <!-- inner edit area -->
          <div
            :class="[
              'page-main-inner',
              {
                'page-main-noside':
                  !curPage.showSide || curPage.pageType === 'cover',
              },
            ]"
          >
            <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 class="page-column-body">
                    <topic-element-edit
                      v-for="element in column.elements"
                      :key="element.key"
                      class="page-column-element"
                      :data-h="element.h"
                      :data="element"
                    ></topic-element-edit>
                  </div>
                </div>
                <page-number
                  v-if="curPage.showPageNo && curPage.pageType !== 'cover'"
                  type="text"
                  :total="getTotalPage()"
                  :current="getPageNumber(curPageNo, columnNo)"
                ></page-number>
              </div>
            </div>
          </div>
          <!-- side edit   -->
          <paper-side-edit
            v-if="curPage.showSide && curPage.pageType !== 'cover'"
            class="page-column-side"
            :data="curPage.sides"
          ></paper-side-edit>
        </div>
      </div>
    </div>

    <!-- all topics -->
    <div class="topic-list">
      <div :class="['page-box', `page-box-${curPage.pageSize}`, `page-box-0`]">
        <div
          :class="[
            'page-main-inner',
            { 'page-main-noside': !curPage.showSide },
          ]"
        >
          <div
            :class="['page-main', `page-main-${curPage.columnNumber}`]"
            :style="{ margin: `0 -${curPage.columnGap / 2}px` }"
          >
            <div
              class="page-column"
              :style="{ padding: `0 ${curPage.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.key"
                    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></right-click-menu>
  </div>
</template>

<script>
import { mapState, mapMutations, mapActions } from "vuex";
import {
  getElementModel,
  ELEMENT_LIST,
  TOPIC_LIST,
  PAGE_CONFIG,
} from "../elementModel";
import { getModel as getPageModel, PAGE_TYPE } from "../elements/page/model";

import PagePropEdit from "./PagePropEdit";
import ElementPropEdit from "./ElementPropEdit";
import RightClickMenu from "./RightClickMenu";
import PageNumber from "./PageNumber";
import TopicElementEdit from "./TopicElementEdit.vue";
import TopicElementPreview from "./TopicElementPreview.vue";
import PaperSideEdit from "./PaperSideEdit.vue";

export default {
  name: "PaperTemplateDesign",
  components: {
    PagePropEdit,
    ElementPropEdit,
    RightClickMenu,
    PageNumber,
    TopicElementEdit,
    TopicElementPreview,
    PaperSideEdit,
  },
  props: {
    content: {
      type: Object,
      default() {
        return {
          pages: [],
        };
      },
    },
  },
  data() {
    return {
      ELEMENT_LIST,
      TOPIC_LIST,
      PAGE_TYPE,
      isSubmit: false,
    };
  },
  computed: {
    ...mapState("paper-export", [
      "topics",
      "pageConfig",
      "pages",
      "curElement",
      "curPage",
      "curPageNo",
    ]),
  },
  mounted() {
    this.initCard();
  },
  beforeDestroy() {
    this.initState();
  },
  methods: {
    ...mapMutations("paper-export", [
      "addPage",
      "setCurElement",
      "setOpenElementEditDialog",
      "setCurDragElement",
      "setPages",
      "setPageConfig",
      "initState",
    ]),
    ...mapActions("paper-export", [
      "addElement",
      "modifyElement",
      "rebuildPages",
      "changePage",
    ]),
    pageTypeType(pageType) {
      const types = {
        cover: 0,
        front: 0,
        back: 1,
      };
      return types[pageType];
    },
    getPageNumber(curPageNo, columnNo) {
      let pageNo = this.pageConfig.showCover ? curPageNo - 1 : curPageNo;
      return pageNo * this.pageConfig.columnNumber + columnNo + 1;
    },
    getTotalPage() {
      let pageCount = this.pageConfig.showCover
        ? this.pages.length - 1
        : this.pages.length;
      return pageCount * this.pageConfig.columnNumber;
    },
    initCard() {
      let { pages, pageConfig } = this.content;
      if (!pageConfig) {
        pageConfig = { ...PAGE_CONFIG };
      }
      this.setPageConfig(pageConfig);

      if (pages && pages.length) {
        this.setPages(pages);
        this.changePage(0);
      } else {
        this.initPageData(pageConfig);
      }
    },
    initPageData() {
      let pages = [
        getPageModel({ ...this.pageConfig, pageType: "front" }),
        getPageModel({ ...this.pageConfig, pageType: "back" }),
      ];
      if (this.pageConfig.showCover) {
        pages.unshift(getPageModel({ ...this.pageConfig, pageType: "cover" }));
      }
      this.setPages(pages);
      this.changePage(0);
    },
    addNewTopic(type) {
      // if (type === 'PAGE')
      let element = getElementModel(type);
      element.w = document.getElementById("topic-column").offsetWidth;
      this.addElement(element);
      this.$nextTick(() => {
        this.rebuildPages();
      });
    },
    // 元件编辑
    dragstart(element) {
      this.setCurDragElement(getElementModel(element.type));
    },
    // 切换正反页
    swithPage(pindex) {
      if (this.curPageNo === pindex) return;
      this.setCurElement({});
      this.changePage(pindex);
    },
    getTemplateData() {
      return {
        pages: this.pages,
        pageConfig: this.pageConfig,
      };
    },
    getTemplateJson() {
      return new Promise((resolve) => {
        setTimeout(() => {
          const data = JSON.stringify(this.getTemplateData(), (k, v) =>
            k.startsWith("_") ? undefined : v
          );
          resolve(data);
        }, 100);
      });
    },
    toPreview() {
      if (this.isSubmit) return;
      this.$emit("on-preview", this.getTemplateData());
    },
    toSubmit() {
      if (this.isSubmit) return;
      this.$emit("on-submit", this.getTemplateData());
    },
    toExit() {
      this.$emit("on-exit");
    },
    loading() {
      this.isSubmit = true;
    },
    unloading() {
      this.isSubmit = false;
    },
  },
};
</script>
