<template>
  <el-dialog
    :title="$t('inspectionPointQrCode.title')"
    :visible.sync="visible"
    width="400px"
    @close="handleClose"
  >
    <div class="qr-container">
      <div ref="qrcode" class="qrcode"></div>
      <div class="point-name">{{ inspectionPointQrCodeInfo.inspectionName }}</div>
      <p class="tip">{{ $t('inspectionPointQrCode.tip') }}</p>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{ $t('common.close') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import QRCode from 'qrcodejs2'

export default {
  name: 'InspectionPointQrCode',
  data() {
    return {
      visible: false,
      inspectionPointQrCodeInfo: {
        url: '',
        inspectionName: ''
      },
      qrCode: null
    }
  },
  methods: {
    open(qrInfo) {
      this.inspectionPointQrCodeInfo = { ...qrInfo }
      this.visible = true
      
      this.$nextTick(() => {
        this.generateQrCode()
      })
    },
    
    handleClose() {
      this.inspectionPointQrCodeInfo = {
        url: '',
        inspectionName: ''
      }
      if (this.qrCode) {
        this.qrCode.clear()
      }
    },
    
    generateQrCode() {
      if (this.qrCode) {
        this.qrCode.clear()
      }
      
      this.qrCode = new QRCode(this.$refs.qrcode, {
        text: this.inspectionPointQrCodeInfo.url,
        width: 200,
        height: 200,
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.L
      })
    }
  },
  beforeDestroy() {
    if (this.qrCode) {
      this.qrCode.clear()
    }
  }
}
</script>

<style scoped>
.qr-container {
  text-align: center;
}

.qrcode {
  display: inline-block;
  margin: 0 auto;
}

.point-name {
  margin-top: 15px;
  font-size: 16px;
  font-weight: bold;
}

.tip {
  margin-top: 10px;
  color: #999;
  font-size: 14px;
}
</style>