<template>
  <el-dialog
    :title="$t2('二维码', 'components.Qrcode.title')"
    :append-to-body="true"
    :modal-append-to-body="true"
    :close-on-click-modal="false"
    :visible.sync="showDialog"
    :modal="false"
    custom-class="dialog-style list-dialog dialog-checkbox pd_0"
    width="350px"
    height="350px"
    @close="dialogClose"
    v-el-drag-dialog
    v-el-dialog-center
  >
    <div class="cont" style="height: 342px;padding: 0;">
      <Qrcode ref="qrcodeRef" id="myPrint" :qrContent="qrContent" :option="{ width: 342, height: 342 }"/>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" plain class="button-sty" @click="dialogClose">
        <i class="el-icon-close el-icon"></i>
        {{ $t2('取 消', 'system.button.cancel2') }}
      </el-button>
      <el-button type="primary" plain @click="download" class="button-sty">
        <i class="el-icon-download el-icon"></i>
        {{ $t2('下 载', 'system.button.download2') }}
      </el-button>
      <el-button type="primary" plain v-print="printObj" class="button-sty">
        <i class="el-icon-printer el-icon"></i>
        {{ $t2('打 印', 'system.button.print2') }}
      </el-button>
    </span>
  </el-dialog>
</template>

<script>
import {saveFile} from 'vxe-table';

export default {
  name: "printDialog",
  props: {
    qrContent: {
      type: String,
      default: ''
    },
    visiable: {
      type: Boolean
    }
  },
  components: {Qrcode: () => import('../../components/Qrcode/index.vue')},
  data() {
    return {
      showDialog: true,
      printObj: {
        id: 'myPrint', // 这里是要打印元素的ID
        popTitle: '&nbsp', // 打印的标题
        extraCss: '', // 打印可引入外部的一个 css 文件
        extraHead: '',// 打印头部文字
      }
    };
  },
  methods: {
    dialogClose(event) {
      this.$emit('update:visiable', false);
    },
    // base64转化为Blob对象
    convertBase64ToBlob(imageEditorBase64) {
      var base64Arr = imageEditorBase64.split(',');
      var imgtype = '';
      var base64String = '';
      if (base64Arr.length > 1) {
        //如果是图片base64，去掉头信息
        base64String = base64Arr[1];
        imgtype = base64Arr[0].substring(base64Arr[0].indexOf(':') + 1, base64Arr[0].indexOf(';'));
      }
      // 将base64解码
      var bytes = atob(base64String);
      //var bytes = base64;
      var bytesCode = new ArrayBuffer(bytes.length);
      // 转换为类型化数组
      var byteArray = new Uint8Array(bytesCode);

      // 将base64转换为ascii码
      for (var i = 0; i < bytes.length; i++) {
        byteArray[i] = bytes.charCodeAt(i);
      }

      // 生成Blob对象（文件对象）
      return new Blob([bytesCode], {type: imgtype});
    },
    download() {
      let url = this.$refs.qrcodeRef.qrBase64;
      saveFile({
        filename: '二维码',
        type: 'png',
        content: this.convertBase64ToBlob(url)
      });
    }
  }
};
</script>

<style></style>
