<template>
  <div class="card-design">
    <div class="design-top">
      <div class="design-top-logo">
        <h1><i class="icon icon-back" @click="goback"></i>答题卡制作</h1>
      </div>
      <div class="design-top-info">
        <div class="info-help"><i class="icon icon-help"></i>帮助</div>
      </div>
    </div>

    <div class="design-main">
      <!-- menus -->
      <div class="design-head">
        <div class="design-steps">
          <div class="step-item" v-for="(step, index) in steps" :key="index">
            <i>{{ index + 1 }}</i>
            <span>{{ step }}</span>
          </div>
        </div>
        <div class="design-control">
          <div class="control-right">
            <el-button
              class="btn-white"
              @click="toPreview"
              :disabled="!pages.length"
              >预览</el-button
            >
            <save-page @confirm="toSave" ref="SavePage"></save-page>
            <el-button type="primary" @click="toSubmit">提交</el-button>
          </div>
          <div class="control-left">
            <el-button
              v-for="(page, pageNo) in pages"
              :key="pageNo"
              :class="{ 'btn-white': curPageNo === pageNo }"
              @click="swithPage(pageNo)"
              >第{{ pageNo + 1 }}页</el-button
            >
          </div>
        </div>
      </div>

      <!-- actions -->
      <div class="design-action">
        <div class="action-part">
          <div class="action-part-title"><h2>基本设置</h2></div>
          <div class="action-part-body">
            <page-prop-edit></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
                class="type-item"
                v-for="(item, index) in TOPIC_LIST"
                :key="index"
              >
                <el-button @click="addNewTopic(item)"
                  ><i class="el-icon-plus"></i>{{ item.name }}</el-button
                >
              </div>
            </div>
          </div>
        </div>
        <div class="action-part">
          <div class="action-part-title"><h2>插入元素</h2></div>
          <div class="action-part-body">
            <div class="type-list">
              <div
                class="type-item"
                v-for="(item, index) in ELEMENT_LIST"
                :key="index"
                draggable="true"
                @dragstart="dragstart(item)"
              >
                <el-button
                  ><i class="el-icon-plus"></i>{{ item.name }}</el-button
                >
              </div>
            </div>
          </div>
          <!-- Develop btns -->
          <!-- <card-config-prop-edit></card-config-prop-edit>
          <br /><br />
          <el-button @click="initCard">新建页面</el-button> -->
        </div>
      </div>

      <!-- edit body -->
      <div class="design-body">
        <template v-for="(page, pageNo) in pages">
          <div
            :class="['page-box', `page-box-${pageNo % 2}`]"
            v-if="curPageNo === pageNo"
            :key="pageNo"
          >
            <div
              :class="[
                'page-locators',
                `page-locators-${page.locators.length}`
              ]"
            >
              <ul
                class="page-locator-group"
                v-for="(locator, iind) in page.locators"
                :key="iind"
              >
                <li
                  v-for="(elem, eindex) in locator"
                  :key="eindex"
                  :id="elem.id"
                ></li>
              </ul>
            </div>
            <!-- inner edit area -->
            <div class="page-main-inner">
              <div
                :class="['page-main', `page-main-${page.columns.length}`]"
                :style="{ margin: `0 -${page.columnGap / 2}px` }"
              >
                <div
                  class="page-column"
                  v-for="(column, columnNo) in page.columns"
                  :key="columnNo"
                  :style="{ padding: `0 ${page.columnGap / 2}px` }"
                >
                  <div
                    class="page-column-main"
                    :id="[`column-${pageNo}-${columnNo}`]"
                  >
                    <div class="page-column-body" v-if="column.elements.length">
                      <topic-element-edit
                        class="page-column-element"
                        v-for="element in column.elements"
                        :key="element.id"
                        :data="element"
                      ></topic-element-edit>
                    </div>
                    <div class="page-column-body" v-else>
                      <div
                        class="page-column-forbid-area"
                        v-if="cardConfig.showForbidArea"
                      >
                        <p>该区域严禁作答</p>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <!-- outer edit area -->
            <div class="page-main-outer"></div>
          </div>
        </template>
      </div>

      <!-- design other pages -->
      <div class="design-other-pages">
        <template v-for="(page, pageNo) in pages">
          <div
            :class="['page-box', `page-box-${pageNo % 2}`]"
            v-if="curPageNo !== pageNo"
            :key="pageNo"
          >
            <div
              :class="[
                'page-locators',
                `page-locators-${page.locators.length}`
              ]"
            >
              <ul
                class="page-locator-group"
                v-for="(locator, iind) in page.locators"
                :key="iind"
              >
                <li
                  v-for="(elem, eindex) in locator"
                  :key="eindex"
                  :id="elem.id"
                ></li>
              </ul>
            </div>
            <!-- inner edit area -->
            <div class="page-main-inner">
              <div
                :class="['page-main', `page-main-${page.columns.length}`]"
                :style="{ margin: `0 -${page.columnGap / 2}px` }"
              >
                <div
                  class="page-column"
                  v-for="(column, columnNo) in page.columns"
                  :key="columnNo"
                  :style="{ padding: `0 ${page.columnGap / 2}px` }"
                >
                  <div
                    class="page-column-main"
                    :id="[`column-${pageNo}-${columnNo}`]"
                  >
                    <div class="page-column-body">
                      <topic-element-edit
                        class="page-column-element"
                        v-for="(element, eindex) in column.elements"
                        :key="eindex"
                        :data="element"
                      ></topic-element-edit>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </template>
      </div>
    </div>

    <!-- element-prop-edit -->
    <element-prop-edit></element-prop-edit>
    <!-- right-click-menu -->
    <right-click-menu></right-click-menu>
    <!-- card-head-sample -->
    <card-head-sample v-if="pages.length"></card-head-sample>
    <!-- card-view-frame -->
    <div class="design-preview-frame" v-if="cardPreviewUrl">
      <iframe :src="cardPreviewUrl" frameborder="0"></iframe>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations, mapActions } from "vuex";
import {
  cardConfigInfos,
  cardDetailEdit,
  cardTempDetail,
  saveCard,
  submitCard
} from "../api";
import { saveWaitTask } from "@/modules/exam-center/api";
import {
  getElementModel,
  getCardHeadModel,
  getNewPage,
  getTopicModel,
  ELEMENT_LIST,
  TOPIC_LIST
} from "../elementModel";
import { transformField, getAOrBSystem } from "../enumerate";
import TopicElementEdit from "../components/TopicElementEdit";
import PagePropEdit from "../components/PagePropEdit";
// import CardConfigPropEdit from "../components/CardConfigPropEdit";
import ElementPropEdit from "../components/elementPropEdit/ElementPropEdit";
import RightClickMenu from "../components/RightClickMenu";
import CardHeadSample from "../components/elementEdit/CardHeadSample";
import SavePage from "../components/SavePage";

export default {
  name: "card-design",
  components: {
    TopicElementEdit,
    PagePropEdit,
    // CardConfigPropEdit,
    ElementPropEdit,
    RightClickMenu,
    CardHeadSample,
    SavePage
  },
  data() {
    return {
      cardId: this.$route.params.cardId,
      cardDetailId: this.$ls.get("cardDetailId"),
      prepareTcPCard: this.$ls.get("prepareTcPCard", {}),
      ELEMENT_LIST,
      TOPIC_LIST,
      steps: ["添加标题", "基本设置", "试题配置", "试题配置"],
      columnWidth: 0,
      cardPreviewUrl: ""
    };
  },
  computed: {
    ...mapState("card", ["cardConfig", "pages", "curElement", "curPageNo"]),
    isEdit() {
      return !!this.cardId;
    }
  },
  mounted() {
    this.initCard();
    this.registWindowSubmit();
  },
  methods: {
    ...mapMutations("card", [
      "addPage",
      "setCurPageNo",
      "setCurElement",
      "setCardConfig",
      "setOpenElementEditDialog",
      "setCurDragElement",
      "setPages",
      "initState"
    ]),
    ...mapActions("card", [
      "removePage",
      "addElement",
      "modifyCardHead",
      "modifyElement",
      "rebuildPages"
    ]),
    async initCard() {
      await this.getCardConfig();
      if (this.isEdit) {
        this.getCardTempDetail();
      } else {
        this.initPageData();
      }
      this.addWatch();
    },
    async getCardTempDetail() {
      const detData = await cardDetailEdit(this.cardId);
      const tempData = await cardTempDetail(this.cardId);
      this.prepareTcPCard = Object.assign(this.prepareTcPCard, detData);

      // 可能存在题卡内容没有记录的情况
      if (tempData) {
        const cont = JSON.parse(tempData.content);
        this.cardDetailId = tempData.id;
        this.setPages(cont.pages);
        this.setCardConfig(cont.cardConfig);
      } else {
        // 没有题卡内容时，直接创建新的内容
        this.initPageData();
      }
    },
    initPageData() {
      this.addNewPage();
      this.addNewPage();

      this.$nextTick(() => {
        this.modifyCardHead({
          ...getCardHeadModel(this.cardConfig)
        });
      });
    },
    async getCardConfig() {
      const data = await cardConfigInfos();
      const aOrBSystem = getAOrBSystem(this.prepareTcPCard);
      let config = {
        ...transformField(data),
        pageSize: "A3",
        columnNumber: 2,
        columnGap: 20,
        showForbidArea: true,
        cardName: ""
      };
      if (aOrBSystem !== null) config.aOrBSystem = aOrBSystem;
      config.aOrB = !!config["aOrBSystem"];

      this.setCardConfig(config);
    },
    addNewTopic(item) {
      let element = getTopicModel(item.type);
      element.w = document.getElementById("column-0-0").offsetWidth;
      this.setCurElement(element);
      this.setOpenElementEditDialog(true);
      // to elementPropEdit/ElementPropEdit open topic edit dialog
    },
    addNewPage() {
      const page = getNewPage(this.pages.length, this.cardConfig.columnNumber);
      this.addPage(page);
    },
    // 元件编辑
    dragstart(element) {
      this.setCurDragElement(getElementModel(element.type));
    },
    addWatch() {
      this.$watch("cardConfig", val => {
        const element = getCardHeadModel(val);
        this.modifyCardHead(element);
        this.$nextTick(() => {
          this.rebuildPages();
        });
      });
    },
    // 操作
    async toPreview() {
      await this.toSave(this.$refs.SavePage.getPageModel());
      window.open(`/#/card/preview/${this.cardId}/view`);
    },
    swithPage(pindex) {
      if (this.curPageNo === pindex) return;
      this.setCurPageNo(pindex);
      this.setCurElement({});
    },
    // save
    getCardData(contentTemp = "") {
      const tcPCard = this.$objAssign(
        {
          examId: "",
          enablePaperType: "A",
          paperAttachmentId: "",
          courseName: "",
          courseCode: "",
          cardSource: "",
          title: ""
        },
        {
          ...this.prepareTcPCard,
          title: this.cardConfig.cardName,
          // todo:A,B最好前端配置一下，以便支持扩展
          enablePaperType: this.cardConfig.aOrB ? "A,B" : "A"
        }
      );

      let data = {
        tcPCard,
        tcPCardDetail: {
          content: this.$refs.SavePage.getPageModel()
        }
      };
      if (this.cardDetailId) data.tcPCardDetail.id = this.cardDetailId;
      if (contentTemp) data.tcPCardDetail.contentTemp = contentTemp;
      return data;
    },
    async save() {
      if (!this.cardConfig.cardName) {
        this.$message.error("题卡标题不能为空！");
        return Promise.reject("error:题卡标题不能为空");
      }
      const result = await saveCard(this.getCardData());
      this.cardDetailId = result.cardDetailId;
      this.$ls.set("cardDetailId", this.cardDetailId);
      this.cardId = result.cardId;
    },
    async toSave() {
      await this.save();
      this.$message.success("保存成功！");

      // 自助创建时暂存任务
      if (
        this.prepareTcPCard.taskId &&
        this.prepareTcPCard.cardSource === "1"
      ) {
        saveWaitTask({
          tcPExamTaskDetail: { ...this.prepareTcPCard, cardId: this.cardId }
        });
      }
    },
    registWindowSubmit() {
      window.submitCardTemp = async cardContentTemp => {
        await submitCard(this.getCardData(cardContentTemp));
        this.$message.success("提交成功！");
        this.cardPreviewUrl = "";
      };
    },
    async toSubmit() {
      await this.save();
      this.cardPreviewUrl = `/#/card/preview/${this.cardId}/frame`;
    }
  },
  beforeDestroy() {
    this.$ls.remove("cardDetailId");
    this.$ls.remove("prepareTcPCard");
    this.initState();
  }
};
</script>
