<template>
  <div class="qrCode-container">
    <u-popup 
      :show="visible" 
      mode="center"
      closeable
      :round="10"
    >
      <view class="qr-code-container-content">
        <view class="qr-code-container-title">{{ title }}</view>
        <canvas 
          canvas-id="QRCodeCanvas"
          :style="`width: ${size}px; height: ${size}px;`"
        ></canvas>
      </view>
    </u-popup>
  </div>
</template>

<script>
import UQRCode from 'uqrcodejs'
let qrCode = null
export default {
  props: {
    qrData: {
      type: String,
      default: ''
    },
    size: {
      type: Number,
      default: 280
    },
    show: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      qrCode: null
    }
  },
  computed: {
    visible: {
      get() {
        return this.show
      },
      set(val) {
        this.$emit('update:show', val)
      }
    }
  },
  methods: {
    initQRCode() {
      if (!this.qrData) return
      this.$nextTick(() => {
        qrCode = new UQRCode()
        qrCode.data = this.qrData
        qrCode.size = this.size
        qrCode.make()
        const canvasContext = uni.createCanvasContext('QRCodeCanvas', this)
        qrCode.canvasContext = canvasContext
        console.log(
          '%c [ qrCode ]-58',
          'font-size:13px; background:#777244; color:#bbb688;',
          qrCode
        )
        qrCode.drawCanvas()
      })
    }
  },
  onLoad() {
    // this.initQRCode()
  },
  beforeDestroy() {
    qrCode?.destroy()
    qrCode = null
  },
  watch: {
    show(val) {
      if (val) {
        this.$nextTick(() => {
          this.initQRCode()
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.qrCode-container {
  .qr-code-container-content {
    text-align: center;
    margin-top: 20px;
    padding: 20rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .qr-code-container-title {
      font-size: 32rpx;
      font-weight: bold;
      margin-bottom: 20rpx;
    }
  }
  
}
</style>show