<template>
  <div class="card-edit">
    <card-design
      v-if="dataReady"
      ref="CardDesign"
      :content="cardContent"
      :paper-json="paperJson"
      @on-preview="toPreview"
      @on-save="toSave"
      @on-submit="toSubmit"
      @on-exit="toExit"
    ></card-design>

    <!-- card-view-frame -->
    <div v-if="cardPreviewUrl" class="design-preview-frame">
      <iframe :src="cardPreviewUrl" frameborder="0"></iframe>
    </div>
  </div>
</template>

<script>
import { cardConfigInfos, cardDetail, saveCard, paperDetailApi } from "../api";
import CardDesign from "../components/CardDesign";
import { getPaperJsonSimpleStructInfo } from "../autoBuild/paperStruct";

export default {
  name: "CardEdit",
  components: {
    CardDesign,
  },
  data() {
    return {
      cardId: this.$route.params.cardId,
      paperId: this.$route.params.paperId,
      paperJson: null,
      cardContent: {},
      cardPreviewUrl: "",
      canSave: false,
      dataReady: false,
    };
  },
  computed: {
    isEdit() {
      return !!this.cardId;
    },
  },
  mounted() {
    this.initCard();
    this.registWindowSubmit();
  },
  beforeDestroy() {
    delete window.submitCardTemp;
  },
  methods: {
    async initCard() {
      this.dataReady = false;
      const paperRes = await paperDetailApi(this.paperId);
      this.paperJson = paperRes.data;

      if (this.isEdit) {
        await this.getCardTempDetail();
      } else {
        await this.initCardContent();
      }
      this.dataReady = true;
    },
    async getCardTempDetail() {
      const detData = await cardDetail(this.cardId);
      // 可能存在题卡内容没有记录的情况
      if (detData.content) {
        this.cardContent = JSON.parse(detData.content);
        const curPaperSimpleStruct = getPaperJsonSimpleStructInfo(
          this.paperJson
        );
        if (curPaperSimpleStruct !== this.cardContent.paperSimpleStruct) {
          this.$message.info("试卷结构有变化，将重新生成题卡");
          this.cardContent = {
            pages: [],
            cardConfig: detData.cardConfig,
            paperSimpleStruct: getPaperJsonSimpleStructInfo(this.paperJson),
          };
        }
      } else {
        this.$message.info("无题卡内容，将重新生成题卡");
        await this.initCardContent();
      }
    },
    async initCardContent() {
      const cardConfig = await this.getCardConfig();
      this.cardContent = {
        pages: [],
        cardConfig,
        paperSimpleStruct: getPaperJsonSimpleStructInfo(this.paperJson),
      };
    },
    async getCardConfig() {
      const data = await cardConfigInfos();
      if (!data) {
        this.$message.error("找不到题卡版头！");
        return;
      }
      const config = {
        ...data,
        ...{
          pageSize: "A3",
          columnNumber: 2,
          columnGap: 20,
          showForbidArea: true,
          showScorePan: false,
        },
      };
      return config;
    },
    // 操作
    getCardData(htmlContent = "", model = "") {
      let data = this.$refs.CardDesign.getCardData(htmlContent, model);
      data = {
        ...data,
        paperId: this.paperId,
      };
      if (this.cardId) data.id = this.cardId;
      return data;
    },
    async toPreview(datas) {
      await this.toSave(datas);

      const { href } = this.$router.resolve({
        name: "CardPreview",
        params: {
          cardId: this.cardId,
          viewType: "view",
        },
      });
      window.open(href);
    },
    // save
    async toSave(datas) {
      datas.status = "STAGE";
      const result = await saveCard(datas).catch(() => {});

      this.$refs.CardDesign.unloading();
      if (!result) return;

      this.cardId = result;
      // this.$ls.set("cardId", this.cardId);
      this.$message.success("保存成功！");
    },
    async toSubmit(cardData) {
      const res = await this.$confirm("确定要提交当前题卡吗?", "提示", {
        type: "warning",
      }).catch(() => {});
      if (res !== "confirm") return;

      window.cardData = cardData;
      const { href } = this.$router.resolve({
        name: "CardPreview",
        params: {
          cardId: 1,
          viewType: "frame",
        },
      });
      this.cardPreviewUrl = href;
    },
    registWindowSubmit() {
      window.submitCardTemp = async (htmlContent, model, cardImages) => {
        if (!cardImages || !cardImages.length) {
          this.$message.error("题卡图片生成失败！");
          return;
        }

        const datas = this.getCardData(htmlContent, model);
        datas.status = "SUBMIT";
        datas.cardImages = cardImages;
        const result = await saveCard(datas, this.getRequestConfig()).catch(
          () => {}
        );
        this.cardPreviewUrl = "";
        window.cardData = null;
        if (result) {
          this.cardId = result;
          // this.$ls.set("cardId", this.cardId);
          this.canSave = false;
          this.$message.success("提交成功！");
          this.goback();
        } else {
          this.$message.error("提交失败，请重新尝试！");
        }
      };
    },
    toExit() {
      this.$confirm(
        "请确保当前题卡已经正常保存，确定要退出当前题卡编辑吗?",
        "提示",
        {
          type: "warning",
        }
      )
        .then(() => {
          this.goback();
        })
        .catch(() => {});
    },
  },
};
</script>
