<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 @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
                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 class="action-part">
          <div class="action-part-title"><h2>阅卷参数</h2></div>
          <div class="action-part-body">
            <el-button type="primary">上传阅卷参数（0）</el-button>
          </div>
        </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"
                        :data-h="element.h"
                        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">
              <page-number
                type="rect"
                :total="pages.length"
                :current="pageNo + 1"
              ></page-number>
              <page-number
                type="text"
                :total="pages.length"
                :current="pageNo + 1"
              ></page-number>
            </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 {
  getElementModel,
  getCardHeadModel,
  getNewPage,
  getTopicModel,
  ELEMENT_LIST,
  TOPIC_LIST
} from "../elementModel";
import { transformField, getAOrBSystem } from "../enumerate";
// import CardConfigPropEdit from "../components/CardConfigPropEdit";
import TopicElementEdit from "../components/TopicElementEdit";
import PagePropEdit from "../components/PagePropEdit";
import ElementPropEdit from "../components/elementPropEdit/ElementPropEdit";
import RightClickMenu from "../components/RightClickMenu";
import CardHeadSample from "../components/elementEdit/CardHeadSample";
import SavePage from "../components/SavePage";
import PageNumber from "../components/pageInfo/PageNumber";

export default {
  name: "card-design",
  components: {
    // CardConfigPropEdit,
    TopicElementEdit,
    PagePropEdit,
    ElementPropEdit,
    RightClickMenu,
    CardHeadSample,
    SavePage,
    PageNumber
  },
  data() {
    return {
      cardId: this.$route.params.cardId || this.$ls.get("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",
      "initTopicNos",
      "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);
        this.initTopicNos();
      } else {
        // 没有题卡内容时，直接创建新的内容
        this.setCardConfig({ cardName: detData.title });
        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() {
      const result = await this.save();
      if (!result) return;
      window.open(
        this.getRouterPath({
          name: "CardPreview",
          params: {
            cardId: this.cardId,
            viewType: "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: "",
          id: this.cardId
        },
        {
          ...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;

      if (this.prepareTcPCard.taskId && this.prepareTcPCard.cardSource === "1")
        data.tcPExamTaskDetail = {
          ...this.prepareTcPCard,
          cardId: this.cardId
        };
      return data;
    },
    async save() {
      if (!this.cardConfig.cardName) {
        this.$message.error("题卡标题不能为空！");
        this.setCurPageNo(0);
        setTimeout(() => {
          document.getElementById("cardNameInput").focus();
        });
        return false;
      }
      const result = await saveCard(this.getCardData());
      this.cardDetailId = result.cardDetailId;
      this.cardId = result.cardId;
      this.$ls.set("cardDetailId", this.cardDetailId);
      this.$ls.set("cardId", this.cardId);
      return true;
    },
    async toSave() {
      const result = await this.save();
      if (result) this.$message.success("保存成功！");
    },
    toSubmit() {
      this.$confirm("确定要提交当前题卡吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const result = await this.save();
          if (result)
            this.cardPreviewUrl = `/#/card/preview/${this.cardId}/frame`;
        })
        .catch(() => {});
    },
    registWindowSubmit() {
      window.submitCardTemp = async cardContentTemp => {
        const result = await submitCard(
          this.getCardData(cardContentTemp)
        ).catch(() => {});
        this.cardPreviewUrl = "";
        if (result) {
          this.$message.success("提交成功！");
        } else {
          this.$message.error("提交失败，请重新尝试！");
        }
      };
    }
  },
  beforeDestroy() {
    this.$ls.remove("cardId");
    this.$ls.remove("cardDetailId");
    this.$ls.remove("prepareTcPCard");
    this.initState();
  }
};
</script>
