// packageA/others/materialCenter/materialCenter.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    second_catgory:[],
    parentid:'',
    childid:'',
    search_title:'',
    language: '',
    show1: false,
    posterShow: false,
    list: [],
    posterImg: '',
    // more
    isLoadMore: true,
    page: 1,
    total_page: 0,
    posterId:0
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.initData();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync('langIndex');
    this.setData({ 'language': language.en});
  },

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

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

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

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

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.isLoadMore) {
      this.getMoreData();
    } else {
      console.log('没有更多数据');
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  initData() {
    this.setData({
      show1: false,
      posterShow: false,
      list: [],
      posterImg: '',
      // more
      isLoadMore: true,
      page: 1,
      total_page: 0
    });
  },
  // 获取更多数据
  getMoreData() {

    let that = this;
    let urlStr = app.getNetAddresss('plugin.material-center.api.centerlist.index');
    that.setData({
      isLoadMore: false // 防止多次请求分页数据
    });

    if (that.data.page >= that.data.total_page) {
      return;
    } else {
      that.setData({
        page: that.data.page + 1,
      });
      app._getNetWork({
        url: urlStr,
        data: {
          page:that.data.page,
          parentid:that.data.parentid,
          childid:that.data.childid,
          search_title:that.data.search_title
        },
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            let myData = res.data.list.data;
            that.setData({
              isLoadMore:true,
              list: that.data.list.concat(myData) // 数组拼接
            });
          } else {
            that.setData({
              page: that.data.page - 1,
              isLoadMore: false
            });
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }
  },
  changeValue(e){
    this.setData({
      search_title:e.detail.value
    });
  },
  getData() {
    if(!this.data.search_title){
      wx.showToast({
        title:'请输入搜索内容',
        icon: 'none',
        duration: 1500
      });
      return; 
    }
    let that = this;
    let urlStr = app.getNetAddresss('plugin.material-center.api.centerlist.index');
    that.setData({
      isLoadMore: false,
      page: 1
    });
    let json={
      page:that.data.page,
      parentid:that.data.parentid,
      childid:that.data.childid,
      search_title:that.data.search_title
    };
    app._postNetWork({
      url: urlStr,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            isLoadMore: true,
            total_page: res.data.list.last_page
          });
     
          if (!that.data.total_page) {
            that.setData({
              total_page: 0
            });
          }
          that.setData({
            list: res.data.list.data
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  showimage(e) {
    let imgarr = e.currentTarget.dataset.images;
    let imgidx = e.currentTarget.dataset.imgidx;
    wx.previewImage({
      current: imgarr[imgidx] ? imgarr[imgidx] : '', // 当前显示图片的http链接
      urls: imgarr ? imgarr : [] // 需要预览的图片http链接列表
    });
  },
  update(e) {
    let id = e.currentTarget.dataset.id;
    let title = e.currentTarget.dataset.title;
    wx.setClipboardData({
      data: title ? title : '',
      success(res) {
        wx.showToast({
          title: '复制成功',
          icon: 'none',
          duration: 1500
        });
      },
      fail() {
        wx.showToast({
          title: '复制失败',
          icon: 'none',
          duration: 1500
        });
      }
    });
    this.setData({
      show1: true
    });
    let urlStr = app.getNetAddresss('plugin.material-center.api.centerlist.updateNum');
    app._getNetWork({
      url: urlStr,
      data: {
        id: id,
        params: 'share'
      },
      success: function (resdata) {},
      fail: function (res) {
        console.log(res);
      }
    });
  },
  show1Close() {
    this.setData({
      show1: false
    });
  },
  download(e){
    let images=e.currentTarget.dataset.images;
    let video=e.currentTarget.dataset.video;
    if(images.length>0){
      this.loadImg(images);
    }
    if(video&&video.video_url){
      this.loadVideo(video);
    }    
  },
  loadImg(images){
    images.forEach((item)=>{
      wx.downloadFile({
        url: item,//需要下载的图片url
        success: function (res) {
          //成功后的回调函数
          wx.saveImageToPhotosAlbum({
            //保存到本地
            filePath: res.tempFilePath,
            success(res) {
              wx.showToast({
                title: '图片下载成功',
                icon: 'success',
                duration: 2000
              });
            },
            fail: function (err) {
                
              if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
                wx.openSetting({
                  success(settingdata) {
                    console.log(settingdata);
                    if (settingdata.authSetting['scope.writePhotosAlbum']) {
                      console.log('获取权限成功，给出再次点击图片保存到相册的提示。');
                    } else {
                      console.log('获取权限失败，给出不给权限就无法正常使用的提示');
                    }
                  }
                });
              }
            }
          });
        }
      });
    });
  },
  loadVideo(video){
    wx.downloadFile({
      url: video.video_url,//需要下载的视频url
      success: function (res) {
        //成功后的回调函数
        wx.saveVideoToPhotosAlbum({
          //保存到本地
          filePath: res.tempFilePath,
          success(res) {
            wx.showToast({
              title: '视频下载成功',
              icon: 'success',
              duration: 2000
            });
          },
          fail: function (err) {
              
            if (err.errMsg === "saveVideoToPhotosAlbum:fail auth deny") {
              wx.openSetting({
                success(settingdata) {
                  console.log(settingdata);
                  if (settingdata.authSetting['scope.saveVideoToPhotosAlbum']) {
                    console.log('获取权限成功，给出再次点击视频保存到相册的提示。');
                  } else {
                    console.log('获取权限失败，给出不给权限就无法正常使用的提示');
                  }
                }
              });
            }
          }
        });
      }
    });
  },
  // 海报生成
  postShow(e) {
    let that = this;
    let id = e.currentTarget.dataset.id;
    if (that.data.posterImg && this.data.posterId==id) {
      this.setData({
        posterShow: true
      });
    } else {
      this.data.posterId = id;
      wx.showLoading({
        title: '海报生成中',
      });
      let urlStr = app.getNetAddresss('goods.goods-poster.generate-goods-poster');
      app._getNetWork({
        url: urlStr,
        data: {
          id: id
        },
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              posterShow: true,
              posterImg: res.data.image_url
            });
          } else {
            that.setData({
              posterShow: false
            });
            wx.showToast({
              title: res.msg,
              icon: 'none',
              duration: 1500
            });
          }
          wx.hideLoading();
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }
  },
  posterShowClose() {
    this.setData({
      posterShow: false
    });
  },
  saveImg() {
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              console.log('授权成功');
            }
          });
        }
      }
    });
    var imgSrc = this.data.posterImg;
    wx.downloadFile({
      url: imgSrc,
      success: function (res) {
        console.log(res);
        // 图片保存到本地
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function (data) {
            wx.showToast({
              title: '保存成功',
              icon: 'none',
              duration: 2000
            });
          },
          fail: function (err) {
            console.log(err);
            if (err.errMsg === 'saveImageToPhotosAlbum:fail auth deny') {
              console.log('当初用户拒绝，再次发起授权');
              wx.openSetting({
                success(settingdata) {
                  if (settingdata.authSetting['scope.writePhotosAlbum']) {
                    wx.showToast({
                      icon: 'none',
                      title: '获取权限成功,再次长按保存图片',
                      duration: 1500
                    });
                  } else {
                    wx.showToast({
                      icon: 'none',
                      title: '获取权限失败,保存图片需要用户授权',
                      duration: 1500
                    });
                  }
                }
              });
            }
          },
          complete(res) {
            console.log(res);
          }
        });
      }
    });
    
  },
});
