<template>
  <cr-popup v-model="show" round>
    <div class="max-popup">
      <div class="max-popup__head">
        添加您的专属顾问，享无限次免息
      </div>
      <div class="max-popup__content">
        <cr-image :src="qrcode" width="4.05rem" height="4.05rem" />
        <div class="max-popup__content__desc">微信扫一扫，添加企业微信</div>
      </div>
      <div class="max-popup__foot">
        <cr-button type="primary" shape="circle" block @click="download">
          保存二维码，去激活
        </cr-button>
      </div>
    </div>
    <cr-icon type="close" size="33px" color="#fff" @click="show = false" />
  </cr-popup>
</template>
<script>
import { isApp } from '@/service/validation.service';

export default {
  props: {
    value: Boolean,
    qrcode: String
  },
  data() {
    return {
      show: false
    };
  },
  watch: {
    value(val) {
      this.show = val;
    },
    show(val) {
      this.$emit('input', val);
    }
  },
  methods: {
    download() {
      if (isApp) {
        this.downloadByApp();
      } else {
        this.downloadByH5();
      }
      this.show = false;
    },
    downloadByApp() {
      this.$bridge.run({
        event: 'downloadImgEvent',
        data: {
          imageUrl: this.qrcode
        }
      });
    },
    downloadByH5() {
      let image = new Image();
      // 解决跨域 Canvas 污染问题
      image.setAttribute('crossOrigin', 'anonymous');
      image.onload = function() {
        let canvas = document.createElement('canvas');
        canvas.width = image.width;
        canvas.height = image.height;
        let context = canvas.getContext('2d');
        context.drawImage(image, 0, 0, image.width, image.height);
        let url = canvas.toDataURL('image/png'); //得到图片的base64编码数据
        let a = document.createElement('a'); // 生成一个a元素
        a.download = '微信二维码'; // 设置图片名称
        a.href = url; // 将生成的URL设置为a.href属性
        a.click(); // 触发a的单击事件
      };
      image.src = this.qrcode;
    }
  }
};
</script>
<style lang="less" scoped>
@import './dialog.less';
.max-popup {
  &__content {
    text-align: center;
    padding: @padding-xl - 2 @padding-sm;
    min-height: auto;
  }
}
</style>
