<template>
  <div class="card-edit">
    <card-design
      v-if="dataReady"
      ref="CardDesign"
      :content="cardContent"
      @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,
  cardDetailByPaperId,
  cardTemplateDetail,
  saveCardByPaper,
} from "../api";
import CardDesign from "../components/CardDesign";
import { getPaperJsonSimpleStructInfo } from "../autoBuild/paperStruct";

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

      const paperRes = await paperDetailApi(this.paperId);
      this.paperJson = paperRes.data;

      const detDataRes = await cardDetailByPaperId(this.paperId);
      if (detDataRes.data && detDataRes.data.id)
        this.cardId = detDataRes.data.id;

      if (detDataRes.data && detDataRes.data.content) {
        this.cardContent = JSON.parse(detDataRes.data.content);
        const curPaperSimpleStruct = getPaperJsonSimpleStructInfo(
          this.paperJson
        );

        if (curPaperSimpleStruct !== this.cardContent.paperSimpleStruct) {
          this.$message.warning("试卷结构有变化，已重新生成题卡");
          this.cardContent = {
            pages: [],
            cardConfig: this.cardContent.cardConfig,
            paperSimpleStruct: curPaperSimpleStruct,
          };
        }
      } else {
        await this.initCardContent();
      }
      this.dataReady = true;
    },
    async initCard() {
      this.dataReady = false;

      if (this.isEdit) {
        await this.getCardTempDetail();
      } else {
        await this.initCardContent();
      }
      this.dataReady = true;
    },
    async getCardTempDetail() {
      const detDataRes = await cardDetail(this.cardId);

      // 可能存在题卡内容没有记录的情况
      if (!detDataRes.data || !detDataRes.data.content) {
        this.$message.info("无题卡内容，将重新生成题卡");
        await this.initCardContent();
        return;
      }

      this.cardContent = JSON.parse(detDataRes.data.content);
      // 通过单纯试卷结构生成的题卡，试卷结构是不会变得，这里暂时不做自动更新处理。
      // const curPaperSimpleStruct = getPaperStructSimpleStructInfo(
      //   detDataRes.data.structure || { details: [] }
      // );
      // if (curPaperSimpleStruct !== this.cardContent.paperSimpleStruct) {
      //   this.$message.warning("试卷结构有变化，已重新生成题卡");
      //   this.cardContent = {
      //     pages: [],
      //     cardConfig: this.cardContent.cardConfig,
      //     paperSimpleStruct: curPaperSimpleStruct,
      //   };
      // }
    },
    async initCardContent() {
      const cardConfig = await this.getCardConfig();
      this.cardContent = {
        pages: [],
        cardConfig,
        paperSimpleStruct: getPaperJsonSimpleStructInfo(this.paperJson),
      };
    },
    async getCardConfig() {
      const res = await cardConfigInfos();
      if (!res.data) {
        this.$message.error("找不到题卡版头！");
        return;
      }
      const tempRes = await cardTemplateDetail(res.data.cardTemplateId);
      if (!tempRes.data) {
        this.$message.error("找不到题卡模板！");
        return;
      }

      const config = {
        ...res.data,
        ...{
          columnNumber: 2,
          columnGap: 20,
          showForbidArea: false,
          showScorePan: false,
          templateInfo: JSON.parse(tempRes.data.content),
        },
      };
      config.pageSize = config.pageSize || "A3";
      return config;
    },
    // 操作
    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(infos) {
      let datas = { ...infos };
      datas.id = this.cardId;
      datas.formal = false;
      let saveFunc = null;
      if (this.idType === "paper") {
        datas.paperId = this.paperId;
        saveFunc = saveCardByPaper;
      } else {
        saveFunc = saveCard;
      }
      let result = await saveFunc(datas).catch(() => {});
      this.$refs.CardDesign.unloading();
      if (!result) return;
      this.cardId = result.data;
      this.$message.success("保存成功！");
    },
    async toSubmit(cardData) {
      const res = await this.$confirm("确定要提交当前题卡吗?", "提示", {
        type: "warning",
      }).catch(() => {});
      if (res !== "confirm") return;

      window.cardData = cardData;
      this.$refs.CardDesign.loading();
      const { href } = this.$router.resolve({
        name: "CardPreview",
        params: {
          cardId: 1,
          viewType: "frame",
        },
        query: {
          t: Date.now(),
        },
      });
      this.cardPreviewUrl = href;
    },
    registWindowSubmit() {
      window.submitCardTemp = async (model, cardContentTemp) => {
        if (!model || !cardContentTemp) {
          this.$refs.CardDesign.unloading();
          window.cardData = null;
          this.cardPreviewUrl = "";
          this.$message.error("提交失败，请重新尝试！");
          return;
        }

        let datas = {
          content: model,
          htmlContent: cardContentTemp,
          pageSize: window.cardData.cardConfig.pageSize,
        };
        datas.id = this.cardId;
        datas.formal = true;
        let saveFunc = null;
        if (this.idType === "paper") {
          datas.paperId = this.paperId;
          saveFunc = saveCardByPaper;
        } else {
          saveFunc = saveCard;
        }
        let result = await saveFunc(datas).catch(() => {});
        this.cardPreviewUrl = "";
        window.cardData = null;
        this.$refs.CardDesign.unloading();
        if (result) {
          this.cardId = result.data;
          this.canSave = false;
          this.$message.success("提交成功！");
          this.goback();
        } else {
          this.$message.error("提交失败，请重新尝试！");
        }
      };
    },
    toExit() {
      this.$confirm(
        "请确保当前题卡已经正常保存，确定要退出当前题卡编辑吗?",
        "提示",
        {
          type: "warning",
        }
      )
        .then(() => {
          this.goback();
        })
        .catch(() => {});
    },
  },
};
</script>
