<template>
  <div class="printExample">
    <Button>
      京东云打印模拟
    </Button>
    <img
      :src="'data:image/jpeg;base64,'+preViewURL"
      alt=""
    >
  </div>
</template>
<script>
  export default {
    components: {},
    data() {
      return {
        preViewURL: ''
      };
    },
    created() {
      this.initWebSocket();
    },
    destroyed() {
      this.websock.close();// 离开路由之后断开websocket连接
    },
    methods: {
      initWebSocket() { // 初始化weosocket(必须)
        const wsuri = 'ws://localhost:9113'; // 请根据实际项目需要进行修改

        this.websock = new WebSocket(wsuri); // 新建一个webstock对象

        this.websock.onmessage = this.websocketonmessage;

        this.websock.onopen = this.websocketonopen;

        this.websock.onerror = this.websocketonerror;

        this.websock.onclose = this.websocketclose;
      },

      websocketonopen() { // websocket连接后发送数据(send发送)
        // 请根据实际项目需要进行修改
        let actions = {
          orderType: 'PRINT', // 1、PRE_View  打印预览  2、GET_Printers 打印列表 3、PRINT  打印
          parameters: {
            printName: 'Microsoft Print to PDF',
            dataType: 'app',
            tradeCode: 'tradeCode',
            offsetTop: '10mm',
            offsetLeft: '10mm',
            tempUrl: 'https://storage.360buyimg.com/print-tmpl/template-3d3a687e-8688-4a9f-be4b-ef7d2f4b4f9d.1616501557056.txt',
            customTempUrl: '',
            printData: ['wiqDBbRQAazRtDwJW1wIhNRTwGs0Okv34LVPS9aHYGeZnigzqgomzi9K550N8PWBYrSx/DYd8mhjMQ8Ds4fQdUuVNcVRAkWDIVPO3NbKbz0Y8m00MuF48JZKyihXi64n82SBHpNeVysSCORNMjSyENsHKPBSk2YCOdVhUiixBy/7jUands9yR7zEzm8Sem4cgGVQeyCFKpm8mMmWm/wtV6VPu3nxvi+2Ap5HDboKMfLs0SupVQC8kfW06MVQep2jTKHdh99AueoNCtf3OmAPejgmk7fDdQ1ZIW3v4gHiBqYGobWekj9qIMkbkTs0NknWnndkV1jpj5Z6EdOunGsJJztLDg1ulhL3miJd12ZJrMy42smDhcZNMyh22gf5D7ULUeBHLQMZCbfY8arnkQB2Jmi6wgS5SzIIqtjg00/5Jr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f+TzQ7f/YP7l8jccli3B+maolPZcDn2KAG2f97YMHnBS48c3Gafw0WdO+or3+04p2ZkCVBfCBkNl182RwUvb/R4cPLE6c1WqgfVCfKQFvnwOQdsDL6ltVTLDxVdTIWMT2OA='],
            customData: [],
            addData: {}
          }
        };
        this.websocketsend(JSON.stringify(actions));
      },

      websocketonerror() { // 连接建立失败重连
        this.initWebSocket();
      },

      websocketonmessage(e) { // 数据接收
        this.redata = JSON.parse(e.data).content;
        if (JSON.parse(e.data).code == 8) {
          this.preViewURL = this.redata;
        }
        console.log(this.redata);
      },

      websocketsend(Data) { // 数据发送
        this.websock.send(Data);
      },

      websocketclose(e) { // 关闭
        console.log('断开连接', e);
      },
    },
  };
</script>
<style lang='less' scoped>
  .printExample {
    padding-top: 100px;
    text-align: center;
  }
</style>
