const util = require("../../../utils/util.js");
var app = getApp();
const config = require('../../../utils/config')
Page({
  data: {
    selectMore: false,
    checkedGroup: [],
    showShare: false,
    picGroup: [],
    activeDate: 0,
    info: {},
    picArr: [],
    saveImageList: [],
    liveId: "",
    teamId: "",
    options: {},
    imgArr: [],
    num: 24,
    change: 0,
    imgPath: util.config.imgPath,
    current: '', //预览当前index
    ceilingShow: false, //吸顶
  },
  scroll(e) {
    let query = wx.createSelectorQuery();
    let height = ''
    query.select('#topImg').boundingClientRect(rect => {
      //获取到元素
      height = rect.height;
      // console.log(6767, height, e.detail.scrollTop)
      if (e.detail.scrollTop >= height) {
        if (!this.data.ceilingShow) {
          this.setData({
            ceilingShow: true
          })
        }
      } else {
        if (this.data.ceilingShow) {
          this.setData({
            ceilingShow: false
          })
        }
      }
    }).exec();

  },
  showpic(e) {
    let url = e.currentTarget.dataset.url;
    wx.previewImage({
      current: url, // 当前显示图片的 http 链接
      saveImageList: [],
      photos: [],
      activeInfo: {},

    })
  },
  onShareAppMessage: function () {
    let shareImg = this.data.activeInfo.sharePhoto ? this.data.activeInfo.sharePhoto : 'https://img.bbztx.com/weixin/applet/share/activity_cover.jpg'
    return {
      title: '查看活动过程中的精彩图片',
      path: `/pages/growup/activePhoto/index?liveId=${this.data.liveId}`,
      imageUrl: shareImg
    }
  },
  onLoad(options) {
    if (options.liveId || options.scene) {
      this.setData({
        liveId: options.liveId ? options.liveId : options.scene
      })
      this.getInfor()
      this.getPicture()
      return
    }
  },
  onShow(options) {
    // this.getInfor()
    let option = app.globalData.info
    if (option && option.liveId != "") {
      this.setData({
        liveId: option.liveId
      })
      this.getInfor()
      this.getPicture()
      //  return
    }
  },
  // 获取活动信息
  getInfor() {
    let that = this
    util.ajax({
      func: "v2/child/liveRoomDetail",
      data: {
        "liveId": that.data.liveId
      }
    }, function (res) {
      if (res.code == 0) {
        that.data.activeInfo = res.data
        wx.setStorageSync('info', res.data)
        that.setData({
          activeInfo: that.data.activeInfo
        })
      }
    })
  },
  finishLoad: function (e) {
    let index = e.currentTarget.dataset.index
    this.data.imgArr[index].finishLoadFlag = true
    this.setData({
      imgArr: this.data.imgArr
    })
  },
  // 切换图片
  dataChange(e) {
    this.setData({
      picArr: []
    })
    let i = e.currentTarget.dataset.index
    // let photo=this.data.picGroup.cameraPhotos[i].photoList
    let arr = this.data.picGroup.cameraPhotos[i].photoList.slice(0, this.data.num)
    let obj = {}
    let newArr = []
    let newArr1 = []
    let copy = []
    arr.forEach((ele, i) => {
      copy.push(ele)
      obj.url = ele,
        obj.flag = true,
        // 显示展位图
        obj.finishLoadFlag = true
      newArr.push(JSON.parse(JSON.stringify(obj)))
    })
    // todo：左右两边高度问题
    //   newArr.forEach(item=>{
    //     item.image=item.url
    //   })
    //   console.log(newArr)
    // this._select(newArr, false).then(() => {
    //   success && success();
    // }).catch(err => {
    //   console.error(err);
    // });
    this.setData({
      imgArr: newArr,
      activeDate: i,
      picArr: copy,
      change: 1,
    })
  },

  _select(data, refresh) {
    const query = wx.createSelectorQuery().in(this);
    this.columnNodes = query.selectAll('#left, #right');
    return new Promise((resolve) => {
      this._render(data, 0, refresh, () => {
        resolve();
      });
    });
  },
  _render(data, i, refresh, success) {
    if ((data.length > i || refresh) && this.data.imgArr.length !== 0) {
      this.columnNodes.boundingClientRect().exec(res => {
        console.log(res)
        const rects = res[0];
        this.data.leftHeight = rects[0].height;
        this.data.rightHeight = rects[1].height;
        if (this.data.leftHeight <= this.data.rightHeight || refresh) {
          data[i].location = 'left'
        } else {
          data[i].location = 'right'
        }
        console.log(6555555, this.data.rightHeight, this.data.leftHeight, data)
        this.setData({
          imgArr: data,
        }, () => {
          this._render(data, ++i, false, success);
        });
      });
    } else {
      success && success();
    }
  },

  imgListBinderror(e) {
    var photos = this.data.photos,
      index = e.currentTarget.dataset.index;
    photos[index] = '/images/noimg.png'
    this.setData({
      photos
    });
  },

  // 预览图片
  openpreviewImg(e) {
    this.selectComponent("#previewComponent").showPreview();
    let index = e.target.dataset.index
    let abbreviationPic = []
    this.data.picArr.forEach(item => {
      let item1 = {
        url: '',
        originalShow: false
      }
      item1.url = item + '?x-oss-process=image/quality,q_10'
      abbreviationPic.push(item1)
    })
    console.log(abbreviationPic[index], 888, this.data.picArr)
    this.setData({
      defImg: abbreviationPic[index].url, //当前图片
      preList: abbreviationPic, //缩略图列表
      originalArr: this.data.picArr //原图列表
    })
  },
  // 选择图片
  checkRadio(e) {
    let picInfo = e.currentTarget.dataset;
    let that = this
    if (picInfo.flag == true) { //已选中，修改选中项数组
      this.data.checkedGroup.forEach((el, i) => {
        if (picInfo.id == i) {
          this.data.checkedGroup.splice(i, 1)
        }
      });
      this.data.imgArr[picInfo.id].flag = false;
    } else { //未选中，修改原数组
      this.data.imgArr[picInfo.id].flag = true;
      if (this.data.checkedGroup.length <= 300) {
        this.data.checkedGroup.push(picInfo.id);
      } else {
        util.showTips('最多可选300张图片。');
      }
    }
    this.setData({
      imgArr: this.data.imgArr
    })
  },
  // 保存图片
  // save(event) {
  //   // 获取图片
  //   wx.getImageInfo({
  //     src: this.data.saveImageList,
  //     success: function (res) {
  //       let path = res.path
  //       wx.saveImageToPhotosAlbum({
  //         filePath: path,
  //         success: function (result) {
  //           wx.showToast({
  //             title: '下载图片成功',
  //             duration: 2000,
  //             mask: true
  //           })
  //         },
  //         fail: function () {
  //           wx.openSetting({
  //             success: function () {}
  //           })
  //         }
  //       })
  //     }
  //   })
  // },
  // 查看更多
  // jumPage(){
  //   wx.navigateTo({
  //     url: '/pages/growup/photo/index',
  //   })
  //   this.setData({
  //     imgArr:that.data.imgArr
  //   })
  // },
  // 保存图片的延迟回调
  getTempPath(url) {
    return new Promise((resolve, reject) => {
      wx.downloadFile({
        url: url,
        success: function (res) {
          var temp = res.tempFilePath
          wx.saveImageToPhotosAlbum({
            filePath: temp,
            success(res) {
              return resolve(res)
            },
            fail: function (err) {
              reject(url + JSON.stringify(err))
            }
          })
        },
        fail: function (err) {
          reject(url + JSON.stringify(err))
        }
      })
    })
  },
  // 保存图片
  save(event) {
    // 获取图片
    let saveList = []
    this.data.imgArr.filter((item, index) => {
      if (item.flag == false) {
        saveList.push(this.data.imgArr[index].url)
      }
    })
    // let copyList=saveList.join(",")
    wx.showLoading({
      title: '图片下载中',
      mask: true
    })
    const imageList = []
    // 循环数组
    for (let i = 0; i < saveList.length; i++) {
      imageList.push(this.getTempPath(saveList[i]))
    }
    const loadTask = []
    let index = 0
    while (index < imageList.length) {
      loadTask.push(
        new Promise((resolve, reject) => {
          // 将数据分割成多个promise数组
          Promise.all(imageList.slice(index, (index += 8)))
            .then(res => {
              resolve(res)
            })
            .catch(err => {
              reject(err)
            })
        })
      )
    }
    // Promise.all 所有图片下载完成后弹出
    Promise.all(loadTask)
      .then(res => {
        wx.showToast({
          title: '下载完成',
          duration: 3000
        })
      })
      .catch(err => {
        wx.showToast({
          title: `下载完成`,
          icon: 'none',
          duration: 3000
        })
      })
  },
  // 查看更多
  jumPage() {
    wx.setStorageSync('liveId', this.data.liveId)
    wx.navigateTo({
      url: `/pages/growup/photo/index?liveId=${this.data.liveId}`,
    })
  },
  // 批量选择
  selectMore() {
    this.setData({
      selectMore: true
    })
  },
  swipeUpload() {
    if (this.data.num < this.data.picGroup.cameraPhotos[this.data.activeDate].photoList.length) {
      this.data.num = this.data.num + 24
      let arr = this.data.picGroup.cameraPhotos[this.data.activeDate].photoList.slice(0, this.data.num)
      let obj = {}
      let newArr = []
      let copy = []
      arr.forEach((ele, i) => {
        copy.push(ele)
        obj.url = ele,
          obj.flag = true
        newArr.push(JSON.parse(JSON.stringify(obj)))
      })
      this.setData({
        imgArr: newArr,
        picArr: copy,
      })

      this.setData({
        num: this.data.num
      })
    }
  },

  onPullDownRefresh() {
    console.log('下拉')
    this.setData({
      num: 20
    })
    this.getPicture()
  },
  // 获取图片
  getPicture() {
    let that = this;
    util.ajax({
      func: "v2/child/photoList",
      data: {
        "liveId": that.data.liveId,
      }
    }, function (res) {
      if (res.code == 0) {
        let copyRes = res.data.cameraPhotos[0].photoList.slice(0, that.data.num)
        let obj = {}
        let newArr = []
        let copy = []
        copyRes.forEach((ele, i) => {
          copy.push(ele)
          obj.url = ele,
            obj.flag = true
          newArr.push(JSON.parse(JSON.stringify(obj)))
        })

        that.setData({
          picArr: copy,
          picGroup: res.data,
          imgArr: newArr
        })
      }
    })
  },

  // 跳转至活动详情
  toDetail() {
    let status = this.data.activeInfo.status
    if (status == 2) {
      util.showTips('该活动已下架，无法查看。可联系宝大大进行咨询~');
    } else if (status == 0) {
      // 跳转至活动详情页
      wx.navigateTo({
        url: `/pages/product/activity/index?aid=${this.data.activeInfo.aid}`,
      })
    } else if (status == 1) {
      //  跳转至详情
      wx.navigateTo({
        url: `/pages/product/activity/index?aid=${this.data.activeInfo.aid}`,
      })
    }
  },
  cancel() {
    this.setData({
      selectMore: false
    })
  },
  share() {
    this.setData({
      showShare: true
    })
  },
  onUnload() {
    this.data.setData({
      liveId: ""
    })
  }

})