let Parse = getApp().Parse;
let company = getApp().globalData.company
Page({

  /**
   * 页面的初始数据
   */
  data: {
    noBind:false //不绑定关系
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    console.log(options);
    let {
      path,
      sx,
      sy,
      cColor,
      bColor,
      noBind,
      route //扫码携带路径
    } = options
    let userId = Parse.User.current().id
    let imgUrl = await this.loadPoster() || 'https://file-cloud.fmode.cn/L3xHgXbTHJ/20230814/vod1h4054437092.png'
    this.setData({
      imgUrl,
      path,
      sx,
      sy,
      noBind,
      route
    });
    const _this = this
    let qrCodeUrl = `https://pwa.fmode.cn/gomini/${path}/?invite=${userId}`;
    if(this.data.noBind){
      qrCodeUrl = `https://pwa.fmode.cn/gomini/${path}/`;
    }
    if(route){
      if(this.data.noBind){
        qrCodeUrl = qrCodeUrl+`?route=${route}`
      }else{
        qrCodeUrl = qrCodeUrl+`&route=${route}`
      }
    }
    console.log(qrCodeUrl);
    wx.request({
      url: "https://server.fmode.cn/api/common/qrcode",
      data: {
        qrCode: qrCodeUrl,
        darkColor: bColor || "#ffffff",
        lightColor: cColor || "#000000"
      },
      async success(res) {
        if (res.data.code == 1) {
          let that = this;
          //把base64文件转图片
          let fileSystemManager = wx.getFileSystemManager()
          fileSystemManager.writeFile({
            filePath: wx.env.USER_DATA_PATH + '/qr_code.png',
            data: res.data.data.slice(22),
            encoding: 'base64',
            success: res => {
              _this.setData({
                xcxcode: wx.env.USER_DATA_PATH + '/qr_code.png'
              })
              _this.drawOne()
            },
            fail(e) {
              console.log('文件保存失败', e)
            }
          })
        } else {
          wx.showToast({
            title: '请先删除小程序重新授权后重试',
            icon: 'none'
          })
        }
      },
    });
  },

  //获取海报图片
  async loadPoster() {
    let Poster = new Parse.Query('Banner')
    Poster.equalTo('company', company)
    Poster.equalTo('desc', 'invite')
    Poster.ascending('index')
    let poster = await Poster.first()
    if(poster?.id){
      return poster.get('image')
    }
    return
  },

  async drawOne() {
    let { sx, sy } = this.data
    let that = this
    let imgPath = that.data.imgUrl; //背景图片;
    let avatar = Parse.User.current()?.get('avatar')
    let balance = await this.getImageInfo(imgPath)
    let userAvatar = await this.getImageInfo(avatar)

    let xcxcode = that.data.xcxcode; //二维码
    const ctx = wx.createCanvasContext('myCanvas');
    //填充背景(图片的白色背景)
    ctx.setFillStyle('#ffffff');
    ctx.fillRect(0, 0, 375, 596); //坐标和宽高
    ctx.fillRect(0, 0, 338, 480); //坐标和宽高
    // 第一张图片(背景图片)
    if(company != 'UP2cStyjuk')  ctx.drawImage(balance, 0, 0, 340, 540);
    userAvatar && ctx.drawImage(userAvatar, 126 , 100, 80, 80);
    //绘制二维码
    ctx.drawImage(xcxcode, sx ? sx : 70 , sy ? sy : 250, 200, 200);
    ctx.draw();
   
  },

  getImageInfo(url){
    return new Promise((result)=>{
      wx.getImageInfo({
        src: url, //服务器返回的图片地址
        success: function (res) {
          // res.path是网络图片的本地地址
          let Path = res.path;
          result(Path)
        },
        fail(err) {
          console.log(err);
          result()
        }
      });
    })
  },

  // 保存图片
  savetup: function () {
    let that = this;
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: 750,
      height: 1334,
      destWidth: 750,
      destHeight: 1334,
      canvasId: 'myCanvas',
      success: function (result) {
        wx.getSetting({
          success(res) {
            if (!res.authSetting['scope.writePhotosAlbum']) {
              wx.authorize({
                scope: 'scope.writePhotosAlbum',
                success() {
                  //这里是用户同意授权后的回调
                  // that.saveImgToLocal();
                  wx.saveImageToPhotosAlbum({
                    filePath: result.tempFilePath,
                    success(res) {
                      wx.showModal({
                        title: '图片保存成功!',
                        content: '请将图片分享到朋友圈',
                        showCancel: false,
                        confirmText: '知道了',
                        confirmColor: '#72B9C3',
                        success: function (res) {
                          if (res.confirm) {
                            console.log('用户点击确定');
                            that.setData({
                              show: false
                            })
                          }
                        }
                      })
                    }
                  })
                },
                fail() { //这里是用户拒绝授权后的回调
                  wx.showToast({
                    title: '打开相册授权,才能保存二维码哦~',
                    icon: 'none',
                    duration: 2000
                  })
                  that.setData({
                    openSettingBtnHidden: false
                  })
                }
              })
            } else {
              //调取小程序当中获取图片
              console.log(result.tempFilePath);
              wx.saveImageToPhotosAlbum({
                filePath: result.tempFilePath,
                success(res) {
                  wx.showModal({
                    title: '图片保存成功!',
                    content: '请将图片分享到朋友圈',
                    showCancel: false,
                    confirmText: '知道了',
                    confirmColor: '#72B9C3',
                    success: function (res) {
                      if (res.confirm) {
                        console.log('用户点击确定');
                        that.setData({
                          show: false
                        })
                      }
                    }
                  })
                }
              })
            }
          }
        })

      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  onCopy() {
    let id = Parse.User.current().id;
    let url = 'https://server.fmode.cn/api/wxapp/wechat/urlLink'
    let query = `invite=${id}`
    if(this.data.noBind) {
      query = ``
    }
    wx.request({
      url: url,
      data: {
        company: company,
        path: 'index',
        query: query,
      },
      header: {
        'content-type': 'application/json'
      },
      method: 'POST',
      dataType: 'json',
      responseType: 'text',
      success: (result) => {
        console.log(result);
        if (result ?.data ?.url_link) {
          let path = result.data.url_link
          wx.setClipboardData({
            data: path,
            success: function (res) {
              wx.getClipboardData({
                success: function (res) {
                  wx.showToast({
                    title: '复制成功',
                  })
                  // console.log(res.data) // data
                }
              })
            }
          })
          return
        }
        wx.showToast({
          title: '复制错误',
          icon: 'error',
          image: '',
          duration: 1500,
          mask: false,
        });
      },
      fail: () => {},
      complete: () => {}
    });
  },

  onShareTimeline() {
    console.log(123)
    return {
      title: '发送朋友圈',
      query: '',
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let uid = Parse.User.current().id
    let path = `index?invite=${uid}`
    if(this.data.noBind) {
      path = 'index'
    }
    if(this.data.route){
      if(this.data.noBind){
        qrCodeUrl = qrCodeUrl+`?route=${this.data.route}`
      }else{
        qrCodeUrl = qrCodeUrl+`&route=${this.data.route}`
      }
    }
    return {
      title: '邀请好友',
      path: path,
      imageUrl: '',
    }
  }
})