<template>
  <el-dialog
    class="formula-dialog"
    :visible.sync="modalIsShow"
    title="公式编辑"
    top="10px"
    width="850px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @opened="initData"
    @closed="closed"
  >
    <div v-if="modalIsShow" class="math-body">
      <iframe
        ref="FormulaFrame"
        :src="iframeSrc"
        frameborder="0"
        width="783"
        height="386"
      ></iframe>
    </div>
    <div slot="footer">
      <el-button type="primary" :disabled="loading" @click="submit"
        >确认</el-button
      >
      <el-button type="danger" plain @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: "FormulaDialog",
  props: {
    imageHandle: {
      type: Function,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      modalIsShow: false,
      iframeSrc: "",
      loading: false,
      // imgRate: 1,
      imgRate: 0.625,
    };
  },
  methods: {
    getFrameUrl() {
      const formulaPath = "kityformula-plugin/kityFormulaDialog.html";
      const rootUrl = window.location.origin;
      const url = `${rootUrl}/admin/${formulaPath}`;

      return url;
    },
    initData() {
      this.iframeSrc = this.getFrameUrl();
      const childFrameObj = this.$refs.FormulaFrame;
      const editor = this.$parent.$parent.$refs.editor;
      childFrameObj.onload = function () {
        this.contentWindow.editor = editor;
      };
    },
    closed() {
      this.iframeSrc = "";
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    base64ToBlob(base64Str) {
      var bytes = atob(base64Str.split(",")[1]);
      let arr = new Uint8Array(bytes.length);
      for (let i = 0; i < bytes.length; i++) {
        arr[i] = bytes.charCodeAt(i);
      }
      return new Blob([arr], { type: "image/png" });
    },
    getFormulaResult() {
      return new Promise((resolve, reject) => {
        const childFrameObj = this.$refs.FormulaFrame;
        const kfe = childFrameObj.contentWindow.kfe;

        try {
          kfe.execCommand("get.image.data", (data) => {
            const latex = kfe.execCommand("get.source");
            if (latex.indexOf("placeholder") > -1) {
              this.modalIsShow = false;
              this.loading = false;
              resolve();
              return;
            }

            const img = document.createElement("img");
            img.src = data.img;
            img.onload = () => {
              resolve({
                dataUrl: data.img,
                latex,
                param: {
                  width: img.width * this.imgRate,
                  height: img.height * this.imgRate,
                },
              });
            };
          });
        } catch (error) {
          reject(error);
        }
      });
    },
    async submit() {
      if (this.loading) return;
      this.loading = true;

      const result = await this.getFormulaResult().catch((error) => {
        console.error(error);
      });
      this.loading = false;

      if (result) {
        this.$emit("confirm", result);
      }
      this.cancel();
    },
  },
};
</script>
