// component/shar-dialog/shar-dialog.js
import httpRequestApi from '../../utils/APIClient';
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    shareType: {
      type: 'String',
      value: ''
    },
    shareId: {
      type: 'String',
      value: ''
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    shareFlag: false,
    imgUrls: '',
    avatar: '',
    author: '',
    iconImg: '',
    title: '',
    path: '',
    QRCodeImagePath: '',
    QRCodeImageLocalPath: '',
    activityImg: '',
    groupPurchaseInfo: {},
    groupType: '',
    animationData: {},
    touchMove: true,
    randomSologan: [
      '开发右脑最简单的方式就是大声朗读',
      '大声朗读  有利于建立自信心',
      '大声朗读  能帮助孩子提高写作能力',
      '朗读是感知世界的一种重要方式',
      '增强记忆力的方法之一大声朗读',
      '大声朗读是语感形成的最佳途径',
      '大声朗读  还原课文的诗性美',
      '在朗读中  提升孩子的思辨能力',
      '重温经典课文  享受亲子美好时光',
      '大声朗读  能帮助孩子提高写作能力'
    ],
    shareStep: 'firend',
    activity: ''
  },

  /**
   * 组件的方法列表
   */
  methods: {
    touchMove: function () {
      return false
    },
    poster: function () {
      const that = this;
      wx.showLoading({
        title: '专属海报生成中',
        // mask: true
      })
      httpRequestApi.createQRCode(this.data.QRData).success(res => {
        console.log('----------------->分享二维码222',res.data.data)
        // 下载二维码
        wx.downloadFile({
          url: res.data.data,
          success: res => {
            console.log('----------------->分享二维码',res.tempFilePath)
            this.setData({
              QRCodeImagePath: res.tempFilePath
            }, () => {
              this.saveAvatar();
            })
          }
        });
      })
    },
    makeImage: function () {
      const ctx = wx.createCanvasContext('myCanvas');
      // 画出背景和相同内容
      if(this.data.activity) {
        ctx.drawImage(this.data.activityImg, 0, 0, 1200, 2100, 0, 0, 600, 1050); //插入图片
      } else {
        if (this.data.shareType === 'works') {
          ctx.drawImage('../../static/image/works_poster.jpg', 0, 0, 1200, 2100, 0, 0, 600, 1050); //插入图片
        } else {
          ctx.drawImage('../../static/image/group_poster.jpg', 0, 0, 1200, 2100, 0, 0, 600, 1050); //插入图片
        }
      }
      if (this.data.activity) {
        ctx.save()
        ctx.arc(49, 50, 29, 0, 2 * Math.PI, true)
        ctx.clip(); //剪切头像区域
        ctx.drawImage(this.data.avatar, 20, 20, 61, 61);
        ctx.clip(); //剪切头像区域
        ctx.restore();
        ctx.font = 'normal bold 14px'
        // ctx.setFontSize(14)
        // ctx.setFontWeight(500)
        ctx.setFillStyle('#198165')
        ctx.fillText(this.data.author, 82, 49)
        ctx.restore();
        ctx.setFontSize(16)
        ctx.setFillStyle('#434343')
        ctx.fillText(`《${this.data.title}》`, (300 - ctx.measureText(`《${this.data.title}》`).width) / 2, 285)
        // 二维码
        ctx.drawImage(this.data.QRCodeImagePath, 104, 299, 92, 92);
        ctx.draw();
      } else {
        ctx.save()
        ctx.beginPath()
        ctx.fill()
        ctx.setFontSize(25)
        ctx.setFillStyle('#fff')
        ctx.fillText('课文朗读 每天5分钟', (300 - ctx.measureText('课文朗读 每天5分钟').width) / 2, 54.5)
        ctx.setFontSize(16)
        let randomSologan = this.data.randomSologan[Math.floor(Math.random() * 10)];
        ctx.fillText(randomSologan, (300 - ctx.measureText(randomSologan).width) / 2, 75.5)
        ctx.setFontSize(15)
        ctx.setFillStyle('#838383')
        ctx.fillText('长按识别二维码', 130.5, 391)
        ctx.setFontSize(12)
        ctx.setFillStyle('#838383')
        ctx.fillText('接收邀请，获得你的课程吧', 130.5, 409.5) /*  */
        // 头像
        console.log('画头像')
        if (this.data.shareType === 'works') {
          ctx.arc(150, 160, 36, 0, 2 * Math.PI, true)
          ctx.clip(); //剪切头像区域
          ctx.drawImage(this.data.avatar, 116, 126, 68, 68);
          ctx.arc(150, 160, 34, 0, 2 * Math.PI, false)
          ctx.setFillStyle('#ff6f42')
          ctx.fill();
          ctx.clip(); //剪切头像区域
          ctx.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 可以继续绘制
          ctx.setFontSize(15)
          ctx.setFillStyle('#ff6f42')
          ctx.fillText(this.data.author, (300 - ctx.measureText(this.data.author).width) / 2, 220)
          ctx.setFillStyle('#434343')
          ctx.fillText('播音主持特长生', (300 - ctx.measureText('播音主持特长生').width) / 2, 243)
          ctx.setFontSize(15)
          ctx.setFillStyle('#434343')
          ctx.fillText('使出洪荒之力，声情并茂地朗诵了', (300 - ctx.measureText('使出洪荒之力，声情并茂地朗诵了').width) / 2, 262)
          ctx.fillText(`《${this.data.title}》`, (300 - ctx.measureText(`《${this.data.title}》`).width) / 2, 284)
        } else {
          ctx.arc(64, 146, 29, 0, 2 * Math.PI, true)
          ctx.clip(); //剪切头像区域
          ctx.drawImage(this.data.avatar, 37, 119, 54, 54);
          ctx.arc(64, 146, 27, 0, 2 * Math.PI, false)
          ctx.setFillStyle('#ff6f42')
          ctx.fill();
          ctx.clip(); //剪切头像区域
          //插入图片
          ctx.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 可以继续绘制
          ctx.setFontSize(18)
          ctx.setFillStyle('#ff6f42')
          ctx.fillText(this.data.author, 100, 143.5)
          ctx.setFontSize(16)
          ctx.setFillStyle('#434343')
          ctx.fillText('邀您和我一起大声朗读', 100, 167.5)
          ctx.drawImage(this.data.iconImg, 27, 194, 247, 103.5);
          ctx.setFontSize(15)
          ctx.setFillStyle('#434343')
          ctx.fillText('朗朗读书声，是世界上最美妙的声音', (300 - ctx.measureText('朗朗读书声，是世界上最美妙的声音').width) / 2, 327.5)
        }
        console.log('花二维码')
        console.log(this.data)
        console.log(this.data.avatar)
        ctx.drawImage(this.data.QRCodeImagePath, 35, 351, 90, 90);
        ctx.draw();
      }

      setTimeout(() => {
        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          width: 300,
          height: 525,
          destWidth: 1200,
          destHeight: 2100,
          canvasId: 'myCanvas',
          success: (res) => {
            this.setData({
              imgUrls: res.tempFilePath
            })
            wx.hideLoading()
          },
          fail: (res) => {
            console.log('史称失败', res)
            wx.hideLoading();
          }
        })
      }, 400)

    },
    saveIcon: function () {
      wx.downloadFile({
        url: this.data.iconImg,
        success: res => {
          this.setData({
            iconImg: res.tempFilePath
          }, () => {
            console.log(this.data.iconImg)
            this.makeImage();
          })
        }
      });
    },
    /** 需要优化 */
    saveAvatar: function () {
      wx.downloadFile({
        url: this.data.avatar,
        success: res => {
          this.setData({
            avatar: res.tempFilePath
          }, () => {
            wx.downloadFile({
              url: 'https://reader-wx.ai160.com/images/reader/activity/activity_bg.jpg',
              success: res => {
                this.setData({
                  activityImg: res.tempFilePath
                }, () => {
                  if (this.data.shareType === 'group') {
                    this.saveIcon();
                  } else {
                    this.makeImage();
                  }
                })
              }
            })
          })
        }
      });
    },
    share: function (data) {
      console.log('分享内容', data)
      if (this.data.shareType === 'works') {

        this.setData({
          shareFlag: !this.data.shareFlag,
          avatar: data.avatar,
          author: data.author,
          iconImg: data.iconImg,
          title: data.title,
          productId: data.productId,
          id: data.scene,
          type: data.type,
          grade: data.grade,
          shareImg: data.shareImg,
          shareStep: 'firend',
          shareIndex: data.index,
          activity: data.activity,
          QRData: {
            page: data.path,
            scene: data.scene
          }
        })
      }
      if (this.data.shareType === 'group') {
        console.log(data)
        console.log('团购分享')
        this.setData({
          shareFlag: !this.data.shareFlag,
          avatar: data.avatar,
          author: data.author,
          iconImg: data.iconImg,
          title: data.title,
          // path: data.path,
          QRData: {
            page: data.path,
            scene: data.scene
          },
          groupPurchaseInfo: data.groupPurchaseInfo,
          groupType: data.groupType
        })
      }
      if (this.data.shareType === 'class') {
        console.log('课程分享')
        this.setData({
          shareFlag: !this.data.shareFlag
        })
      }
      // 动画测试
      this.animation = wx.createAnimation({
        duration: 700,
        timingFunction: 'ease',
      })
      this.animation.bottom(0).step();
      this.setData({
        animationData: this.animation.export()
      })
      // 动画测试
      // this.poster();
    },
    //关闭弹框
    close: function (e) {
      this.animation = wx.createAnimation({
        duration: 400,
        timingFunction: 'ease',
      })
      this.animation.bottom(-300).step();
      this.setData({
        animationData: this.animation.export()
      }, () => {
        setTimeout(() => {
          this.setData({
            shareFlag: !this.data.shareFlag,
            imgUrls: ''
          })
          this.triggerEvent('ShareDialogClose', {})
        }, 200)
      })
      wx.hideLoading()
    },
    nothing: function (e) {
      return
    },
    // 保存最终图片
    PreservationImg: function () {
      // this.getImgAuthorize()
      wx.saveImageToPhotosAlbum({
        filePath: this.data.imgUrls,
        success: (res) => {
          wx.showModal({
            title: '海报已保存至相册',
            content: '快去分享给小伙伴吧',
            confirmText: '我知道了',
            showCancel: false,
            success: (res) => {
              console.log('用户点击确定')
              this.close();
              httpRequestApi.shareImgLog({
                readId: this.data.id,
              }).success((oRes) => {
                this.triggerEvent('addShareAmount', {
                  index:this.data.shareIndex
                })
                setTimeout(() => {
                  if (oRes.data.count > 0) {
                    this.setData({
                      flowerNum: oRes.data.count
                    })
                    this.flowerAnimationHandler();
                  }
                }, 500)
              })
            }
          })

          this.setData({
            imgUrls: false
          })
        },
        fail: res => {
          wx.getSetting({
            success(res) {
              if (!res.authSetting['scope.writePhotosAlbum']) {
                // wx.showToast({
                //   title: '无权限操作',
                //   icon: 'fail',
                //   duration: 800
                // })
                wx.showModal({
                  title: '无法保存分享图片到相册',
                  content: '点击右上角浮点按钮->设置，进行授权',
                  confirmText: '我知道了',
                  showCancel: false,
                  success(res) {
                    console.log('用户点击确定')
                  }
                })
              }
            }
          })
        }
      })
    },
    shareFriend: function () {
      this.setData({
        shareStep: 'circle'
      })
      this.poster();
      httpRequestApi.shareLog({
        readId: this.data.id,
        type: this.data.type,
        grade: this.data.grade
      }).success((res) => {
        console.log('分享记录', res)
        if (res.data.count > 0) {
          this.setData({
            flowerNum: res.data.count,
          }, () => {
            // this.flowerAnimationHandler();
          })
        }
        this.triggerEvent('addShareAmount', {
          index:this.data.shareIndex
        })
      })
    },
    flowerAnimationHandler: function () {
      this.flowerBox = this.selectComponent("#flower-toast");
      console.log('this.flower', this.flowerBox)
      this.flowerBox.comeOut();
    },
  },
  onShareAppMessage: (e) => {
    console.log('点击分享按钮', e)
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    } else {
      return {
        title: '课文朗读，从未如此有趣。',
        path: '/pages/index/index'
      }
    }
  }
})
