<template>
   <view class="pageBgImg">
     <div class="downloadBtn">
       <div class="saveImg" @click="downloadImg()">
         <icon type="download" color="orange" size="40"/>
         <div>保存</div>
       </div>
       <div>
         <van-button type="default" size="large" @click="close()">取消</van-button>
       </div>
     </div>

     <!--合成图片存放地方-->
     <image :src="img" :height="bgH" class="img"></image>
     
     <!--背景-->
     <canvas canvas-id="shareCanvas" :style="'height:'+bgH+'px'" class="canvas"></canvas>
     <!--二维码临时存放地方-->
     <view class="canvas-box">
       <canvas :style="'height:'+codebgH+'px;width:'+codebgW+'px;background:#ffffff;'" canvas-id="mycanvas"/>
     </view>
   </view>
</template>
<script>
//import QR from '../../utils/qrcode.js'
import { checkLogin } from '@/api/login'
import drawQrcode from 'weapp-qrcode'
export default {
  name: 'creatShareImage',
  data() {
    return {
      isLogin: false,
      userId:'',
      bgH:0,
      bgW:0,
      codebgW: 0,
      codebgH: 0,
      logo: '../../static/img/logo-mini.jpg',
      imgUrl: '../../static/img/bgimg.jpg', //图片链接
      codeUrl: 'https://shop.zy-yc.cn/?inviterId=', // 二维码内容用于生成二维码
      //codeUrl: 'https://shop.zy-yc.cn/?inviterId=10002',
      temporarycodeUrl: '', // 二维码临时图片路径
      img: '' // 合成后图片路径
    }
  },
  methods: {
      // 下载
      downloadImg (){
        wx.getImageInfo({
          src: this.img,
          success (res) {
            let path = res.path
            // 保存到相册
            wx.saveImageToPhotosAlbum({
              filePath: path,
              success(res) {
                wx.showToast({
                  title: '图片已经保存到相册中，您可以发送图片给好友',
                  icon: 'none',
                  duration: 5000
                });
              }
            })
          }
        })
      },
      // 取消
      close (){
        wx.navigateBack()
      },
     //点击图片进行预览，长按保存分享图片
      previewImg: function (e) {
        var img = this.img;
        console.log(img);
        wx.previewImage({
          current: img, // 当前显示图片的http链接
          urls: [img] // 需要预览的图片http链接列表
        })
      },
      createQrCode: function (url, canvasId, cavW, cavH, left, top) {
        //调用插件中的draw方法，绘制二维码图片
        //QR.api.draw(url, canvasId, cavW, cavH, this);
        drawQrcode({
          width: cavW,
          height: cavH,
          canvasId: canvasId,
          text: url,
          // v1.0.0+版本支持在二维码上绘制图片
          image: {
            imageResource: this.logo,
            dx: (cavW-30)/2,
            dy: (cavH-30)/2,
            dWidth: 30,
            dHeight: 30
          }
        })
      },
      // 绘制背景海报到canvas//动态设置画布大小
      drawBgImg (){
        const ctx = wx.createCanvasContext('shareCanvas')
        ctx.drawImage(this.imgUrl, 0, 0, this.bgW, this.bgH)
        ctx.draw()
        return ctx
      },
      // 绘制二维码到canvas//动态设置画布大小
      drawCodeImg(){
        let userId = wx.getStorageSync('userId');
        var initUrl = this.codeUrl + userId;
        // 在另一个canvas上生成二维码
        var scale = 1080 / 232;
        var width = this.bgW / scale * 1.4;
        this.codebgW = width
        this.codebgH = width
        this.createQrCode(initUrl, "mycanvas", width, width);
      },
      // 生成合成图片
      creatBg(){
            var res = wx.getSystemInfoSync();
            this.bgW = res.windowWidth
            this.bgH = res.windowHeight
            let ctx = this.drawBgImg()
            this.drawCodeImg()
            var that = this;
            setTimeout(() => {
                //获取临时缓存code照片路径，存入data中
                wx.canvasToTempFilePath({
                  canvasId: 'mycanvas',
                  success: function (data) {
                    var tempFilePath = data.tempFilePath;
                    that.temporarycodeUrl = tempFilePath
                    console.log(tempFilePath)
                    //将临时code图片路径绘制到海报canvas中
                    var res = wx.getSystemInfoSync();
                    var scale = 1080 / 232;
                    var width = res.windowWidth / scale;
                    var height = width
                    var leftscale = 1080 / 170;
                    var left = res.windowWidth / leftscale;
                    var topscale = 1920 / 1590;
                    var top = res.windowHeight / topscale;
                    ctx.drawImage(that.temporarycodeUrl, left, top, width, height)
                    ctx.draw(true,function(){
                      //获取临时缓存合成照片路径，存入data中
                      wx.canvasToTempFilePath({
                        canvasId: 'shareCanvas',
                        success: function (res) {
                          var tempFilePath = res.tempFilePath;
                          that.img = tempFilePath
                        },
                        fail: function (res) {
                          console.log(res);
                        }
                      });
                    })
                  },
                  fail: function (res) {
                    console.log(res);
                  }
                });
            }, 1000);
      }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const _this = this;
    this.userId = wx.getStorageSync('userId');
    console.log(this.userId)
    if(this.userId){
      // 生成合成图片
      _this.creatBg()
    }else{
      wx.navigateTo({
        url: `/pages/login/main?lanuch=false&path=` + encodeURIComponent(`/pages/creatShareImage/main`)
      });
    }
  }
};
</script>

<style lang="stylus">
page,.pageBgImg{
  width: 100%;
  height: 100%;
  position:relative;
  background :#000;
  overflow: hidden;
  margin :0;
  padding :0;
}
.canvas {
  width: 100%;
  height: 100%;
}
.canvas-box{
  position: fixed;
  top:999999rpx;
  left: 0
}
.img {
  position: relative;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index:100;
}

.downloadBtn{
  text-align :center;
  position: absolute;
  width:100%;
  background: #fff;
  bottom:0;
  left:0;
  z-index:10000;
  .saveImg{
    padding: 30rpx 0;
    font-size: 30rpx;
  }
}
</style>
