<template>
  <div class="card-free-edit">
    <card-free-design
      v-if="dataReady"
      ref="CardFreeDesign"
      :content="cardContent"
      @on-preview="toPreview"
      @on-save="toSave"
      @on-submit="toSubmit"
      @on-exit="toExit"
    ></card-free-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 } from "../api";
import CardFreeDesign from "../modules/free/components/CardFreeDesign";

export default {
  name: "CardFreeEdit",
  components: {
    CardFreeDesign,
  },
  data() {
    return {
      cardId: this.$route.params.cardId || this.$ls.get("cardId"),
      prepareTcPCard: this.$ls.get("prepareTcPCard", {
        examTaskId: "",
        courseCode: "",
        courseName: "",
        makeMethod: "SELF",
        cardRuleId: "",
      }),
      cardContent: {},
      cardPreviewUrl: "",
      isSubmit: false,
      canSave: false,
      dataReady: false,
    };
  },
  computed: {
    isEdit() {
      return !!this.cardId;
    },
  },
  mounted() {
    // if (!this.prepareTcPCard.examTaskId && !this.isEdit) {
    //   this.$message.error("找不到命题任务，请退出题卡制作！");
    //   return;
    // }
    this.initCard();
    this.registWindowSubmit();
  },
  beforeDestroy() {
    this.$ls.remove("cardId");
    this.$ls.remove("prepareTcPCard");
    delete window.submitCardTemp;
  },
  methods: {
    async initCard() {
      this.dataReady = false;
      if (this.isEdit) {
        await this.getCardTempDetail();
      } else {
        const cardConfig = await this.getCardConfig();
        this.cardContent = {
          pages: [],
          cardConfig,
          paperParams: {},
        };
      }
      this.dataReady = true;
    },
    getCardTitle(titleRule) {
      const fieldMap = {
        courseCode: this.prepareTcPCard.courseCode,
        courseName: this.prepareTcPCard.courseName,
        schoolName: this.prepareTcPCard.schoolName,
      };
      Object.entries(fieldMap).forEach(([key, val]) => {
        titleRule = titleRule.replace("${" + key + "}", val);
      });
      return titleRule;
    },
    async getCardTempDetail() {
      const detData = await cardDetail(this.cardId);

      // 可能存在题卡内容没有记录的情况
      if (detData.content) {
        this.cardContent = JSON.parse(detData.content);
      } else {
        let cardConfig = await this.getCardConfig();
        // 没有题卡内容时，直接创建新的内容
        if (detData.makeMethod === "CUST") {
          this.setCardConfig({ cardTitle: detData.title });
        }

        this.cardContent = {
          pages: [],
          cardConfig,
          paperParams: {},
        };
      }
    },
    async getCardConfig() {
      const data = await cardConfigInfos(this.prepareTcPCard.cardRuleId);
      if (!data) {
        this.$message.error("找不到题卡规则！");
        return;
      }
      let config = {
        ...data,
        ...{
          pageSize: "A3",
          columnNumber: 2,
          columnGap: 20,
          showForbidArea: true,
          cardDesc: "",
          makeMethod: this.prepareTcPCard.makeMethod,
        },
      };
      config.aOrB = true; // 默认开启A/B卷型
      config.requiredFields = JSON.parse(config.requiredFields);
      config.extendFields = JSON.parse(config.extendFields);
      config.cardTitle = this.getCardTitle(config.titleRule);
      return config;
    },
    // 操作
    getRequestConfig() {
      return this.prepareTcPCard.makeMethod === "CUST"
        ? {
            headers: {
              schoolId: this.prepareTcPCard.schoolId,
            },
          }
        : {};
    },
    getCardData(htmlContent = "", model = "") {
      let data = this.$refs.CardFreeDesign.getCardData(htmlContent, model);
      data = {
        ...data,
        type: "CUSTOM",
        ...this.prepareTcPCard,
      };
      if (this.cardId) data.id = this.cardId;
      return data;
    },
    async toPreview(datas) {
      await this.toSave(datas);

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

      this.$refs.CardFreeDesign.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: "CardFreePreview",
        params: {
          cardId: 1,
          viewType: "frame",
        },
      });
      this.cardPreviewUrl = href;
    },
    registWindowSubmit() {
      window.submitCardTemp = async (htmlContent, model) => {
        const datas = this.getCardData(htmlContent, model);
        datas.status = "SUBMIT";
        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>
