<template>
  <div class="card-build card-preview card-print">
    <card-view
      v-if="pages.length"
      ref="CardView"
      class="preview-body"
      :pages="pages"
      :card-config="cardConfig"
    ></card-view>
    <!-- all topics -->
    <div v-else class="topic-list">
      <div
        :class="['page-box', `page-box-${cardConfig.pageSize}`, 'page-box-0']"
      >
        <div class="page-main-inner">
          <div
            :class="['page-main', `page-main-${cardConfig.columnNumber}`]"
            :style="{ margin: `0 -${cardConfig.columnGap / 2}px` }"
          >
            <div
              class="page-column"
              :style="{ padding: `0 ${cardConfig.columnGap / 2}px` }"
            >
              <div id="topic-column" class="page-column-main">
                <div class="page-column-body">
                  <!-- topic element -->
                  <topic-element-preview
                    v-for="element in topics"
                    :key="element.id"
                    class="page-column-element"
                    :data="element"
                  ></topic-element-preview>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations, mapActions } from "vuex";
import TopicElementPreview from "../components/TopicElementPreview";
import CardView from "../components/CardView";
import html2canvas from "html2canvas";
import { getPageInitElements } from "../pageModel";
import { buildCardFromPaperSimpleStruct } from "../autoBuild/simplePaperCard";
import { saveCard } from "../api";

export default {
  name: "CardBuild",
  components: { CardView, TopicElementPreview },
  data() {
    return {
      cardId: "",
    };
  },
  computed: {
    ...mapState("card", [
      "cardConfig",
      "paperSimpleStruct",
      "pageDefaultElems",
      "topics",
      "pages",
    ]),
  },
  mounted() {
    this.initData();
  },
  methods: {
    ...mapMutations("card", [
      "setCardConfig",
      "setPages",
      "setTopics",
      "setPageDefaultElems",
      "initState",
      "setPaperSimpleStruct",
    ]),
    ...mapActions("card", ["resetTopicSeries", "rebuildPages"]),
    initData() {
      this.initState();
      const cardData = window.parent.cardData;
      if (!cardData) return;

      const { cardConfig, paperSimpleStruct, cardId } = cardData;
      this.cardId = cardId;
      this.setCardConfig(cardConfig);
      this.setPaperSimpleStruct(paperSimpleStruct);
      const pageDefaultElems = getPageInitElements(cardConfig);
      this.setPageDefaultElems(pageDefaultElems);

      const elementTypePreSetInfo = {
        FILL_LINE: { fillCountPerLine: 1 },
        FILL_QUESTION: {
          pageSize: cardConfig.pageSize,
          columnNumber: cardConfig.columnNumber,
        },
      };
      const elements = buildCardFromPaperSimpleStruct(
        paperSimpleStruct,
        elementTypePreSetInfo
      );
      this.setTopics([...this.pageDefaultElems.elements, ...elements]);
      this.resetTopicSeries();

      this.$nextTick(() => {
        this.rebuildPages();

        this.$nextTick(() => {
          this.buildData();
        });
      });
    },
    async buildData() {
      const model = this.$refs.CardView.getPageModel({
        cardConfig: this.cardConfig,
        pages: this.pages,
        paperSimpleStruct: this.paperSimpleStruct,
      });
      // const images = await this.transformImags().catch(() => {});
      const cardContentTemp = this.$refs.CardView.getPreviewTemp(
        this.$el.outerHTML
      );

      const datas = {
        id: this.cardId,
        content: model,
        pageSize: this.cardConfig.pageSize,
        htmlContent: cardContentTemp,
        formal: true,
      };
      const result = await saveCard(datas).catch(() => {});

      window.parent &&
        window.parent.emitResult &&
        window.parent.emitResult(result && result.data, datas);
    },
    async transformPageToImage(pageDom) {
      const canvasDom = await html2canvas(pageDom, {
        allowTaint: true,
        imageTimeout: 3000,
      });

      return canvasDom.toDataURL();
    },
    async transformImags() {
      const pageDoms = this.$refs.CardView.$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;
      }
      return images;
    },
  },
};
</script>
