<template>
  <div class="paper-template-edit card-edit">
    <paper-template-design
      v-if="dataReady"
      ref="PaperTemplateDesign"
      :content="tempContent"
      @on-preview="toPreview"
      @on-submit="toSubmit"
      @on-exit="toExit"
    ></paper-template-design>
  </div>
</template>

<script>
import { savePaperTemplateApi } from "../api";
import PaperTemplateDesign from "../components/PaperTemplateDesign.vue";
export default {
  name: "PaperTemplateEdit",
  components: {
    PaperTemplateDesign,
  },
  data() {
    return {
      tempContent: {},
      dataReady: false,
      paperTempInfo: {},
    };
  },
  mounted() {
    this.initData();
  },
  methods: {
    async initData() {
      let paperTempInfo = window.sessionStorage.getItem("paperTempInfo");
      if (!paperTempInfo) {
        this.$message.error("数据丢失，请退出编辑页面！");
        return;
      }
      this.paperTempInfo = JSON.parse(paperTempInfo);
      this.dataReady = false;
      if (this.paperTempInfo.id) {
        const content = this.paperTempInfo.content
          ? JSON.parse(this.paperTempInfo.content)
          : { pages: [] };
        this.tempContent = content;
      } else {
        this.tempContent = {
          pages: [],
        };
      }
      this.dataReady = true;
    },
    // 操作
    async toPreview(paperTempData) {
      const result = await this.toSave(paperTempData).catch(() => {});
      if (!result) {
        this.$message.error("保存失败");
      }

      const { href } = this.$router.resolve({
        name: "PaperTemplatePreview",
        params: {
          tid: this.tid,
          viewType: "view",
        },
      });
      window.open(href);
    },
    // save
    async toSave(paperTempData) {
      this.$refs.PaperTemplateDesign.loading();

      let datas = {
        id: this.paperTempInfo.id,
        name: this.paperTempInfo.name,
        type: this.paperTempInfo.type,
        content: JSON.stringify(paperTempData),
        pageSize: paperTempData.pages[0].pageSize,
      };
      let result = await savePaperTemplateApi(datas).catch(() => {});
      this.$refs.PaperTemplateDesign.unloading();
      if (!result) return Promise.reject("保存失败");
      this.tid = result.data;
      return Promise.resolve("保存成功！");
    },
    async toSubmit(paperTempData) {
      const result = await this.toSave(paperTempData).catch((e) => {
        console.dir(e);
      });
      if (result) {
        this.$message.success("提交成功！");
        this.goback();
      } else {
        this.$message.error("提交失败，请重新尝试！");
      }
    },
    toExit() {
      this.$confirm(
        "请确保当前模板已经正常保存，确定要退出当前模板编辑吗?",
        "提示",
        {
          type: "warning",
        }
      )
        .then(() => {
          this.goback();
        })
        .catch(() => {});
    },
  },
};
</script>
