<template>
  <div class='output-html-container'>

    <slot name="poster"></slot>

    <img src="" class="output-png" id="outputPng" alt="">
  </div>
</template>
<script>
import { getShortLink, uploadPic } from '@apis/common';
import { formatUrl } from '@js/utils';
import html2canvas from 'html2canvas';
const QRious = require('qrious');

export default {
  data() {
    return {};
  },
  props: {
    shareInfo: {
      default: () => {},
    },
    level: {
      default: 'L',
    },
  },
  methods: {
    /**
     * @param {*} extData 额外的数据
     */
    savePNG(extData) {
      // if (!this.shareInfo.clickUrl) {
      //   console.log('分享链接为空');
      //   return;
      // }
      this.$loading('分享图片上传中...');
      return getShortLink(
        formatUrl(this.shareInfo.clickUrl, {
          isPic: 1, // 二维码分享标识
        })
      ).then(data => {
        console.log('shortLink=>' + data);
        const qr = new QRious({
          value: data,
          level: this.level,
          size: 300,
          element: document.getElementById('qrcode'),
        });

        // slot 作用域问题
        return html2canvas(document.getElementById('outputHtml'), {
          useCORS: true,
          // allowTaint: true,
          scale: 4,
        }).then(canvas => {
          let picBase64 = canvas.toDataURL('image/jpeg', 0.3);
          document.getElementById('outputPng').src = picBase64;
          console.log(picBase64.length / 1024, 'size');
          return this.uploadImg(picBase64).then(url => {
            console.log('url=>>' + url);
            this.uploadImgUrl = url;
            this.$loading.close();
            console.log('图片上传结束');
            let data = {
              uploadImgUrl: this.uploadImgUrl,
              extData: extData,
            };
            this.$emit('uploadEnd', data);
            return data;
          });
        });
      });
    },

    uploadImg(data) {
      // this.$loading('上传中');
      return uploadPic(data).then(data => {
        console.log(data);
        return data.url;
      });
    },
  },
};
</script>
<style lang="less" >
.output-html-container {
  position: absolute;
  left: 0;
  top: 0;
}
.output-png {
  position: absolute;
  width: 750px;
  height: 1206px;
  left: -10000px;
  top: -5000px;
  opacity: 0.01;
  pointer-events: all;
  z-index: 1;
}
</style>