<template>
  <div :class="classes">
    <div v-if="IS_COMMON_CARD" class="preview-frame" id="preview-frame"></div>
    <card-view
      v-if="!IS_COMMON_CARD && pages.length"
      ref="CardView"
      class="preview-body"
      :pages="pages"
      :card-config="cardConfig"
    ></card-view>
  </div>
</template>

<script>
import CardView from "../components/CardView";
import { cardDetail } from "../api";
import { deepCopy } from "../plugins/utils";
const JsBarcode = require("jsbarcode");

export default {
  name: "card-preview",
  components: { CardView },
  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 = this.$refs.CardView.getPreviewTemp(
          this.$el.outerHTML
        );
        const model = this.$refs.CardView.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) {
        // TODO:通卡展示逻辑要调整
        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>
