<template>
  <div :class="classes">
    <card-view
      v-if="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";
import html2canvas from "html2canvas";

export default {
  name: "CardPreview",
  components: { CardView },
  data() {
    return {
      isPrint: this.$route.params.viewType !== "view",
      isFrame: this.$route.params.viewType === "frame",
      cardId: this.$route.params.cardId,
      cardConfig: {},
      pages: [],
    };
  },
  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);

      this.cardConfig = cardConfig;
      this.pages = pages;

      this.$nextTick(() => {
        this.buildData(cardData);
      });
    },
    async buildData(cardData) {
      const cardContentTemp = this.$refs.CardView.getPreviewTemp(
        this.$el.outerHTML
      );
      // console.log(cardContentTemp);
      const cardImages = await this.transformImags().catch(() => {});
      try {
        const model = this.$refs.CardView.getPageModel(cardData);
        window.parent &&
          window.parent.submitCardTemp &&
          window.parent.submitCardTemp(model, cardImages, cardContentTemp);
      } catch (error) {
        console.dir(error);
        window.parent &&
          window.parent.submitCardTemp &&
          window.parent.submitCardTemp("", "", "");
      }
    },
    async init() {
      const detDataRes = await cardDetail(this.cardId);
      // 常规卡展示
      if (!detDataRes.data || !detDataRes.data.content) {
        this.$message.error("很抱歉，当前无题卡数据！");
        return;
      }
      const { cardConfig, pages } = JSON.parse(detDataRes.data.content);

      this.cardConfig = cardConfig;
      this.pages = pages;
    },
    async transformPageToImage(pageDom) {
      const canvasDom = await html2canvas(pageDom, {
        allowTaint: true,
        imageTimeout: 3000,
        scale: 2,
      });

      return canvasDom.toDataURL();
    },
    async transformImags() {
      const pageDoms = this.$el.querySelectorAll(".page-box");
      let images = [];
      for (let i = 0; i < pageDoms.length; i++) {
        const pageDom = pageDoms[i];
        const imgDataUrl = await this.transformPageToImage(pageDom);
        images[i] = imgDataUrl;
      }
      // console.log(images);
      return images;
    },
  },
};
</script>
