<template>
  <el-dialog
    title="Connector QR"
    :visible="visible"
    width="320px"
    top="100px"
    :before-close="dialogBeforeClose">
    <div id="content" class="qrcode" ref="qrCodeUrl"></div>
    <div class="footer">
      <el-button @click="onPrint" type="primary">Print</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import QRCode from 'qrcodejs2'
  export default {
    name: "ConnectorTags",
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      qrCode: {
        type: String,
        default: ""
      }
    },
    data() {
      return {
        qrcode: ""
      };
    },
    mounted() {
      
    },
    watch: {
      qrCode: {
        immediate: true,
        handler(value) {
          if (value) {
            this.$nextTick(() => {
              this.getQRCode()
            })
          }
        },
      }
    },
    methods: {
      dialogBeforeClose() {
        this.$emit("hide")
      },
      getQRCode() {
        if (this.qrcode) {
          this.qrcode.clear()
          this.qrcode.makeCode(this.qrCode)
        } else {
          this.qrcode = new QRCode(this.$refs.qrCodeUrl, {
            text: this.qrCode,
            width: 200,
            height: 200,
            colorDark: '#000000',
            colorLight: '#ffffff',
            correctLevel: QRCode.CorrectLevel.H,
          })
        }
      },
      onPrint() {
        const contentHtmlString = document.querySelector('#content').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 {
  margin: 10px 0;
  display: flex;
  align-items: center;
  justify-content: center;
}
.footer {
  text-align: center;
  padding: 30px 0 0px;
}
</style>