<template>
  <div class="code-container">
    <div class="qrcode">
      <div class="title">{{ name }}正品授权</div>
      <div class="content">
        <img :src="imgUrl" alt="">
      </div>
      <div class="sub-title">{{ qrcodeData.authParty }}</div>
      <div class="btn down-btn" @click="handleDown">下载二维码</div>
      <div class="btn close-btn" @click="handleClose">关闭</div>
    </div>
    <canvas id="canvas" style="display: none" />
    <div v-if="isVisible" class="mask" @click="handleClose" />
    <a id="downloadLink" href="#" style="display: none" />
  </div>
</template>

<script>
import QRCode from 'qrcode'
import downImage from '@/assets/img/qrcode-bg-club-down.png'
import { mapGetters } from 'vuex'
export default {
  name: 'QrcodeClub',
  props: {
    qrcodeData: {
      type: Object,
      default: () => {}
    },
    isVisible: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      imgUrl: '',
      wwwHost: process.env.VUE_APP_WWW_HOST,
      qrcodePath: ''
    }
  },
  computed: {
    ...mapGetters(['authUserId', 'name', 'prefix'])
  },
  created() {
    this.initQrcode()
  },
  methods: {
    // 关闭二维码
    handleClose() {
      this.$emit('close')
    },
    // 下载二维码
    handleDown() {
      this.createDownFile((downCanvas) => {
        // 构造url
        var url = downCanvas.toDataURL('image/jpg')
        // 构造a标签并模拟点击
        var downloadLink = document.getElementById('downloadLink')
        downloadLink.setAttribute('href', url)
        downloadLink.setAttribute('download', '二维码.jpg')
        downloadLink.click()
      })
    },
    // 初始化二维码
    async initQrcode() {
      this.qrcodePath = `${this.wwwHost}/${this.qrcodeData.authUserId}/${this.prefix}/approve/club/detail?id=${this.qrcodeData.authId}`
      // 二维码配置
      const options = {
        width: 192,
        height: 192,
        margin: 1
      }
      try {
        this.imgUrl = await QRCode.toDataURL(this.qrcodePath, options)
      } catch (err) {
        console.error(err)
      }
    },
    // 生成下载的文件
    async createDownFile(callback) {
      this.qrcodePath = `${this.wwwHost}/${this.qrcodeData.authUserId}/${this.prefix}/approve/club/detail?id=${this.qrcodeData.authId}`
      const strHeader = this.name + '正品授权'
      const strFooter = this.qrcodeData.authParty
      // 生成二维码参数信息
      const options = {
        width: 720,
        height: 720,
        margin: 1
      }
      // 生成二维码dataURL
      const downDataURL = await QRCode.toDataURL(this.qrcodePath, options)

      // 设置下载二维码
      const downCanvas = document.getElementById('canvas')
      const downImg = new Image()
      const downBgImg = new Image()
      downImg.src = downDataURL
      downBgImg.src = downImage
      downBgImg.onload = function() {
        // 重新绘制画布
        const w = this.width
        const h = this.height
        downCanvas.width = w
        downCanvas.height = h
        const ctx = downCanvas.getContext('2d')
        // 设置画布背景
        ctx.fillStyle = '#ffffff'
        ctx.fillRect(0, 0, downCanvas.width, downCanvas.height)
        // 设置文字样式
        ctx.fillStyle = '#ffffff'
        ctx.font = 'bold 52px MicrosoftYaHei'
        ctx.textAlign = 'center'
        // 绘制背景
        ctx.drawImage(this, 0, 0)
        // 绘制二维码
        ctx.drawImage(downImg, 185, 342)
        // 绘制顶部文字描述
        const chr1 = strHeader.split('')
        let temp1 = ''
        const row1 = []
        for (let a = 0; a < chr1.length; a++) {
          if (ctx.measureText(temp1).width >= w - 290) {
            row1.push(temp1)
            temp1 = ''
          }
          temp1 += chr1[a]
        }
        row1.push(temp1)
        if (row1.length === 1) {
          ctx.fillText(row1[0], w / 2, 170)
        } else {
          for (let b = 0; b < row1.length; b++) {
            ctx.fillText(row1[b], w / 2, 170 - (row1.length - b - 1) * 65)
          }
        }

        const chr2 = strFooter.split('')
        let temp2 = ''
        const row2 = []
        for (let a = 0; a < chr2.length; a++) {
          if (ctx.measureText(temp2).width >= w - 290) {
            row2.push(temp2)
            temp2 = ''
          }
          temp2 += chr2[a]
        }
        row2.push(temp2)
        if (row2.length === 1) {
          ctx.fillText(row2[0], w / 2, 170 + 1040)
        } else {
          for (let b = 0; b < row2.length; b++) {
            ctx.fillText(row2[b], w / 2, 170 + 1070 - (row2.length - b - 1) * 65)
          }
        }

        // 绘制完成后的回调
        callback(downCanvas)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.code-container {
  position: relative;
  z-index: 999999;
}
.mask {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999998;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.5);
}
.qrcode {
  z-index: 999999;
  position: fixed;
  left: 50%;
  top: 20%;
  transform: translateX(-50%);
  width: 300px;
  height: 400px;
  background: url(../../assets/img/qrcode-bg-club-show.png) no-repeat center;
  .content {
    width: 192px;
    height: 192px;
    position: absolute;
    left: 54px;
    bottom: 85px;
  }
  .down-btn {
    left: 0;
  }
  .close-btn {
    right: 0;
  }
  .title {
    position: absolute;
    top: 30px;
    left: 50%;
    transform: translateX(-50%);
    width: 256px;
    text-align: center;
    font-size: 16px;
    color: #fff;
    font-weight: bold;
  }

  .sub-title {
    position: absolute;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
    width: 256px;
    text-align: center;
    font-size: 16px;
    color: #fff;
    font-weight: bold;
  }
  .sncode {
    position: absolute;
    top: 78px;
    left: 50%;
    transform: translateX(-50%);
    text-align: center;
    width: 192px;
    color: #0e9ef0;
    font-size: 14px;
    span {
      font-weight: bold;
    }
  }
}
.btn {
  position: absolute;
  bottom: -60px;
  width: 108px;
  height: 32px;
  background-image: linear-gradient(-90deg, #50c0ff 0%, #0e90dc 100%);
  border-radius: 4px;
  text-align: center;
  line-height: 32px;
  color: #fff;
  font-size: 14px;
  cursor: pointer;
}
</style>
