<template>
  <div :class="classes">
    <div class="preview-frame" id="preview-frame" v-if="IS_COMMON_CARD"></div>
    <div class="preview-body" v-else>
      <template v-for="(page, pageNo) in pages">
        <div
          :class="[
            'page-box',
            `page-box-${cardConfig.pageSize}`,
            `page-box-${pageNo % 2}`
          ]"
          :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-preview
                      class="page-column-element"
                      v-for="element in column.elements"
                      :key="element.id"
                      :data="element"
                    ></topic-element-preview>
                  </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>
  </div>
</template>

<script>
import TopicElementPreview from "../components/TopicElementPreview";
import PageNumber from "../components/PageNumber";
import { cardDetail } from "../api";
import previewTemp from "../previewTemp";
import exchangeMixins from "../mixins/exchange";
import { deepCopy } from "../plugins/utils";
const JsBarcode = require("jsbarcode");

export default {
  name: "card-preview",
  components: { TopicElementPreview, PageNumber },
  mixins: [exchangeMixins],
  data() {
    return {
      isPrint: this.$route.params.viewType !== "view",
      isFrame: this.$route.params.viewType === "frame",
      cardId: this.$route.params.cardId,
      cardConfig: {},
      pages: [],
      IS_COMMON_CARD: false
    };
  },
  computed: {
    classes() {
      return [
        "card-preview",
        {
          "card-print": this.isPrint
        }
      ];
    }
  },
  mounted() {
    if (this.isFrame) {
      this.initFrame();
    } else {
      this.init();
    }
  },
  methods: {
    initFrame() {
      const cardData = window.parent.cardData;
      if (!cardData) return;

      const { cardConfig, pages } = deepCopy(cardData);
      let fieldInfos = {};
      [...cardConfig.requiredFields, ...cardConfig.extendFields]
        .filter(item => item.enable)
        .map(item => {
          fieldInfos[item.code] = "${" + item.code + "}";
        });
      if (cardConfig.examNumberStyle === "PRINT") {
        fieldInfos.examNumber = "data:image/png;base64,${examNumber}";
        fieldInfos.examNumberStr = "${examNumberStr}";
      }

      if (cardConfig.aOrB && cardConfig.paperType === "PRINT") {
        fieldInfos.paperType = "data:image/png;base64,${paperType}";
        fieldInfos.paperTypeName = "${paperTypeName}";
      }

      this.cardConfig = cardConfig;
      this.pages = this.appendFieldInfo(pages, fieldInfos);

      this.$nextTick(() => {
        const cardContentTemp = previewTemp(this.$el.outerHTML);
        const model = this.getPageModel(cardData);
        window.parent &&
          window.parent.submitCardTemp &&
          window.parent.submitCardTemp(cardContentTemp, model);
      });
    },
    async init() {
      const detData = await cardDetail(this.cardId);

      this.IS_COMMON_CARD = detData.type === "GENERIC";
      // 通卡展示
      if (this.IS_COMMON_CARD) {
        this.$nextTick(() => {
          this.initHtmlTemp(detData.htmlContent);
        });
        return;
      }
      // 常规卡展示
      if (!detData.content) {
        this.$message.error("很抱歉，当前题卡还没开始制作！");
        return;
      }
      const { cardConfig, pages } = JSON.parse(detData.content);
      const fieldInfos = this.fetchFieldInfos(cardConfig, {});

      this.cardConfig = cardConfig;
      this.pages = this.appendFieldInfo(pages, fieldInfos);
    },
    initHtmlTemp(htmlTemp) {
      const iframeDom = document.createElement("iframe");
      document.getElementById("preview-frame").appendChild(iframeDom);
      const wwidth = window.innerWidth - 10;
      const wheight = window.innerHeight - 10;
      iframeDom.style.cssText = `width: ${wwidth}px;height: ${wheight}px;border:none;outline:none;`;
      const iframeDoc = iframeDom.contentDocument;
      iframeDoc.open();
      iframeDoc.write(htmlTemp);
      iframeDoc.close();
    },
    fetchFieldInfos(cardConfig, stdInfo) {
      let fieldInfos = {};
      const defContent = "相关信息";
      const defNumber = "123456789";
      [...cardConfig.requiredFields, ...cardConfig.extendFields]
        .filter(item => item.enable)
        .map(item => {
          fieldInfos[item.code] = stdInfo[item.code] || defContent;
        });
      if (cardConfig.examNumberStyle === "PRINT") {
        fieldInfos.examNumber = this.getBase64Barcode(
          stdInfo["examNumber"] || defNumber
        );
        fieldInfos.examNumberStr = stdInfo["examNumber"] || defNumber;
      }
      if (cardConfig.aOrB && cardConfig.paperType === "PRINT") {
        fieldInfos.paperType = this.getBase64Barcode(
          stdInfo["paperType"] || defNumber
        );
        fieldInfos.paperTypeName = stdInfo["paperTypeName"] || "A";
      }

      return fieldInfos;
    },
    getBase64Barcode(str) {
      const canvas = document.createElement("CANVAS");
      JsBarcode(canvas, str, {
        width: 2,
        height: 30,
        displayValue: false,
        marginLeft: 20,
        marginRight: 20,
        marginTop: 0,
        marginBottom: 0
      });

      return canvas.toDataURL();
    },
    appendFieldInfo(pages, fieldInfos) {
      pages.forEach((page, pageNo) => {
        if (pageNo % 2) return;
        const cardHeadElement = page.columns[0].elements[0];

        if (cardHeadElement.type === "CARD_HEAD") {
          cardHeadElement.fieldInfos = fieldInfos;
        }
      });
      return pages;
    }
  }
};
</script>
