<template>
  <div>
    <div :ref="'qrCode' + uuid" class="qrCode" @click="preView" />
    <el-dialog
      :visible.sync="preViewDialogVisable"
      width="500"
      height="500"
      :append-to-body="true"
    >
      <div :ref="'previewQRCode' + uuid" class="previewQRCode" />
    </el-dialog>
  </div>
</template>

<script>
import QRcode from 'qrcodejs2'

const createUUID = (function(uuidRegEx, uuidReplacer) {
  return function() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(uuidRegEx, uuidReplacer).toUpperCase()
  }
})(/[xy]/g, function(c) {
  const r = Math.random() * 16 | 0
  const v = c === 'x' ? r : (r & 3 | 8)
  return v.toString(16)
})

export default {
  props: {
    width: {
      type: Number,
      default: 100
    },
    height: {
      type: Number,
      default: 100
    },
    // 二维码内容
    content: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      uuid: createUUID(),
      // 二维码对象
      qrCode: null,
      // 预览二维码弹出框
      preViewDialogVisable: false,
      // 预览二维码对象
      previewCode: null
    }
  },
  watch: {
    content() {
      this.getQRcode()
    }
  },
  mounted() {
    this.getQRcode()
  },
  methods: {
    getQRcode() {
      if (this.qrCode) {
        // 清除二维码
        this.qrCode.clear()
        this.qrCode = null
        this.$refs['qrCode' + this.uuid].innerHTML = ''
      }
      this.$nextTick(function() {
        this.qrCode = new QRcode(this.$refs['qrCode' + this.uuid], {
          text: this.content,
          width: this.width,
          height: this.height,
          render: 'canvas',
          colorDark: '#000000',
          colorLight: '#ffffff',
          correctLevel: QRcode.CorrectLevel.H
        })
      })
    },
    preView() {
      // 打开弹窗
      this.preViewDialogVisable = true
      if (this.previewCode) {
        // 清除二维码
        this.previewCode.clear()
        this.previewCode = null
        this.$refs['previewQRCode' + this.uuid].innerHTML = ''
      }
      this.$nextTick(function() {
        this.previewCode = new QRcode(this.$refs['previewQRCode' + this.uuid], {
          text: this.content,
          width: 500,
          height: 500,
          render: 'canvas',
          colorDark: '#000000',
          colorLight: '#ffffff',
          correctLevel: QRcode.CorrectLevel.H
        })
      })
    }
  }
}
</script>

<style lang='scss' scoped>
.qrCode {
  text-align: center;
  ::v-deep canvas {
    display: inline-block !important;
  }
  ::v-deep img {
    display: none !important;
  }
}
</style>
<style lang="scss">
.previewQRCode {
  text-align: center;
  canvas {
    display: inline-block !important;
  }
  img {
    display: none !important;
  }
}
</style>
