<template>
  <div>
    <button @click="handleClick">渲染</button>
    <button @click="savePaper">保存</button>
    <iframe v-if="showSketchPage" :src="sketchPageSrc" id="aaaa2" style="width: 100%; height: 500px;"></iframe>
  </div>
</template>

<script>
import HttpResetClass from "vue-client/src/plugins/HttpResetClass";

export default {
  title: 'App',
  data() {
    return {
      inputText: '',
      showSketchPage: false,
      sketchPageSrc: '/sketch',
      sketchId: '',
      title: '',
      paperMessage: ''
    };
  },
  props: {
    row: ''
  },
  async ready() {
    if (this.row) {
      await new HttpResetClass().load('POST', 'rs/sql/tel_singleTable_OrderBy', {
        data: {
          items: 'blob', tablename: 't_blob_sketch', condition: `id  = '${this.row}'`, orderitem: 'id'
        }
      }).then(res => {
        if (res.data.length === 0) {
          this.handleClick()
          return
        }
        try {
          let hex = Buffer.from(res.data[0].blob, 'hex').toString('utf8');
          if (!hex.includes('{')) {
            this.inputText = Buffer.from(hex, 'hex').toString('utf8');
          } else {
            this.inputText = hex;
          }
        } catch (e) {
          this.$showMessage('网络异常请联系管理员')
        }
        this.handleClick()
      })
    }
  },
  methods: {
    handleClick() {
      this.showSketchPage = true;
      this.$nextTick(() => {
        const sketchIframe = document.getElementById('aaaa2');

        window.addEventListener('message', (event) => {
          if (JSON.parse(event.data.param).gadgets.length > 0) {
            this.paperMessage = event.data.param;
          }
        });

        sketchIframe.contentWindow.postMessage(this.inputText, '*');
      })
    },
    savePaper() {
      if (!this.paperMessage) {
        this.$showMessage('请先点击左上角保存图标')
        return
      }
      let param = JSON.parse(this.paperMessage)
      if (!param.title) {
        this.$showMessage('请填写示意图标题')
        return
      }
      let gadgets = param.gadgets
      if (gadgets.length > 0) {
        var jsonString = JSON.stringify(param);
        var reqdata = {
          blob: Buffer.from(jsonString, 'utf8').toString('hex'),
          orgid: this.$login.f.orgid,
          orgname: this.$login.f.orgs,
          title: param.title,
          f_userinfo_id: this.row
        }
        new HttpResetClass().load('POST', 'rs/logic/savePaperEdit', {data: reqdata}).then(res => {
          if (res.data.code === 200) {
            this.$showMessage('保存成功')
          } else {
            this.$showMessage('保存失败')
          }
        })
      }
    },
    hexToBytes(hex) {
      for (var bytes = [], c = 0; c < hex.length; c += 2)
        bytes.push(parseInt(hex.substring(c, 2), 16));
      return new Uint8Array(bytes);
    },
    decodeHexStringToJSON(hexString) {
      // 去除前缀 "0x"
      var cleanHexString = hexString.slice(2);

      // 将十六进制字符串转换为字节数组
      var byteArray = this.hexToBytes(cleanHexString);

      // 创建 Blob 对象
      var blob = new Blob([byteArray], {type: 'application/json'});

      // 读取 Blob 为文本
      return new Promise(function (resolve, reject) {
        var reader = new FileReader();
        reader.onloadend = function () {
          resolve(reader.result);
        };
        reader.onerror = function () {
          reject(reader.error);
        };
        reader.readAsText(blob, 'UTF-8');
      });
    }
  },
  // beforeDestroy() {
  //   this.savePaper()
  // }
}
</script>

<style>
/* 这里可以添加样式 */
</style>
