<template>
  <div :class="classes">
    <card-free-view
      v-if="pages.length"
      ref="CardFreeView"
      class="preview-body"
      :pages="pages"
      :card-config="cardConfig"
    ></card-free-view>
  </div>
</template>

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

export default {
  name: "card-free-preview",
  components: { CardFreeView },
  data() {
    return {
      isPrint: this.$route.params.viewType !== "view",
      isFrame: this.$route.params.viewType === "frame",
      cardId: this.$route.params.cardId,
      pages: [],
      cardConfig: {}
    };
  },
  computed: {
    classes() {
      return [
        "card-free-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 + "}";
        });
      this.cardConfig = cardConfig;
      this.pages = this.appendFieldInfo(pages, fieldInfos);

      this.$nextTick(() => {
        const cardContentTemp = this.$refs.CardFreeView.getPreviewTemp(
          this.$el.outerHTML
        );
        const model = this.$refs.CardFreeView.getPageModel(cardData);
        window.parent &&
          window.parent.submitCardTemp &&
          window.parent.submitCardTemp(cardContentTemp, model);
      });
    },
    async init() {
      const detData = await cardDetail(this.cardId);
      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);
    },
    fetchFieldInfos(cardConfig, stdInfo) {
      let fieldInfos = {};
      const defContent = "相关信息";
      [...cardConfig.requiredFields, ...cardConfig.extendFields]
        .filter(item => item.enable)
        .map(item => {
          fieldInfos[item.code] = stdInfo[item.code] || defContent;
        });

      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) {
      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") {
              const field = element.fields[0] && element.fields[0].code;
              element.content = `data:image/png;base64,${fieldInfos[field]}`;
              return;
            }

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