const util = require("../../../utils/util.js");
const app = getApp();
Page({
  data: {
    childInfo: [],
    childs: [],
    childIndex: 0,
    activity: [],
    actives: [],
    activityIndex: 0,
    teamInfo: {
      cameraPhotos: [],
      teamPhotos: []
    },
    list: [],
    photoList: [],
    photos: [],
    activeIndex: 0,
    activeDate: 0,
    finished: false,
    pageSize: 32,
    pageIndex: 1,
    finishedText: '',
    npsOptons: {},
    npsStatus: false, //nps组件是否显示
    isGet: true,
    liveId: "",
    liveFlag: false,
    idcard: "",
    cardType: "",
    Copyactives: "",
    childName: "",
    butFlag: true,
    actives2: [],
    imgArr: [],
    picGroup: [],
    saveImageList: [],
    picArr: [],
    dateList: [],
    photoFlag: true
  },
  selectMore() {
    this.setData({
      butFlag: false
    })
  },
  // 选择图片
  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
    })
  },
  showpic(e) {
    let url = e.currentTarget.dataset.url;
    wx.previewImage({
      current: url, // 当前显示图片的 http 链接
      saveImageList: [],
      photos: [],
      activeInfo: {}
    })
  },
  // 保存图片
  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
        })
      })
  },
  // 保存图片的延迟回调
  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))
        }
      })
    })
  },

  cancel() {
    this.setData({
      butFlag: true
    })
  },
  onShow() {
  },
  onLoad: function (options) {
    if (options.liveId) {
      this.data.liveId = options.liveId
      this.setData({
        liveId: this.data.liveId || JSON.parse(wx.getStorageSync('liveId')),
        liveFlag: true,
      })
      this.getChild();
      return
    } else {
      this.setData({
        liveFlag: false
      })
      this.getChild();
    }

  },
  getInfo() {
    let that = this
    util.ajax({
      func: "v2/child/photoDefaultItems",
      data: {
        "liveId": that.data.liveId
      }
    }, function (res) {
      if (res.data&&res.data.cardType&&res.data.idcard) { //有默认项数据
        that.data.childInfo.forEach((item, index) => {
          if (res.data.cardType == item.cardType && res.data.idcard == item.cardNo) {
            that.setData({
              idcard: res.data.idcard,
              cardType: res.data.cardType,
              childName: item.name,
              childIndex: index //保存默认儿童位置
            })
            wx.setNavigationBarTitle({
              title: that.data.childName
            });
            // 为真 跳转过来有liveid
            if (that.data.liveFlag) {
              that.CopygetActivity()
            } else {
              that.getActivity()
            }
          }
        })
      } else {
          that.getActivity()
      }
    });
  },
  // 如果是跳转页面的话执行
  CopygetActivity() {
    let that = this,
      arr = [];
    // console.log(this.data.idcard);
    let arr2 = []
    // console.log(this.data.cardType);
    util.ajax({
      func: "daily/activity_list",
      data: {
        "idcard": that.data.idcard,
        "cardType": that.data.cardType
      }
    }, function (res) {
      if (res.code == 0) {
        res.data.forEach((item, i) => {
          if (item.liveId === that.data.liveId) {
            // console.log(8888, i, item.liveId, that.data.liveId)
            that.data.activityIndex = i
            for (var i = 0; i < res.data.length; i++) {
              arr.push(res.data[i].sname + " " + res.data[i].pstitle);
              arr2.push(res.data[i].sname + " " + res.data[i].pstitle)
            }
            that.setData({
              activityIndex: that.data.activityIndex,
              activity: res.data,
              Copyactives: item.sname + "" + item.atitle,
              actives: arr,
              actives2: arr2
            })
            if (res.data.length > 0) {
              that.team();
            }
          }
        })
      }
    });
  },

  selectImage(e) {
    this.setData({
      isGet: e.detail.isGet
    });
  },
  close(e) { //关闭nps
    this.setData({
      npsStatus: false
    });
  },
  getChild() {
    let that = this,
      arr = [];
    util.ajax({
      func: "user/childs"
    }, function (res) {
      if (res.code == 0) {
        for (var i = 0; i < res.data.length; i++) {
          arr.push(res.data[i].name);
        }
        that.setData({
          childInfo: res.data,
          childs: arr
        });
        // if (num == 1) {
        //   that.getInfo()
        //   return
        //   // 获取儿童信息不需要调用获取照片接口
        // } else {
          that.getInfo()
        // }
      } else {
        util.showTips(res.reason)
      }
    });
  },
  getActivity() {
    let that = this,
      arr = [];
    wx.setNavigationBarTitle({
      title: that.data.childs[that.data.childIndex]
    });
    util.ajax({
      func: "daily/activity_list",
      data: {
        "idcard": that.data.childInfo[that.data.childIndex].cardNo,
        "cardType": that.data.childInfo[that.data.childIndex].cardType
      }
    }, function (res) {
      if (res.code == 0) {
        for (var i = 0; i < res.data.length; i++) {
          arr.push(res.data[i].sname + " " + res.data[i].pstitle);
        }
        that.setData({
          activity: res.data,
          actives: arr,
          activityIndex: 0
        })
        if (res.data.length > 0) that.team();
      } else {
        util.showTips(res.reason)
      }
    });
  },
  team() {
    let that = this;
    util.ajax({
      func: "v2/child/photoList",
      data: {
        "liveId": this.data.activity[that.data.activityIndex].liveId,
        "teamId": this.data.activity[that.data.activityIndex].teamId,
      }
    }, function (res) {
      if (res.code == 0) {
        let teamInfo = res.data,
          list = [];
        if (teamInfo.cameraPhotos && teamInfo.teamPhotos && ((teamInfo.cameraPhotos.length > 0 && teamInfo.teamPhotos.length > 0) || (teamInfo.cameraPhotos.length > 0 && teamInfo.teamPhotos.length <= 0))) {
          list = teamInfo.cameraPhotos;
          that.data.activeIndex = 0
        } else if (teamInfo.teamPhotos && teamInfo.teamPhotos.length > 0) {
          list = teamInfo.teamPhotos;
          that.data.activeIndex = 1
        }
        let obj = {}
        let copyArr = []
        let newArr = []
        if (list[0]) {
          // 时间列表
          list.forEach(item => {
            copyArr.push(item.date)
          })
          list[0].photoList.forEach((ele, i) => {
            obj.url = ele,
              obj.flag = true
            newArr.push(JSON.parse(JSON.stringify(obj)))
            that.data.picArr.push(ele)
          })
        }
        if (that.data.activeIndex == 0) {
          that.data.photoFlag = true
        } else {
          that.data.photoFlag = false
        }
        that.setData({
          photoFlag: that.data.photoFlag,
          picGroup: res.data,
          teamInfo,
          list,
          imgArr: newArr,
          dateList: copyArr,
          activeIndex: that.data.activeIndex
        })
        if (list.length > 0) {
          that.resetlist();
        }
      } else {
        util.showTips(res.reason);
      }
    });
  },
  resetlist() {
    this.setData({
      photoList: this.data.list[this.data.activeDate].photoList,
      pageIndex: 1,
      finished: false
    })
    this.getList(1);
  },
  getList(type) {
    wx.hideLoading();
    let data = this.data.photoList.slice(this.data.pageSize * (this.data.pageIndex - 1), this.data.pageSize * this.data.pageIndex);
    this.setData({
      photos: (type ? data : [...this.data.photos, ...data])
    })
    if (this.data.photos.length >= this.data.photoList.length || this.data.photos.length < this.data.pageSize) {
      this.setData({
        finishedText: this.data.photos.length < this.data.pageSize ? '' : "~已经到底了~",
        finished: true
      })
    }
  },
  onReachBottom() {
    if (this.data.finished) return false
    wx.showLoading();
    this.setData({
      pageIndex: this.data.pageIndex + 1
    })
    this.getList()
  },
  childsPickerChange(e) {
    this.setData({
      childIndex: e.detail.value,
      activityIndex: 0,
      activeIndex: 0,
      activeDate: 0,
      teamInfo: [],
      list: [],
      dateList: [],
      childName: "",
      picArr: []
    });
    this.getActivity();
  },
  activesPickerChange(e) {
    this.setData({
      activityIndex: e.detail.value,
      activeIndex: 0,
      activeDate: 0,
      teamInfo: [],
      list: [],
      Copyactives: "",
      picArr: []
    });
    this.team();
  },
  tabsChange(e) {
    let activeIndex = e.currentTarget.dataset.index,
      activeDate = 0;
    if (activeIndex == this.data.activeIndex) return false;
    this.setData({
      picArr: [],
      imgArr: []
    })
    let obj = {}
    let copyobj = {}
    let copyArr = []
    let newArr = []
    let list = activeIndex == 1 ? this.data.teamInfo.teamPhotos : this.data.teamInfo.cameraPhotos;
    list.forEach((item, index) => {
      copyArr.push(item.date)
      if (index == 0) {
        item.photoList.forEach(ele => {
          obj.url = ele,
            obj.flag = true
          newArr.push(JSON.parse(JSON.stringify(obj)))
          this.data.picArr.push(ele)
        })
      }
    })
    if (activeIndex == 0) {
      this.data.photoFlag = true
    } else {
      this.data.photoFlag = false
    }
    this.setData({
      photoFlag: this.data.photoFlag,
      activeIndex,
      activeDate,
      imgArr: newArr,
      dateList: copyArr,
      picArr: this.data.picArr
    });
    this.resetlist();
  },
  dataChange(e) {
    this.setData({
      picArr: []
    })
    let i = e.currentTarget.dataset.index
    let arr
    if (this.data.photoFlag == true) {
      arr = this.data.picGroup.cameraPhotos[i].photoList
    } else {
      arr = this.data.picGroup.teamPhotos[i].photoList
    }

    let obj = {}
    let newArr = []
    arr.forEach((ele, i) => {
      this.data.picArr.push(ele)
      obj.url = ele,
        obj.flag = true
      newArr.push(JSON.parse(JSON.stringify(obj)))
    })
    this.setData({
      imgArr: newArr,
      activeDate: i
    })
  },
  imgListBinderror(e) {
    var photos = this.data.photos,
      index = e.currentTarget.dataset.index;
    photos[index] = '/images/noimg.png'
    this.setData({
      photos
    });
  },
  previewImage(e) {
    let url = e.currentTarget.dataset.url;
    // this.data.picArr.push(url)
    wx.previewImage({
      current: url, // 当前显示图片的 http 链接
      urls: this.data.picArr // 需要预览的图片 http 链接列表
    })
  },
  onShareAppMessage() {
    return {
      title: '儿童参加活动的精彩照片',
      path: '/pages/account/photo/index'
    }
  }
})