<template>
  <el-dialog
    title="WebPOS QR"
    :visible="visible"
    width="320px"
    top="100px"
    :before-close="dialogBeforeClose">
    <div class="qrcode" v-loading="loading" id="webPosQr">
      <el-image class="qr-image" :src="qrcode"/>
    </div>
    <div class="footer">
      <el-button @click="onPrint" type="primary">Print</el-button>
    </div>
  </el-dialog>
</template>

<script>
import api from '@/http/api/charge'
export default {
  name: "WebPosQR",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    item: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      id: "",
      qrcode: "",
      loading: false
    };
  },
  mounted() {
    
  },
  watch: {
    visible: {
      handler(value) {
        if (value) {
          this.$nextTick(() => {
            if (this.id !== this.item.connectorPk) {
              this.loading = true;
              this.getQRCode()
            }
          })
        }
      },
    }
  },
  methods: {
    dialogBeforeClose() {
      this.$emit("hide")
    },
    getQRCode() {
      if (this.item.connectorPk) {
        this.id = this.item.connectorPk;
        api.getWebPosQrCode(this.item.connectorPk).then(res => {
          if (res.data && res.data.base64WebposQr) {
            this.qrcode = res.data.base64WebposQr;
          }
        }).catch(err => {
          this.$message.error(err)
        }).finally(() => {
          this.loading = false;
        })
      }
    },
    onPrint() {
      const contentHtmlString = document.querySelector('#webPosQr').outerHTML;
      let iframe = document.getElementById('print-iframe');
      if (!iframe) {
        iframe = document.createElement('IFRAME')
        iframe.setAttribute('id', 'print-iframe')
        iframe.setAttribute(
          'style',
          'position:absolute;width:0px;height:0px;left:-500px;top:-500px;'
        )
        document.body.appendChild(iframe)
      }
      const doc = iframe.contentWindow.document
      doc.write(contentHtmlString)
      doc.close()
      iframe.contentWindow.focus()
      iframe.contentWindow.print()
      if (navigator.userAgent.indexOf('MSIE') > 0) {
        document.body.removeChild(iframe)
      }
      this.dialogBeforeClose()
    }
  }
}
</script>

<style scoped>
.qrcode {
  display: flex;
  align-items: center;
  justify-content: center;
}
.footer {
  text-align: center;
  padding: 30px 0 0px;
}
.qr-image {
  
}
</style>