<template>
  <div>
    <!-- 二维码弹框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="450px">
      <div style="text-align: center" ref="codeBox">
        <div class="uploadImg">
          <div id="qrcode" class="qrcode" ref="codeItem"></div>
        </div>
        <div class="boxCode">编号：{{ code }}</div>
      </div>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="downloadCode">下 载</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import QRCode from 'qrcodejs2'
import html2canvas from 'html2canvas'

export default {
  data() {
    return {
      dialogTitle: '查看', // 弹框标题
      dialogVisible: false, // 弹框显示状态
      qrcodeValue: '', // 二维码内容
      code: ''
    }
  },
  created() {},
  methods: {
    showQRCode(qrCode, code) {
      console.log('🚀 ~ showQRCode ~ qrCode:', qrCode)
      this.qrcodeValue = '' // 清空之前的二维码内容
      this.dialogTitle = '查看'
      this.dialogVisible = true
      this.qrcodeValue = qrCode
      this.code = code

      this.$nextTick(() => {
        this.$refs.codeItem.innerHTML = ''
        var qrcode = new QRCode(this.$refs.codeItem, {
          text: qrCode, //二维码内容
          width: 256,
          height: 256,
          colorDark: '#000000',
          colorLight: '#ffffff',
          correctLevel: QRCode.CorrectLevel.H
        })
      }, 500)
    },
    //二维码下载
    downloadCode(e) {
      if (document.getElementById('qrcode').childNodes[0]) {
        let element = this.$refs.codeBox
        html2canvas(element).then(canvas => {
          // 将canvas转换为图片URL
          const image = canvas.toDataURL('image/png')
          const alink = document.createElement('a')
          alink.href = image
          alink.download = this.qrcodeValue
          alink.click()
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.uploadImg {
  padding-top: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.boxCode {
  margin-top: 10px;
  padding-bottom: 20px;
  font-size: 18px;
}
</style>
