// pages/liveStream/liveStream.js
var t = require("../../../utils/util"),
  ut = t,
  e = require("../../../utils/common.js"),
  a = require("../../../utils/wxParse/wxParse.js"),
  s = getApp(),
  i = s.request,
  rq = i,
  oo = s.globalData,
  o = s.globalData.setting,
  os = o;
var regeneratorRuntime = require('../../../utils/runtime.js');
const app = getApp();
let self = null;


Page({
  /**
   * 页面的初始数据
   */
  data: {
    curPage: 1,
    ad_data: null,
    sharimg: "",
    living: {},
    livetoBegin: {},
    liveOver: {},
    list: null,
    isLoading: false, // 检测是否已经发送请求,防止重复发送请求
    noMore: false, // 检测是否有更多数据,true为没有更多数据,false为还有数据
    pageNum: 1, // 当前页数
    details: {},
    status: '',
    btnText: '',
    showActionSheet: true,
    showPlaybill: true,
    windowWidth: 0,
    windowHeight: 0,
    dpr: 0,
    canvasScale: 1.0,
    nickName: '',
    avatarUrl: '',
    coverImg: '',
    canvasToImgPath: '',
    screenWidth: 0,
    canvasHidden: 1,
    gid: '',
    shareImgPath: '',
    shartitle: "",
    anchorname:"",
    share_id:0  //分享的ID
  },
  // list: [],
  // live: {
  //   ing:[],
  //   toBegin:[],
  //   over:[]
  // },

  // 点击直播列表项
  clickItem: function (e) {
    // id：列表项id
    // live：直播类别 即将开始/直播中/精彩回放

    if (e.currentTarget.dataset.live == 101) {
      var live_status = 'ing'
    }
    if (e.currentTarget.dataset.live == 102) {
      var live_status = 'toBegin'
    }
    if (e.currentTarget.dataset.live == 103) {
      var live_status = 'over'
    }
    wx.navigateTo({
      url: '/packageA/pages/liveStreamDetails/liveStreamDetails?id=' + e.currentTarget.dataset.id + '&live=' + live_status
    })
    // console.log('options-->');
  },

  // 点击 订阅/观看直播/观看回放 按钮，跳转直播组件
  clickLive: function (e) {
    // console.log('当前房间号roomid：', e.currentTarget.dataset.roomid);
    let roomId = e.currentTarget.dataset.roomid;
    let customParams = encodeURIComponent(JSON.stringify({
      path: 'pages/index/index',
      pid: 1
    }));
    wx.navigateTo({
      url: `plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin?room_id=${roomId}&custom_params=${customParams}`
    })
  },

  updateLiveList: function () {
    return new Promise((resolve, reject) => {
      let self = this;
      getApp().request.put("/api/weshop/wx/livelist/updatelivelist", {
        data: {
          storeId: o.stoid
        },
        success: function (res) {
          // console.log('我发起了PUT请求,请求结果：', res.data);
          if (res.data.code == 0) {
            resolve();
          };
        }
      });
    });
  },

  // loadLiveList: function (curPage) {
  //   // console.log('---->curPage', curPage);
  //   // var live = {};
  //   // live.toBegin = []; // 即将开始
  //   // live.ing = []; // 直播中
  //   // var liveOver = []; // 已结束
  //   var that = this;
  //   var storeId = o.stoid;

  //   // 请求数据
  //   getApp().request.promiseGet("/api/weshop/wx/livelist/page", {
  //     data: {
  //       storedId: o.stoid,
  //       page: curPage,
  //       live_status: 103
  //     }
  //   }).then(res => {
  //     if (res.data.code == 0) {
  //       // console.log('res------------>', res);
  //       // 计算总页数
  //       // var total = res.data.data.total;
  //       // console.log("total", total);
  //       // var pageSize = res.data.data.pageSize;
  //       // console.log("pageSize", pageSize);
  //       // var pageNum = that.pageTotal(total, pageSize);
  //       // that.setData({
  //       //   pageNum: that.pageTotal(total, pageSize)
  //       // });

  //       // 如果当前请求的是第一页数据，则执行赋值，否则执行合并再赋值
  //       if (curPage == 1) {
  //         that.setData({
  //           liveOver: that.data.liveOver.concat(res.data.data.pageData)
  //         })
  //       } else {
  //         that.setData({
  //           liveOver: that.data.liveOver.concat(res.data.data.pageData)
  //         })
  //       };

  //       // var list = that.data.list;
  //       // for(var i in list) {
  //       // var liveStatus = list[i].live_status;
  //       // if (liveStatus == '101') {
  //       //   live.ing.push(list[i]);
  //       // } else if (liveStatus == '102') {
  //       //   live.toBegin.push(list[i]);
  //       // } else if (liveStatus == '103') {
  //       //   live.over.push(list[i]);
  //       // }
  //       // }

  //       // that.setData({
  //       //   liveOver: list
  //       // });

  //       curPage++;
  //       that.setData({
  //         curPage
  //       });

  //       console.log('上拉已经触发，当前page------------------------->',that.data.curPage);

  //     } else {
  //       console.error('请求失败！！！！！');
  //     }
  //   })
  // },

  // pageTotal: function (rowCount, pageSize) {
  //   if (rowCount == null || rowCount == "") {
  //     return 0;
  //   } else {
  //     if (pageSize != 0 && rowCount % pageSize == 0) {
  //       return parseInt(rowCount / pageSize)
  //     };
  //     if (pageSize != 0 && rowCount % pageSize != 0) {
  //       return parseInt(rowCount / pageSize) + 1;
  //     };
  //   }
  // },

  // getData: function (liveStatus) {
  //   var that = this;
  //   var curPage = this.data.curPage
  //   getApp().request.promiseGet("/api/weshop/wx/livelist/page", {
  //     data: {
  //       storedId: o.stoid,
  //       page: curPage,
  //       live_status: liveStatus
  //     }
  //   }).then(res => {
  //     if (res.data.code == 0) {
  //       if (liveStatus == 101) {
  //         that.setData({
  //           liveing: res.data.data.pageData
  //         });
  //       } else if (liveStatus == 102) {
  //         that.setData({
  //           livetoBegin: res.data.data.pageData
  //         });
  //       } else if (liveStatus == 103) {
  //         that.setData({
  //           liveOver: res.data.data.pageData
  //         });

  //         var total = res.data.data.total;
  //         console.log("total", total);
  //         var pageSize = res.data.data.pageSize;
  //         console.log("pageSize", pageSize);
  //         var pageNum = that.pageTotal(total, pageSize);
  //         console.log("pageNum", pageNum);
  //         that.setData({
  //           pageNum
  //         });

  //       }
  //     }

  //     curPage++;
  //     that.setData({
  //       curPage
  //     });

  //   });
  // },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    self = this;
    getApp().is_Single_page(this, function () {
      app.isLogin().then(function (data) {//进入页面前已经授权登录成功
        self.setData({
          userInfo: data,
        });
      });
    })


    getApp().request.promiseGet("/api/weshop/ad/page?pid=1207&store_id=" + os.stoid, {
      data: {
        enabled: 1
      }
    }).then(res => {
      if (res.data.code == 0 && res.data.data && res.data.data.pageData && res.data.data.pageData.length > 0) {
        var a = res.data.data.pageData;
        var narr = [];
        for (var i in a) {
          var tt = {
            'ad_code': os.imghost + a[i].ad_code,
            'media_link': '',
            'ad_weapplink': a[i].ad_weapplink
          };
          narr.push(tt);
        }
        self.setData({
          ad_data: narr
        });
      }
    })
  },

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

  },


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

    getApp().check_can_share(this);
    if (app.globalData.userInfo) {
      if (!this.data.isLogin_a) {
        this.setData({
          userInfo: app.globalData.userInfo,
          imghost: app.globalData.setting.imghost,
          isLogin_a: true,
        });

        this.updateLiveList().then(() => {

          self.getData(true, '/api/weshop/wx/livelist/page', { //请求直播中列表
            storedId: o.stoid,
            pageSize: 100,
            ordertype: 1,
            liveshow: 1
          }).then((res) => {
            var list = self.data.list
            for (var i in list.pageData) {
              var share_img = list.pageData[i].share_img
              list.pageData[i].share_img = share_img.replace("http://", 'https://')
            }
            self.setData({
              living: list,
            });

          });


        });



      };
    };
  },

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

  },

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

  },



  // 分享操作表
  clickShare: function (e) {
    var sharimg = e.currentTarget.dataset.sharimg;
    var shartitle = e.currentTarget.dataset.shartitle;
    var anchorname= e.currentTarget.dataset.anchorname;
    var id= e.currentTarget.dataset.id;

    // if (!getApp().globalData.user_id) {
    //   getApp().goto("/packageE/pages/togoin/togoin");
    //   return false;
    // }

    this.setData({
      showActionSheet: !this.data.showActionSheet,
      sharimg: sharimg,
      shartitle: shartitle,
      anchorname:anchorname,
      share_id:id,
    })
  },

  // actionSheet - 取消按钮
  hiddenActionSheet: function () {
    this.setData({
      showActionSheet: 'false'
    })
    if (!this.data.showPlaybill) {
      this.setData({
        showPlaybill: 'true'
      });
    }
  },

  // 获取图片信息
  getImageInfo(src) {
    return new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: src,
        success: (res) => {
          resolve(res);
        }
      })
    });
  },

  closeWin: function () {
    this.setData({
      showPlaybill: 'true'
    });
  },

  //生成海报
  createPlaybill: function () {
    // 1.提示 “正在生成海报...”
    wx.showLoading({
      title: '正在生成海报...'
    });

    // 3.展示生成的海报
    this.setData({
      showActionSheet: 'false',
      // showPlaybill: !this.data.showPlaybill
    });

    // 2.生成海报，如果生成完毕,关闭提示
    this.drawPlaybill();

  },


  // 生成海报
  drawPlaybill: async function () {

    var that = this;
    // wx.showLoading({
    //   title: '正在生成海报...'
    // });


   

      // 请求主图
      await that.getImageInfo(that.data.sharimg).then(res => {
        that.setData({
          coverImg: res.path,
          coverImgWidth: res.width,
          coverImgHeight: res.height,
          coverImgSize: that.imageResize(res.width, res.height),
          // coverImgHeight: res.height,
        });
        // console.log('主图加载成功~', that.data.coverImgSize);
      });
    




    var path2 = getApp().globalData.userInfo?getApp().globalData.userInfo.head_pic:'';
    if (path2 == "") {
      path2 = "../../../images/share/hui_hear_pic.png";
      this.data.avatarUrl=path2;
    } else {
      getApp().request.promiseGet("/api/weshop/marketing/help/help/imgbase64/get", {
        data: {
          imgurl: path2
        }
      }).then(res => {
        if (res.data.code == 0) {
          console.log(9999)

          var imgSrc =  res.data.data;//base64编码
          var save = wx.getFileSystemManager();
          var number = Math.random();
          save.writeFile({
            filePath: wx.env.USER_DATA_PATH + '/pic' + number + '.png',
            data: imgSrc,
            encoding: 'base64',
            success: res => {
              that.setData({
                avatarUrl: wx.env.USER_DATA_PATH + '/pic' + number + '.png'
              });
              console.log(wx.env.USER_DATA_PATH + '/pic' + number + '.png')
            }, fail: err => {
              console.log(err)
            }
          })
        }
      })
    }
    

    // 请求二维码
    // var path3 = os.url + "/api/wx/open/app/user/getWeAppEwm/" +
    //   os.stoid + "?sceneValue=1012" + "&pageValue=pages/goods/goodsInfo/goodsInfo";

    var path3 = os.url + "/api/wx/open/app/user/getWeAppEwm/" +
        os.stoid + "?sceneValue="+this.data.share_id + "&pageValue=packageA/pages/liveStreamDetails/liveStreamDetails";

    if (!this.data.ewm) {
      await that.getImageInfo(path3).then(res => {
        that.setData({
          ewm: res.path
        });
        console.log('二维码加载成功~')
      });
    }



    // 数据准备
    const title = this.data.shartitle;
    // const headImg = app.globalData.userInfo['head_pic'];

    // console.log('----------------v', headImg);

    // 以iPhone6为例，375/750 = 0.5
    // let scale = this.data.windowWidth / 375;
    let scale = this.data.screenWidth / 750 * 1.35


    // 适配屏get幕
    // let scale = this.data.windowWidth / 375.0;
    // this.setData({totalHeight: 667 * scale});

    // 获取Canvas
    let ctx = wx.createCanvasContext('myCanvas');

    // 放大 因为不放大的话，生成的分享图会模糊。暂时先注释
    // ctx.scale(this.data.canvasScale, this.data.canvasScale)



    //   var path3 = os.url + "/api/wx/open/app/user/getWeAppEwm/" +
    //     os.stoid + "?sceneValue=1012" + "&pageValue=pages/goods/goodsInfo/goodsInfo";
    //  + "?sceneValue=1012" + "&pageValue=packageA/pages/liveStreamDetails/liveStreamDetails"
    //  console.log('path3---->', path3);


    // 绘制主背景白色
    ctx.setFillStyle('#ffffff');
    ctx.fillRect(0, 0, 480, 738);

    // 绘制头像
    ctx.save();
    ctx.beginPath();
    ctx.arc(58, 52, 28, 0, 2 * Math.PI);
    ctx.clip();
    // console.log('1__________________>',app.globalData.userInfo['head_pic']);
    ctx.drawImage(this.data.avatarUrl, 30, 24, 56, 56);
    ctx.restore();


    if(app.globalData.userInfo) {
      // 绘制昵称
      ctx.setFontSize(22);
      ctx.setFillStyle('#ADADAD');
      ctx.fillText(app.globalData.userInfo.nickname, 106, 60);
    }

    // 绘制主图
    ctx.setFillStyle('#f8f8f8');
    ctx.fillRect(0, 104, 480, 380);

    // var w = this.data.coverImgWidth;
    // var h = this.data.coverImgHeight;
    var w = this.data.coverImgSize.imageWidth;
    var h = this.data.coverImgSize.imageHeight;
    // var dw = 480/w          //canvas与图片的宽高比
    // var dh = 380/h
    // var ratio       
    // // 裁剪图片中间部分
    // if(w > 480 && h > 380 || w < 480 && h < 380){
    //     if (dw > dh) {
    //         ctx.drawImage(this.data.coverImg, 0, (h - 380/dw)/2, w, 380/dw, 0, 104, 480, 380);
    //     } else {
    //         ctx.drawImage(this.data.coverImg, (w - 480/dh)/2, 0, 480/dh, h, 0, 104, 480, 380);
    //     };
    // }
    // // 拉伸图片
    // else{
    //     if(w < 300){
    //         ctx.drawImage(this.data.coverImg, 0, (h - 380/dw)/2, w, 380/dw, 0, 104, 480, 380);
    //     }else {
    //         ctx.drawImage(this.data.coverImg, (w - 480/dh)/2, 0, 480/dh, h, 0, 104, 480, 380);
    //     }
    // };
    ctx.drawImage(this.data.coverImg, (480 - w) / 2, (380 - h) / 2 + 104, w, h);


    // 绘制文字
    ctx.setFontSize(24);
    ctx.setFillStyle('#1E1E1E');
    this.drawText(ctx, title, 30, 600, 200, 460, 2);

    // 绘制小程序码
    ctx.drawImage(this.data.ewm, 310, 540, 132, 132);


    //绘制文字：长按识别
    ctx.setFontSize(20);
    ctx.setFillStyle('#1E1E1E');
    ctx.fillText('长按识别小程序', 309, 710);

    ctx.draw(true, function () {
      setTimeout(function () {
        // console.log("我进来了~~~~~");
        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          width: 750,
          height: 1217,
          destWidth: 750,
          destHeight: 1217,
          canvasId: 'myCanvas',
          fileType: 'jpg',
          success: function (res) {
            wx.hideLoading();
            that.setData({
              canvasToImgPath: res.tempFilePath,
              showPlaybill: !that.data.showPlaybill
            });
            // console.log('生成海报陈宫啦', that.data.canvasToImgPath);
            // that.saveImageToPhotosAlbum(res.tempFilePath);
            // console.log('截图陈宫：', that.data.canvasToImgPath);
            // wx.previewImage({
            //   //将图片预览出来
            //   urls: [that.data.canvasToImgPath]
            // });
          }
        })
      }, 1000)
    });



  },



  imageResize(imgWidth, imgHeight) {
    var imageSize = {};
    var originalWidth = imgWidth;//图片原始宽 
    var originalHeight = imgHeight;//图片原始高 
    var originalScale = originalHeight / originalWidth;//图片高宽比 
    // console.log('originalWidth: ' + originalWidth) 
    // console.log('originalHeight: ' + originalHeight)

    //获取屏幕宽高  
    var winWidth = 480;
    var winHeight = 380;
    var winScale = winHeight / winWidth;//屏幕高宽比 
    // console.log('windowWidth: ' + winWidth) 
    // console.log('windowHeight: ' + winHeight) 
    if (originalScale < winScale) {//图片高宽比小于屏幕高宽比 
      //图片缩放后的宽为屏幕宽 
      imageSize.imageWidth = winWidth;
      imageSize.imageHeight = (winWidth * originalHeight) / originalWidth;
    } else {//图片高宽比大于屏幕高宽比 
      //图片缩放后的高为屏幕高 
      imageSize.imageHeight = winHeight;
      imageSize.imageWidth = (winHeight * originalWidth) / originalHeight;
    }
    console.log('缩放后的宽: ' + imageSize.imageWidth)
    console.log('缩放后的高: ' + imageSize.imageHeight)
    return imageSize;
  },


  //文本换行 参数：1、canvas对象，2、文本 3、距离左侧的距离 4、距离顶部的距离 5、6、文本的宽度
  drawText: function (ctx, str, leftWidth, initHeight, titleHeight, canvasWidth, unit) {
    var lineWidth = 0;
    var lastSubStrIndex = 0; //每次开始截取的字符串的索引
    var han = 0;
    for (let i = 0; i < str.length; i++) {
      if (han == 2) return;
      //lineWidth += ctx.measureText(str[i]).width;
      lineWidth += ut.measureText(str[i], 21.3 * unit);
      if (lineWidth > canvasWidth) {
        han++;

        if (han == 2) {
          ctx.textAlign = 'justify';
          ctx.fillText(str.substring(lastSubStrIndex, i) + '...', leftWidth, initHeight); //绘制截取部分
        } else {
          ctx.textAlign = 'justify';
          ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight);
        }
        initHeight += 35; //22为字体的高度
        lineWidth = 0;
        lastSubStrIndex = i;
        titleHeight += 20;
      }
      if (i == str.length - 1) { //绘制剩余部分
        ctx.textAlign = 'justify';
        ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
      }
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    // var self = this;
    // wx.showNavigationBarLoading(); //在标题栏中显示加载
    // setTimeout(function() {
    //   self.loadLiveList(1);
    //   wx.hideNavigationBarLoading(); //完成停止加载
    //   wx.stopPullDownRefresh(); //停止下拉刷新 
    // }, 500);  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // var self = this;
    // var curPage = this.data.curPage;
    // console.log('now curPage',curPage);
    // var pageNum = this.data.pageNum;
    // console.log('now pageNum',pageNum);

    // if (curPage <= pageNum) {
    //   wx.showLoading({
    //     title: '加载中...',
    //   })
    //   setTimeout(function () {
    //     self.loadLiveList(curPage);
    //     wx.hideLoading();
    //   }, 500);
    // } else {
    //   wx.showToast({
    //     title: '已经到底啦~',
    //     duration: 1000
    //   })
    // }

    // console.log('触底啦');
    this.scrollToLower('/api/weshop/wx/livelist/page', {
      storedId: o.stoid,
      live_status: 103
    });
  },

  /**
    * 用户点击右上角分享
    */
  onShareAppMessage: function (res) {
    getApp().globalData.clear = 1;
    this.setData({
      showActionSheet: 'false'
    })
    var self = this;
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: this.data.details.name,
      success: function (res) {
        console.log('res---->', res);
      },
      complete: function (res) {
        console.log('comple', res)
      }
    }
  },

  onShareTimeline: function (res) {
    getApp().globalData.no_clear = 1;
    var user_id = getApp().globalData.user_id;
    if (!user_id) user_id = 0;

    return {
      title: '直播列表',
      query: 'first_leader=' + user_id
    }
  },


  /**
   * 请求数据
   */
  getData: function (isInit, url, data) {
    let p = app.request.promiseGet(url, {
      data: data,
      isShowLoading: true,
    })
      .then(function (res) {
        if (res.data.code == 0) {

          self.setData({
            isLoading: false
          });

          if (isInit) {// 第一次加载
            self.setData({
              list: res.data.data
            });
          } else {
            self.setData({
              'list.pageData': self.data.list.pageData.concat(res.data.data.pageData)
            });
          };

          if ((res.data.data.pageData.length == 0) || (res.data.data.pageSize * res.data.data.page >= res.data.data.total)) {
            self.setData({
              noMore: true
            });
          };

        } else {
          self.setData({
            'list.pageData': []
          });
        };

      });

    return p;
  },


  // 保存图片到手机
  onSaveToPhone() {
    var self = this;
    // 获取用户的当前设置，返回值中有小程序已经向用户请求过的权限
    this.getSetting().then((res) => {
      // 判断用户是否授权了保存到相册的权限，如果没有发起授权
      if (!res.authSetting['scope.writePhotosAlbum']) {
        this.authorize().then(() => {
          // 同意授权后保存下载文件
          this.saveImageToPhotosAlbum(self.data.canvasToImgPath)
        })
      } else {
        // 如果已经授权，保存下载文件
        this.saveImageToPhotosAlbum(self.data.canvasToImgPath)
      }
    })
  },

  //打开设置，引导用户授权
  onOpenSetting() {
    wx.openSetting({
      success: (res) => {
        // console.log(res.authSetting)
      }
    })
  },

  // 获取用户已经授予了哪些权限
  getSetting() {
    return new Promise((resolve, reject) => {
      wx.getSetting({
        success: res => {
          resolve(res)
        }
      })
    })
  },

  // 发起首次授权请求
  authorize() {
    // isFirst 用来记录是否为首次发起授权，
    // 如果首次授权拒绝后，isFirst赋值为1
    let isFirst = wx.getStorageSync('isFirst') || 0;
    return new Promise((resolve, reject) => {
      wx.authorize({
        scope: 'scope.writePhotosAlbum',
        // 同意授权
        success: () => {
          resolve();
        },
        // 拒绝授权,这里是用户拒绝授权后的回调
        fail: res => {
          if (isFirst === 0) {
            wx.setStorageSync('isFirst', 1);
            wx.showToast({
              title: '保存失败',
              icon: 'none',
              duration: 1000
            })
          } else {
            this.showModal();
          }
          console.log('拒绝授权');
          reject();
        }
      })
    })
  },

  //保存下载文件
  savedownloadFile(img) {
    this.downLoadFile(img).then((res) => {
      return this.saveImageToPhotosAlbum(res.tempFilePath)
    }).then(() => {
      // resolve()
    })
  },

  //单文件下载(下载文件资源到本地)，客户端直接发起一个 HTTPS GET 请求，返回文件的本地临时路径。
  downLoadFile(img) {
    var self = this;
    return new Promise((resolve, reject) => {
      wx.showLoading({
        title: '保存中...',
        mask: true,
      });
      wx.downloadFile({
        url: img,
        success: (res) => {
          resolve(res);
        }
      })
    })
  },

  // 保存图片到系统相册
  saveImageToPhotosAlbum(saveUrl) {
    var self = this;
    return new Promise((resolve, reject) => {
      wx.saveImageToPhotosAlbum({
        filePath: saveUrl,
        success: (res) => {
          wx.showToast({
            title: '保存成功',
            duration: 1000,
          });
          self.setData({
            showPlaybill: 'true'
          });
          resolve();
        },
        fail: () => {
          wx.showToast({
            title: '保存失败',
            duration: 1000,
          });
        }
      })
    })
  },


  // 弹出模态框提示用户是否要去设置页授权
  showModal() {
    wx.showModal({
      title: '检测到您没有打开保存到相册的权限，是否前往设置打开？',
      success: (res) => {
        if (res.confirm) {
          console.log('用户点击确定')
          this.onOpenSetting() // 打开设置页面          
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },


  /**
   * 上拉加载
   */
  scrollToLower(url, requestData) {
    // 数据总量
    let total = this.data.list.total;
    // 单页最大数据量
    let pageSize = this.data.list.pageSize;
    // 如果数据总量不为0且小于或等于单页最大数据量，说明数据已全部加载，显示‘没有更多了’
    if ((total != 0) && (total <= pageSize)) {
      this.setData({
        noMore: true
      });
    };

    if (!this.data.isLoading && !this.data.noMore) {
      this.setData({
        isLoading: true,
        pageNum: this.data.pageNum + 1
      });
      requestData.page = this.data.pageNum;
      this.getData(false, url, requestData);
    };
  },



})