import HTTP from "../../../../requestFn/Api"
import QRCode from "../../utils/weapp.qrcode.esm.js"
Page({

  data: {
    qrcodePath: "",
    data: {},
  },

  onLoad(options) {
    const {
      id
    } = options;
    this.getDetail(id);
  },
  async getDetail(id){
   const data = await HTTP.VisitorShare({id});
   this.setData({data})
   this.createQrcode(data.qcode)
  },
  // 生成二维码
  createQrcode(qcode) {
    var that = this;
    const query = wx.createSelectorQuery()
    query.select('#qrcode')
      .fields({
        node: true,
        size: true
      })
      .exec((res) => {
        var canvas = res[0].node
        // 调用方法drawQrcode生成二维码
        QRCode({
          canvas: canvas,
          canvasId: 'qrcode',
          width: 300,
          padding: 10,
          background: '#ffffff',
          foreground: '#000000',
          text: qcode,
        })
        // 获取临时路径（得到之后，想干嘛就干嘛了）
        wx.canvasToTempFilePath({
          canvasId: 'qrcode',
          canvas: canvas,
          x: 0,
          y: 0,
          width: 300,
          height: 300,
          destWidth: 300,
          destHeight: 300,
          success(res) {
            that.setData({
              qrcodePath: res.tempFilePath
            })
          },
          fail(res) {
            console.error(res)
          }
        })
      })
  },
  clickSaveImg() {
    var _this = this;
    const {
      qrcodePath
    } = _this.data
    wx.saveImageToPhotosAlbum({
      filePath: qrcodePath,
      success: function () {
        wx.showToast({
          title: "图片已保存至相册",
          duration: 2000
        })
      },
      fail: error => {
        console.log(error);
        wx.showToast({
          title: "保存图片失败",
          duration: 2000
        })
        if (error.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || error.errMsg === "saveImageToPhotosAlbum:fail auth deny" || error.errMsg === "saveImageToPhotosAlbum:fail authorize no response") {
          // 这边微信做过调整，必须要在按钮中触发，因此需要在弹框回调中进行调用
          wx.showModal({
            title: '提示',
            content: '需要您授权保存相册',
            showCancel: false,
            success: modalSuccess => {
              wx.openSetting({
                success(settingdata) {
                  console.log("settingdata", settingdata)
                  if (settingdata.authSetting['scope.writePhotosAlbum']) {
                    wx.showModal({
                      title: '提示',
                      content: '获取权限成功',
                      showCancel: false,
                    })
                  } else {
                    wx.showModal({
                      title: '提示',
                      content: '获取权限失败，将无法保存到相册哦~',
                      showCancel: false,
                    })
                  }
                },
              })
            }
          })
        }
      }
    })
  },
  previewImage() {
    wx.previewImage({
      urls: [this.data.qrcodePath],
    })
  }
})