// nova-tourism/pages/my/sharing/index.js
let {
  statusBarHeight,
  screenHeight
} = wx.getSystemInfoSync()
let custom = wx.getMenuButtonBoundingClientRect()
let customHeight = custom.height
let Parse = getApp().Parse;
let company = getApp().globalData.company

Page({

  /**
   * 页面的初始数据
   */
  data: {
    navHeight: 0, //导航高度_px

    canv_sty: {
      w: 0,
      h: 0,
    },
    canv_bg: 'https://file-cloud.fmode.cn/EbxZUK5lBI/20250416/pj1b4v042627175.png',
    canv_qr: '',
    canv_avatar: 'https://file-cloud.fmode.cn/EbxZUK5lBI/20250411/frvr1u080411965.jpg?imageView2/1/w/200/h/200',
    canv_name: '微信用户',
    canv_uid: '',
    canv_tag: '云仙客',
    canvas: null, //画布-下载所需

    noBind: false, //不绑定关系
    qrCodeUrl: '', //二维码原文
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let navHeight = statusBarHeight + customHeight + 10
    let canv_sty = {
      w: screenHeight * 0.38 - 2,
      h: screenHeight * 0.60
    }
    this.setData({
      navHeight,
      canv_sty
    })
    console.log(options);
    let {
      path,
      noBind,
      route, //扫码携带路径
      uid
    } = options
    this.setData({
      path,
      noBind,
      route,
      uid
    });
    let qrCodeUrl = `https://pwa.fmode.cn/gomini/${path}/?invite=${uid}`;
    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);
    this.setData({
      qrCodeUrl
    })

    this.refersh()
  },

  async refersh() {
    let {
      uid,
      canv_avatar,
      canv_name,
      canv_uid,
      canv_tag,
    } = this.data
    if (!uid) {
      wx.showToast({
        title: 'UID错误',
        icon: 'error'
      })
      return
    }
    let query = new Parse.Query('_User')
    let u = await query.get(uid)
    canv_avatar = u?.get('avatar') || 'https://file-cloud.fmode.cn/EbxZUK5lBI/20250411/frvr1u080411965.jpg?imageView2/1/w/200/h/200'
    canv_name = u?.get('nickname') || '微信用户'
    canv_uid = uid
    canv_tag = '云仙客'
    if (u?.get('type') == 'shop-admin') {
      let s_query = new Parse.Query('ShopStore')
      s_query.equalTo('company', company);
      s_query.equalTo('user', uid);
      s_query.equalTo('isVerified', true);
      s_query.notEqualTo('isDeleted', true);
      let s = await s_query.first()
      if (!s?.id) {
        wx.showToast({
          title: '暂无营业店铺',
          icon: 'error'
        })
        return
      }
      canv_avatar = s?.get('cover') || 'https://file-cloud.fmode.cn/EbxZUK5lBI/20250411/frvr1u080411965.jpg?imageView2/1/w/200/h/200'
      canv_name = u?.get('username') || '微信用户'
      canv_tag = '民宿主'
    }
    this.setData({
      canv_avatar,
      canv_name,
      canv_uid,
      canv_tag,
    })

    this.getQr()
  },

  /**获取二维码 */
  async getQr() {
    let {
      qrCodeUrl
    } = this.data
    let that = this;
    wx.request({
      url: "https://server.fmode.cn/api/common/qrcode",
      data: {
        qrCode: qrCodeUrl,
        darkColor: "#000",
        lightColor: "#fff"
      },
      async success(res) {
        console.log(res)
        if (res.data.code == 1) {
          that.setData({
            canv_qr: res?.data.data
          })
          that.draw()
        } else {
          wx.showToast({
            title: '请先删除小程序重新授权后重试',
            icon: 'none'
          })
        }
      },
    });
  },
  /**复制链接 */
  onCopy() {
    let {
      uid
    } = this.data
    if (!uid) {
      wx.showToast({
        title: 'UID为空，请退出重试',
        icon: 'none'
      })
      return
    }
    let url = 'https://server.fmode.cn/api/wxapp/wechat/urlLink'
    let query = `invite=${uid}`
    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: '复制成功',
                  })
                }
              })
            }
          })
          return
        }
        wx.showToast({
          title: '复制错误',
          icon: 'error',
          image: '',
          duration: 1500,
          mask: false,
        });
      },
      fail: () => {},
      complete: () => {}
    });
  },

  /**保存图片 */
  saveCanvas() {
    let {
      canvas
    } = this.data
    let that = this
    wx.canvasToTempFilePath({
      canvas: canvas,
      success(res) {
        that.setData({
          saveimage: res.tempFilePath
        })
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: (res) => {
            wx.showToast({
              title: '已下载图片',
              icon: 'none'
            })
          },
          fail: (err) => {
            // console.log('err',err)
          }
        })
      },
      fail: (err) => {
        console.log(err)
      }
    })
  },

  /**绘制canvas */
  draw() {
    let {
      canv_bg,
      canv_qr,
      canv_avatar,
      canv_name,
      canv_uid,
      canv_tag,
    } = this.data
    let that = this
    wx.createSelectorQuery()
      .select('#myCanvas')
      .fields({
        node: true,
        size: true
      })
      .exec((res) => {
        const canvas = res[0].node
        const ctx = canvas.getContext('2d')
        const width = res[0].width
        const height = res[0].height
        // 初始化画布大小
        const dpr = wx.getWindowInfo().pixelRatio
        canvas.width = width * dpr
        canvas.height = height * dpr
        ctx.scale(dpr, dpr)
        ctx.clearRect(0, 0, width, height)
        //========背景=====
        let bg = canvas.createImage()
        bg.onload = () => {
          ctx.drawImage(bg, 0, 0, width, height)
          //========头像=========
          let x = width * 0.06
          let y = width * 0.06
          let w = width * 0.25
          let h = width * 0.25
          let avatar = canvas.createImage();
          avatar.onload = () => {
            ctx.save();
            let r = 10
            ctx.beginPath()
            ctx.moveTo(x + r, y)
            ctx.arcTo(x + w, y, x + w, y + h, r)
            ctx.arcTo(x + w, y + h, x, y + h, r)
            ctx.arcTo(x, y + h, x, y, r)
            ctx.arcTo(x, y, x + w, y, r)
            ctx.closePath()
            ctx.clip()
            ctx.drawImage(avatar, x, y, w, h)
            ctx.restore()
            ctx.draw()
          }
          avatar.src = canv_avatar
          //========文字========
          // ctx.fillStyle = '#4F9AF7';
          ctx.font = `${h*0.25}px bold Arial`;
          ctx.fillText(canv_name, x + w + 8, y + (h * 0.36));
          ctx.font = `${h*0.15}px Arial`;
          ctx.fillText(`UID:${canv_uid}`, x + w + 8, y + (h * 0.63));
          // 标签
          let tag = canvas.createImage()
          tag.onload = () => {
            ctx.drawImage(tag, x + w + 8, y + (h * 0.7), h * 0.36+6, h * 0.21)
            ctx.fillStyle = '#fff';
            ctx.font = `${h*0.12}px bold Arial`;
            ctx.fillText(canv_tag, x + w + 8+3, y + (h * 0.85));
          }
          tag.src = 'https://file-cloud.fmode.cn/EbxZUK5lBI/20250418/f1d8n1042110554.png'

          //二维码
          let qr = canvas.createImage()
          qr.onload = () => {
            ctx.drawImage(qr, width * 0.25, height * 0.5, width * 0.5, width * 0.5)
          }
          qr.src = canv_qr
        }
        bg.src = canv_bg
        that.setData({
          canvas
        })
      })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

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

  },

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

  },

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

  },

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

  },

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

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    let {
      uid
    } = this.data

    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: '',
    }
  }
})