<template>
  <div :class="classes">
    <div v-if="IS_HTML_TEMPLATE" class="preview-frame" id="preview-frame"></div>

    <component
      v-if="!IS_HTML_TEMPLATE && pages.length"
      :is="editComp"
      ref="CardView"
      class="preview-body"
      :pages="pages"
      :card-config="cardConfig"
    ></component>
  </div>
</template>

<script>
import CardView from "../../../../card/components/CardView";
import CardFreeView from "../../../../card/modules/free/components/CardFreeView";
import { cardDetail } from "../api";
import { deepCopy, getBase64Barcode } from "@/plugins/utils";

export default {
  name: "card-preview",
  components: { CardView, CardFreeView },
  props: {
    isDialog: {
      type: Boolean,
      default: false,
    },
    viewType: {
      type: String,
      default: "view",
    },
    cardData: {
      type: Object,
      default: null,
    },
    cardId: {
      type: String,
      default: null,
    },
  },
  data() {
    return {
      isPrint: "",
      cardCreateMethod: "STANDARD",
      cardType: "CUSTOM",
      cardConfig: {},
      pages: [],
      IS_HTML_TEMPLATE: false,
    };
  },
  computed: {
    classes() {
      return [
        "card-preview",
        {
          "card-print": this.isPrint,
          "card-free-preview": this.cardCreateMethod === "FREE",
        },
      ];
    },
    editComp() {
      return this.cardCreateMethod === "FREE" ? "card-free-view" : "card-view";
    },
  },
  mounted() {
    this.isPrint = this.viewType !== "view";

    if (this.cardData) {
      this.initFromData();
    } else {
      this.initFromApi();
    }
  },
  methods: {
    initFromData() {
      let { cardConfig, pages, createMethod, type } = deepCopy(this.cardData);
      this.cardCreateMethod = createMethod;
      this.cardType = type;

      let fieldInfos = {};
      [...cardConfig.requiredFields, ...cardConfig.extendFields]
        .filter((item) => item.enable)
        .map((item) => {
          fieldInfos[item.code] = "${" + item.code + "}";
        });

      if (this.cardCreateMethod === "STANDARD") {
        const isPrintExamNumber = cardConfig.examNumberStyle === "PRINT";
        if (isPrintExamNumber) {
          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}";
        }
      }
      // 保存题卡时，清除src，使用占位字符，以便后台使用变量填充
      // 编辑预览题卡时，则使用给定内容
      if (!cardConfig.courseCodeBarcodeSrc) {
        cardConfig.courseCodeBarcodeSrc = "${courseCodeBarcodeSrc}";
        cardConfig.courseCodeBarcodeName = "${courseCodeBarcodeName}";
      }

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

      if (this.viewType === "view") return;

      this.$nextTick(() => {
        try {
          const htmlContent = this.$refs.CardView.getPreviewTemp(
            this.$el.outerHTML
          );
          const model = this.$refs.CardView.getPageModel(this.cardData);
          this.$emit("confirm", { htmlContent, model });
        } catch (error) {
          console.dir(error);
          this.$emit("confirm", null);
        }
      });
    },
    async initFromApi() {
      const cardId = this.cardId || this.$route.params.cardId;
      if (!cardId) {
        this.$message.error("题卡id丢失！");
        return;
      }
      const detData = await cardDetail(cardId);
      this.cardCreateMethod = detData.createMethod;
      this.cardType = detData.type;

      this.IS_HTML_TEMPLATE =
        detData.type === "GENERIC" && detData.createMethod === "UPLOAD";
      // 通卡展示
      if (this.IS_HTML_TEMPLATE) {
        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, {});

      if (detData.courseCode) {
        cardConfig.courseCodeBarcodeSrc = getBase64Barcode(detData.courseCode);
        cardConfig.courseCodeBarcodeName = detData.courseCode;
      } else {
        cardConfig.courseCodeBarcodeSrc = "";
        cardConfig.courseCodeBarcodeName = "";
      }

      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;
      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";
      const isPrintExamNumber = cardConfig.examNumberStyle === "PRINT";
      [...cardConfig.requiredFields, ...cardConfig.extendFields]
        .filter((item) => item.enable)
        .map((item) => {
          fieldInfos[item.code] = isPrintExamNumber
            ? stdInfo[item.code] || defContent
            : "";
        });
      if (this.cardCreateMethod === "STANDARD") {
        if (isPrintExamNumber) {
          fieldInfos.examNumber = getBase64Barcode(
            stdInfo["examNumber"] || defNumber
          );
          fieldInfos.examNumberStr = stdInfo["examNumber"] || defNumber;
        }
        if (cardConfig.aOrB && cardConfig.paperType === "PRINT") {
          fieldInfos.paperType = getBase64Barcode(
            stdInfo["paperType"] || defNumber
          );
          fieldInfos.paperTypeName = stdInfo["paperTypeName"] || "A";
        }
      }

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

          if (cardHeadElement.type === "CARD_HEAD") {
            cardHeadElement.fieldInfos = fieldInfos;
          }
        });
      } else {
        // const VALID_ELEMENTS_FOR_EXTERNAL = ["BARCODE"];
        // PS:系统暂时没有设置变量值获取方法，变量站位填充暂时取消。
        const VALID_ELEMENTS_FOR_EXTERNAL = ["BARCODE", "FILL_FIELD"];
        pages.forEach((page) => {
          page.columns.forEach((column) => {
            column.elements.forEach((element) => {
              if (!VALID_ELEMENTS_FOR_EXTERNAL.includes(element.type)) return;

              if (element.type === "BARCODE") {
                let field = element.fields[0] && element.fields[0].code;
                element.content = `data:image/png;base64,$\{${field}Barcode}`;
                return;
              }

              element.fieldInfos = fieldInfos;
            });
          });
        });
      }
      return pages;
    },
  },
};
</script>
