import HTTP from "../../../../requestFn/Api"
import QRCode from "../../utils/weapp.qrcode.esm.js"
Page({
  data: {
    num: 30,
    garden_id: null,
    device_id: null,
    Interval: null,
    type: 1,
    start: 0,
    end: 0,
    qrcodePath: "",
  },
  onLoad(options) {
    const that = this;
    const {
      type,id,qcode,device_id,garden_id
    } = options
    if (type == 1) {
      that.setData({
        device_id,
        garden_id,
        type
      })
      that.getQcode();
      that.getData()
    } 
    else if(type == 2){
      that.setData({id,type})
      that.createQrcode(qcode)
    } 
    
  },
  getQcode() {
    const that = this;
    const {
      device_id,
      garden_id
    } = that.data
    HTTP.GetQcode({
      garden_id,
      device_id
    }).then(r => {
      that.setData({ 
        num: 30
      })
      that.createQrcode(r.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: 150,
          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)
          }
        })
      })
  },
  //创建定时器
  getData() {
    const that = this;
    const Interval = setInterval(() => {
      if (that.data.num == 0) {
        clearInterval()
      } else {
        const num = that.data.num--
        that.setData({
          num: that.data.num--
        })
      }
    }, 1000)
    that.setData({
      Interval
    })
  },
  onHide() {
    clearInterval(this.data.Interval)
  },
  onUnload() {
    clearInterval(this.data.Interval)
  },
  onShareAppMessage: function (options) {
    var that = this;
    const {id} = that.data;
    var shareObj = {
      title: "访客邀约二维码",
      path: `/page/gate/pages/sharedoor/sharedoor?id=${id}`,
      imageUrl: "",
      success: function (res) {
        if (res.errMsg == 'shareAppMessage:ok') {}
      },
      fail: function () {
        if (res.errMsg == 'shareAppMessage:fail cancel') {} else if (res.errMsg == 'shareAppMessage:fail') {
        }
      },
      complete() {

      }
    };
    // 返回shareObj
    return shareObj;
  },
  //保存至相册imgUrl
  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],
    })
  }
})