<template></template>
<script>
import QRCode from './qrcode.js'

const VueQRCode = {
  name: 'Qrcode',
  props: {
    tag: {
      type: String,
      default: 'div'
    },
    text: {
      type: String,
      required: true
    },
    size: {
      type: Number,
      default: 256
    },
    colorLight: {
      type: String,
      default: '#ffffff'
    },
    colorDark: {
      type: String,
      default: '#000000'
    },
    logo: String,
    logoSize: Number,
    tips: Array,
    fontSize: {
      type: Number,
      default: 14
    },
    correctLevel: {
      type: Number,
      default: 2
    },
    /**
     * [padding 边框]
     * @type {[type]}
     */
    padding:{
      type:Number,
      default:0
    }
  },
  mounted() {
    this.update()
  },

  destroyed() {
    this.$qrcode.clear()
  },

  watch: {
    text() {
      this.makeCode()
    },
    size(val) {
      this.update()
    },
    colorLight(val) {
      this.$qrcode._htOption.colorLight = val
      this.makeCode()
    },
    colorDark(val) {
      this.$qrcode._htOption.colorDark = val
      this.makeCode()
    }
  },

  methods: {
    update() {
      const $el = this.$el
      const $logo = this.$refs.logo
      while ($el && $logo && $el.childNodes.length && $el.lastChild !== $logo) {
        $el.removeChild($el.lastChild)
      }

      if (this.$qrcode) {
        this.$qrcode.clear()
      }

      const options = this._props

      options.width = options.height = this.size
      options.padding = this.padding
      this.$qrcode = new QRCode(this.$el, options)
    },

    makeCode(text) {
      this.$qrcode.clear()
      this.$qrcode.makeCode(text || this.text)
    }
  }
}

export default VueQRCode
</script>
