<template>
  <div class="card-design">
    <div class="design-top">
      <div class="design-top-logo">
        <h1><i class="icon icon-back" @click="toExit"></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
            >
            <el-button
              type="primary"
              @click="toSave"
              :disabled="canSave || !pages.length"
              >暂存</el-button
            >
            <el-button type="primary" @click="toSubmit" :loading="isSubmit"
              >提交</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>
            <!-- Develop btns -->
            <!-- <card-config-prop-edit></card-config-prop-edit> -->
          </div>
          <!-- <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" @click="modifyParams"
              >上传阅卷参数<span class="color-danger"
                >（{{ paperParams["pageSumScore"] || 0 }}分）</span
              ></el-button
            >
          </div>
        </div> -->
      </div>

      <!-- edit body -->
      <div class="design-body">
        <div
          :class="['page-box', `page-box-${curPageNo % 2}`]"
          v-if="curPage.locators"
        >
          <div
            :class="[
              'page-locators',
              `page-locators-${curPage.locators.length}`
            ]"
          >
            <ul
              class="page-locator-group"
              v-for="(locator, iind) in curPage.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-${curPage.columns.length}`]"
              :style="{ margin: `0 -${curPage.columnGap / 2}px` }"
            >
              <div
                class="page-column"
                v-for="(column, columnNo) in curPage.columns"
                :key="columnNo"
                :style="{ padding: `0 ${curPage.columnGap / 2}px` }"
              >
                <div
                  class="page-column-main"
                  :id="[`column-${curPageNo}-${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="curPageNo + 1"
            ></page-number>
            <page-number
              type="text"
              :total="pages.length"
              :current="curPageNo + 1"
            ></page-number>
          </div>
        </div>
      </div>
    </div>

    <!-- all topics -->
    <div class="topic-list">
      <div class="page-box">
        <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 class="page-column-main" id="topic-column">
                <div class="page-column-body">
                  <!-- card-head-sample -->
                  <card-head-sample
                    :data="cardHeadSampleData"
                    id="simple-card-head"
                    v-if="topics.length && cardHeadSampleData"
                  ></card-head-sample>
                  <!-- topic element -->
                  <topic-element-preview
                    class="page-column-element"
                    v-for="element in topics"
                    :key="element.id"
                    :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>
    <!-- card-view-frame -->
    <div class="design-preview-frame" v-if="cardPreviewUrl">
      <iframe :src="cardPreviewUrl" frameborder="0"></iframe>
    </div>
    <!-- paper-params -->
    <paper-params
      :pages="pages"
      :paper-params="paperParams"
      @confirm="paperParamsModified"
      ref="PaperParams"
    ></paper-params>
    <!-- topic select dialog -->
    <topic-select-dialog
      ref="TopicSelectDialog"
      :topics="topicList"
      @confirm="addNewTopic"
    ></topic-select-dialog>
  </div>
</template>

<script>
import { mapState, mapMutations, mapActions } from "vuex";
import {
  cardConfigInfos,
  cardDetailEdit,
  cardTempDetail,
  saveCard,
  submitCard
} from "../api";
import {
  getElementModel,
  getCardHeadModel,
  ELEMENT_LIST,
  TOPIC_LIST
} from "../elementModel";
import { transformField, getAOrBSystem, CARD_VERSION } from "../enumerate";
// import CardConfigPropEdit from "../components/CardConfigPropEdit";
import TopicElementEdit from "../components/TopicElementEdit";
import TopicElementPreview from "../components/TopicElementPreview";
import PagePropEdit from "../components/PagePropEdit";
import ElementPropEdit from "../components/ElementPropEdit";
import RightClickMenu from "../components/RightClickMenu";
import PageNumber from "../components/PageNumber";
import PaperParams from "../components/PaperParams";
import CardHeadSample from "../elements/card-head/CardHead";
import TopicSelectDialog from "../components/TopicSelectDialog";

export default {
  name: "card-design",
  components: {
    // CardConfigPropEdit,
    TopicElementEdit,
    TopicElementPreview,
    PagePropEdit,
    ElementPropEdit,
    RightClickMenu,
    CardHeadSample,
    PageNumber,
    PaperParams,
    TopicSelectDialog
  },
  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,
      topicList: [],
      steps: ["添加标题", "基本设置", "试题配置", "设置阅卷参数", "预览生成"],
      columnWidth: 0,
      cardPreviewUrl: "",
      isSubmit: false,
      canSave: false
    };
  },
  computed: {
    ...mapState("card", [
      "cardConfig",
      "topics",
      "pages",
      "paperParams",
      "curElement",
      "curPage",
      "curPageNo"
    ]),
    isEdit() {
      return !!this.cardId;
    },
    cardHeadSampleData() {
      if (!this.cardConfig["pageSize"]) return;
      const data = getCardHeadModel(this.cardConfig);
      data.isSimple = true;
      return data;
    }
  },
  mounted() {
    this.initCard();
    this.registWindowSubmit();
  },
  methods: {
    ...mapMutations("card", [
      "addPage",
      "setCurPage",
      "setCurElement",
      "setCardConfig",
      "setOpenElementEditDialog",
      "setCurDragElement",
      "setPages",
      "setPaperParams",
      "setInsetTarget",
      "initState"
    ]),
    ...mapActions("card", [
      "resetTopicSeries",
      "removePage",
      "addElement",
      "modifyCardHead",
      "modifyElement",
      "rebuildPages",
      "initTopicsFromPages"
    ]),
    async initCard() {
      await this.getCardConfig();
      if (this.isEdit) {
        this.getCardTempDetail();
      } else {
        this.initPageData();
      }
      this.addWatch();
    },
    async getCardTempDetail(content) {
      const detData = await cardDetailEdit(this.cardId);
      const tempData = await cardTempDetail(this.cardId);
      this.canSave = !detData.operateStatus;
      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.setPaperParams(cont.paperParams);
        this.initTopicsFromPages();
        this.resetTopicSeries();
        this.setCurPage(0);
      } else {
        // 没有题卡内容时，直接创建新的内容
        this.setCardConfig({
          cardName: detData.title,
          aOrB: detData.enablePaperType.split(",").length > 1
        });
        this.initPageData();
      }
    },
    initPageData() {
      this.modifyCardHead({
        ...getCardHeadModel(this.cardConfig)
      });
      this.$nextTick(() => {
        this.rebuildPages();
        this.setCurPage(0);
      });
    },
    async getCardConfig() {
      const data = await cardConfigInfos();
      if (!data) {
        this.$message.error("请先配置题卡规则！");
        return;
      }
      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 = 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();
        });
      });
    },
    // 操作
    async toPreview() {
      // this.$ls.set("cardData", {
      //   cardConfig: this.cardConfig,
      //   pages: this.pages,
      //   paperParams: this.paperParams
      // });
      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.setCurPage(pindex);
      this.setCurElement({});
    },
    // paper-params
    modifyParams() {
      this.$refs.PaperParams.open();
    },
    paperParamsModified(paperParams) {
      this.setPaperParams(paperParams);
    },
    // save
    getCardData(contentTemp = "", model = "") {
      const multiEnablePaperType =
        this.prepareTcPCard["enablePaperType"] &&
        this.prepareTcPCard["enablePaperType"].split(",").length > 1
          ? this.prepareTcPCard["enablePaperType"]
          : "";
      const tcPCard = this.$objAssign(
        {
          examId: "",
          enablePaperType: "A",
          courseName: "",
          courseCode: "",
          cardSource: "",
          title: "",
          id: this.cardId
        },
        {
          ...this.prepareTcPCard,
          title: this.cardConfig.cardName,
          enablePaperType: this.cardConfig.aOrB
            ? multiEnablePaperType || "A,B"
            : "A"
        }
      );

      let data = {
        tcPCard,
        tcPCardDetail: {
          content: model,
          subjectiveAttachmentId:
            this.paperParams["subjectiveAttachmentId"] || "",
          contentTemp
        }
      };
      if (this.cardDetailId) data.tcPCardDetail.id = this.cardDetailId;

      if (this.prepareTcPCard.taskId && this.prepareTcPCard.cardSource === "1")
        data.tcPExamTaskDetail = {
          ...this.prepareTcPCard,
          cardId: this.cardId
        };
      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.cardConfig.schoolName) {
        this.$message.error("主标题不能为空！");
        this.setCurPageNo(0);
        setTimeout(() => {
          document.getElementById("cardTitleInput").focus();
        });
        return false;
      }
      if (!this.cardConfig.cardName) {
        this.$message.error("题卡标题不能为空！");
        this.setCurPage(0);
        setTimeout(() => {
          document.getElementById("cardNameInput").focus();
        });
        return false;
      }
      if (this.checkElementCovered()) {
        this.$message.error("题卡中存在被遮挡的元件，请注意调整！");
        return false;
      }

      return true;
    },
    getModel() {
      return JSON.stringify(
        {
          version: CARD_VERSION,
          cardConfig: this.cardConfig,
          paperParams: this.paperParams,
          pages: this.pages
        },
        (k, v) => (k.startsWith("_") ? undefined : v)
      );
    },
    async save() {
      if (!this.checkCardValid()) return;

      const result = await saveCard(this.getCardData("", this.getModel()));
      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("保存成功！");
    },
    // toSave() {
    //   // console.log(this.getCardData());
    //   this.canSave = true;
    //   setTimeout(() => {
    //     this.canSave = false;
    //   }, 500);
    // },
    toSubmit() {
      if (this.isSubmit) return;

      if (!this.checkCardValid()) return;

      this.$confirm("确定要提交当前题卡吗?", "提示", {
        cancelButtonClass: "el-button--danger is-plain",
        confirmButtonClass: "el-button--primary",
        type: "warning"
      })
        .then(() => {
          window.cardData = {
            cardConfig: this.cardConfig,
            pages: this.pages,
            paperParams: this.paperParams
          };
          this.isSubmit = true;
          this.cardPreviewUrl = `/#/card/preview/${this.cardId}/frame`;
        })
        .catch(() => {});
    },
    registWindowSubmit() {
      window.submitCardTemp = async (cardContentTemp, model) => {
        const data = this.getCardData(cardContentTemp, model);
        const result = await submitCard(data).catch(() => {});
        this.cardPreviewUrl = "";
        this.isSubmit = false;
        window.cardData = null;
        if (result) {
          this.cardDetailId = result.cardDetailId;
          this.cardId = result.cardId;
          this.$ls.set("cardDetailId", this.cardDetailId);
          this.$ls.set("cardId", this.cardId);
          this.canSave = false;
          this.$message.success("提交成功！");
          // 提交之后退出编辑，v1.1修改
          this.goback();
        } else {
          this.$message.error("提交失败，请重新尝试！");
        }
      };
    },
    toExit() {
      this.$confirm(
        "请确保当前题卡已经正常保存，确定要退出当前题卡编辑吗?",
        "提示",
        {
          cancelButtonClass: "el-button--danger is-plain",
          confirmButtonClass: "el-button--primary",
          type: "warning"
        }
      )
        .then(() => {
          this.goback();
        })
        .catch(() => {});
    }
  },
  beforeDestroy() {
    this.$ls.remove("cardId");
    this.$ls.remove("cardDetailId");
    this.$ls.remove("prepareTcPCard");
    this.initState();
    delete window.submitCardTemp;
  }
};
</script>
