<template>
  <div class="card-edit">
    <component
      v-if="dataReady"
      :is="editComp"
      ref="CardDesign"
      :content="cardContent"
      :show-save-btn="!IS_GENERIC"
      @on-preview="toPreview"
      @on-save="toSave"
      @on-submit="toSubmit"
      @on-exit="toExit"
    ></component>

    <!-- card-view-frame -->
    <div class="design-preview-frame" v-if="cardPreviewUrl">
      <iframe :src="cardPreviewUrl" frameborder="0"></iframe>
    </div>
    <!-- card-view-dialog -->
    <el-dialog
      class="card-view-dialog"
      :visible.sync="dialogIsShow"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
      fullscreen
      @closed="dialogClosed"
    >
      <iframe
        v-if="dialogIsShow && cardDialogPreviewUrl"
        :src="cardDialogPreviewUrl"
        frameborder="0"
        :style="dialogFrameStyle"
      ></iframe>
    </el-dialog>
  </div>
</template>

<script>
import { cardConfigInfos, cardDetail, saveCard } from "../api";
import CardDesign from "../../../../card/components/CardDesign";
import CardFreeDesign from "../../../../card/modules/free/components/CardFreeDesign";
import { examRuleDetail } from "../../base/api";
import { getEnums } from "../../login/api";

export default {
  name: "card-edit",
  components: {
    CardDesign,
    CardFreeDesign,
  },
  props: {
    isDialog: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      cardId: this.$route.params.cardId || this.$ls.get("cardId"),
      prepareTcPCard: this.$ls.get("prepareTcPCard", {}),
      cardType: "CUSTOM",
      cardCreateMethod: "STANDARD",
      cardContent: {},
      cardName: "", // 题卡自定义名称
      cardPreviewUrl: "",
      canSave: false,
      dataReady: false,
      // card-view-dialog
      dialogIsShow: false,
      cardDialogPreviewUrl: "",
      dialogFrameStyle: {},
    };
  },
  computed: {
    isEdit() {
      return !!this.cardId;
    },
    editComp() {
      return this.cardCreateMethod === "STANDARD"
        ? "card-design"
        : "card-free-design";
    },
    IS_GENERIC() {
      return this.cardType === "GENERIC";
    },
  },
  mounted() {
    this.cardCreateMethod = this.prepareTcPCard.createMethod || "STANDARD";
    this.cardId = this.cardId || this.prepareTcPCard.id;
    this.cardType = this.prepareTcPCard.type || "CUSTOM";
    // if (
    //   !this.prepareTcPCard.examTaskId &&
    //   !this.isEdit &&
    //   this.cardType === "CUSTOM"
    // ) {
    //   this.$message.error("找不到命题任务，请退出题卡制作！");
    //   return;
    // }
    this.initCard();
    this.registWindowSubmit();
    // card-view
    this.initFrameStyle();
    window.addEventListener("resize", this.initFrameStyle);
  },
  methods: {
    initFrameStyle() {
      this.dialogFrameStyle = {
        width: window.innerWidth + "px",
        height: window.innerHeight + "px",
        overflow: "auto",
        border: "none",
        outline: "none",
      };
    },
    async initCard() {
      this.dataReady = false;
      if (this.isEdit) {
        await this.getCardTempDetail();
      } else {
        let cardConfig = await this.getCardConfig();
        if (this.IS_GENERIC) {
          cardConfig.cardTitle = this.prepareTcPCard.title;
        }
        this.cardContent = {
          pages: [],
          cardConfig,
          paperParams: {},
        };
        this.cardName = "";
      }
      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);
        this.cardName = detData.title;
      } else {
        let cardConfig = await this.getCardConfig();
        // 没有题卡内容时，直接创建新的内容
        if (detData.makeMethod === "CUST" || detData.type === "GENERIC") {
          cardConfig.cardTitle = detData.title;
        }
        this.cardContent = {
          pages: [],
          cardConfig,
          paperParams: {},
        };
        this.cardName = "";
      }
    },
    async getCardConfig() {
      if (this.cardCreateMethod === "STANDARD") {
        const data = await cardConfigInfos(this.prepareTcPCard.cardRuleId);
        if (!data) {
          this.$message.error("找不到题卡规则！");
          return Promise.reject();
        }
        let config = {
          ...data,
          ...{
            pageSize: "A3",
            columnNumber: 2,
            columnGap: 20,
            showForbidArea: false,
            cardDesc: "",
            makeMethod: this.prepareTcPCard.makeMethod,
          },
        };
        config.fillNumber = data.examNumberDigit;
        config.aOrB = false; // 默认关闭A/B卷型，2023-01-31改
        config.requiredFields = JSON.parse(config.requiredFields);
        config.extendFields = JSON.parse(config.extendFields);
        config.cardTitle = this.getCardTitle(config.titleRule);
        return config;
      } else {
        let requiredFields = await getEnums("REQUIRED_FIELDS");
        requiredFields = requiredFields
          .filter((item) => item.enable)
          .map((item) => {
            return {
              code: item.code,
              name: item.name,
              enable: item.enable,
            };
          });
        const examRule = await examRuleDetail();
        const extendFields = examRule.extendFields || "[]";
        let config = {
          pageSize: "A3",
          columnNumber: 2,
          columnGap: 20,
          showForbidArea: false,
          cardDesc: "",
          requiredFields,
          extendFields: JSON.parse(extendFields),
        };
        return config;
      }
    },
    // 操作
    getRequestConfig() {
      return this.prepareTcPCard.makeMethod === "CUST"
        ? {
            headers: {
              schoolId: this.prepareTcPCard.schoolId,
            },
          }
        : {};
    },
    getCardInfo(data) {
      let cardInfo = {
        ...data,
        ...this.prepareTcPCard,
        title: this.cardName,
      };
      if (this.cardId) cardInfo.id = this.cardId;
      return cardInfo;
    },
    // card preview dialog
    dialogClosed() {
      this.cardDialogPreviewUrl = "";
    },
    toPreview(cardData) {
      window.cardData = {
        ...cardData,
        createMethod: this.cardCreateMethod,
        type: this.cardType,
      };
      const { href } = this.$router.resolve({
        name: "CardPreview",
        params: {
          cardId: 1,
          viewType: "frame-view",
        },
        query: {
          t: Date.now(),
        },
      });
      this.cardDialogPreviewUrl = href;
      this.dialogIsShow = true;
    },
    // save
    async toSave(datas) {
      if (!this.cardName) {
        const res = await this.$prompt("请输入题卡名称", "提示", {
          type: "warning",
          showInput: true,
          inputPlaceholder: "请输入题卡名称",
          inputValue: this.cardName,
          inputValidator: (val) => {
            if (!val) return "请输入题卡名称！";
            if (val.length > 50) return "题卡名称不得超过50个字符！";
            return true;
          },
        }).catch(() => {});
        if (!res || res.action !== "confirm") {
          this.$refs.CardDesign.unloading();
          return;
        }
        this.cardName = res.value;
      }

      let cardInfo = this.getCardInfo(datas);
      cardInfo.status = "STAGE";
      const result = await saveCard(cardInfo, this.getRequestConfig()).catch(
        () => {}
      );

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

      this.cardId = result;
      this.$ls.set("cardId", this.cardId);
      this.$message.success("保存成功！");
      return this.cardId;
    },
    async toSubmit(cardData) {
      const res = await this.$prompt("确定要提交当前题卡吗?", "提示", {
        type: "warning",
        showInput: true,
        inputPlaceholder: "请输入题卡名称",
        inputValue: this.cardName,
        inputValidator: (val) => {
          if (!val) return "请输入题卡名称！";
          if (val.length > 50) return "题卡名称不得超过50个字符！";
          return true;
        },
      }).catch(() => {});
      if (!res || res.action !== "confirm") return;
      this.cardName = res.value;

      this.$refs.CardDesign.loading();
      window.cardData = {
        ...cardData,
        createMethod: this.cardCreateMethod,
        type: this.cardType,
      };
      const { href } = this.$router.resolve({
        name: "CardPreview",
        params: {
          cardId: 1,
          viewType: "frame",
        },
        query: {
          t: Date.now(),
        },
      });
      this.cardPreviewUrl = href;
    },
    registWindowSubmit() {
      window.submitCardTemp = async (htmlContent, model) => {
        if (!htmlContent || !model) {
          this.$refs.CardDesign.unloading();
          window.cardData = null;
          this.cardPreviewUrl = "";
          this.$message.error("提交失败，请重新尝试！");
          return;
        }
        this.cardPreviewUrl = "";
        const datas = this.$refs.CardDesign.getCardData(htmlContent, model);
        const cardInfo = this.getCardInfo(datas);
        cardInfo.status = "SUBMIT";
        const result = await saveCard(cardInfo, this.getRequestConfig()).catch(
          () => {}
        );
        this.$refs.CardDesign.unloading();
        window.cardData = null;
        if (result) {
          this.cardName = "";
          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(() => {});
    },
    goback() {
      if (this.isDialog) {
        this.$emit("exit", this.cardId);
      } else {
        this.$router.go(-1);
      }
    },
  },
  beforeDestroy() {
    this.$ls.remove("cardId");
    this.$ls.remove("prepareTcPCard");
    window.removeEventListener("resize", this.initFrameStyle);
    delete window.submitCardTemp;
  },
};
</script>
