// dispatcher/pages/sweeped_books/sweeped_books.js
import { routers, viewImage, sharePage, isFn, getGlobalVal } from '../../../utils/util.js'
import { SignList, SignSubmit } from '../../../utils/api.js'
const { navigateTo, redirectTo, navigateBack } = routers()
const { globalData } = getApp()
const { baseImgUrl, thumbnail, qrcodeInvalidToastText } = globalData

Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseImgUrl,
    thumbnail,
    isLoaded: false,
    selectAll: 0,
    isManage: 0,
    isDown:false,
    isLoad: false,
    totalNum: 0,
    ids: [],
    pageNo: 1,
    pageSize: 10,
    childName:"",
    type:1,
    isAll: 0,
    totalNumbers: 0,
    isSignin:1,
    list: [],
    nodataArray: {
      text: "会员列表为空",
      image: '../../../assets/Nosign.png',
      margin: '400rpx auto'
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      isSignin: options.isSignin
    });
    if (options.isSignin ==1){
      this.setData({ type: 1 })
      wx.setNavigationBarTitle({
        title: `签到`,
      })
    }
    if (options.isSignin == 0) {
      this.setData({ type: 2 })
      wx.setNavigationBarTitle({
        title: `签离`,
      })
    }
    
    options.vipId = getGlobalVal('vipId', `vipId_${getGlobalVal('userId')}`)
    options.libId = getGlobalVal('list').length > 0 ? getGlobalVal('list')[0].libId : ''
    this.setData(options)
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    const obj = { navigateTo, redirectTo, navigateBack, viewImage }
    for (const i in obj) {
      this[i] = obj[i]
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getData(res => {
      this.setData({ isLoaded: 1 })
    })
  },

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

  },

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

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({ pageNo: 1 })
    this.getData(res => {
      wx.stopPullDownRefresh()
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    const { isAll, isDown } = this.data
    if (isAll) {
      this.setData({ isDown: true })
      return
    } else {
      this.setData({ isLoad: true, isDown: false })
      this.getData(() => {
        this.setData({ isLoad: false })
      })
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if (isFn(sharePage)) return sharePage()
  },

  /**
   * 获取数据
   */

  /**
   * 在馆书籍
   */
  getData: function (cb) {
    const continuousFn = { fn: this.getData, param: { ...arguments } }
    const { pageNo, pageSize, list, libId, type, options, selectAll, childName } = this.data
    SignList({ data: { type, libId, pageNo, pageSize, childName }, continuousFn }).then(res => {
      const { pages } = res.data
      const newList = ((list, isCheck) => {
        for (let i in list) {
          list[i].isCheck = isCheck
        }
        return list
      })(res.data.list, selectAll)
      let tempList = []
      if (pageNo == 1) {
        tempList = newList
      } else {
        tempList = [...list, ...newList]
      }
      const temp = {}
      temp[`list`] = tempList
      temp['pageNo'] = newList.length == pageSize ? ~~pageNo + 1 : pageNo
      temp['isAll'] = newList.length < pageSize
      this.setData(temp)
      this.setData({ totalNumbers: pages })
      this.caclulateBook()
      if (isFn(cb)) cb()
    }).catch(res => {
      if (isFn(cb)) cb()
    })
  },



  /**
   * 切换管理和取消按钮
   */
  toggleManageCtl: function () {
    const { isManage = false } = this.data
    this.setData({ isManage: !isManage })
  },

  /**
   * 选择图书
   */
  toggleSelectLiCtl: function (e) {
    const { index = -1 } = e.currentTarget.dataset
    const { list = [] } = this.data
    const { isCheck } = list[index]
    list[index].isCheck = isCheck != 1 ? 1 : 2
    this.setData({ list })
    this.caclulateBook()
  },

  /**
   * 选择全部图书
   */
  checkAllCtl: function () {
    const { selectAll, list = [] } = this.data
    for (let i in list) {
      list[i]['isCheck'] = selectAll != 1 ? 1 : 2
    }
    this.setData({ list })
    this.caclulateBook()
  },

  /**
   * 计算书籍
   */
  caclulateBook: function () {
    const { list } = this.data
    let num = 0
    let ids = []
    for (let v of list) {
      if (v['isCheck'] == 1) {
        num++
        ids.push(v['id'])
      }
    }
    this.setData({ totalNum: num, ids, selectAll: ids.length == list.length?1:2 })
  },

  /**
   * 签到签离
   */
  SignSubmit: function () {
    const continuousFn = { fn: this.delCtl, param: { ...arguments } }
    const { ids = [], options = {}, selectAll, libId = '', type = 0, childName } = this.data
    if (!ids.length) {
      wx.showToast({
        title: '请先选中要签到的学生',
        icon: 'none'
      })
      return
    }
    SignSubmit({ data: { ids, libId, type, selectAll, childName }, continuousFn }).then(res => {
      this.setData({ pageNo: 1 })
      this.getData()
      wx.hideLoading()
      wx.showToast({
        title: res.msg
      })
    })
  },

  /**
   * 到达提交
   */
  submitCtl: function () {
    const continuousFn = { fn: this.submitCtl, param: { ...arguments } }
    const { options = {} } = this.data
    const { libId = '', type = 0 } = options
    
    if (!libId) {
      wx.showToast({
        title: '请先选择馆',
        icon: 'none'
      })
      return
    }
    const titles = ['', '离馆成功', '到达成功']
    const fn = [null, ConfirmToZb, ConfirmToLib]
    if (isFn(fn[type])) {
      wx.showLoading({
        title: '提交中...',
      })
      fn[type]({ data: { libId }, continuousFn }).then(res => {
        wx.hideLoading()
        wx.showToast({
          title: titles[type]
        })
        setTimeout(() => {
          navigateBack()
        }, 2000)
      }).catch(() => {
        wx.hideLoading()
      })
    }
  }
})