// president/pages/part_call_in/part_call_in.js
import { routers, viewImage, sharePage, isFn, getGlobalVal } from '../../../utils/util.js'
import { GetThemeAllBook, BatchCallInBooks, CallOutBooks, CallInBooks, DeleteBooks } from '../../../utils/api.js'
const { navigateTo, redirectTo, navigateBack } = routers()
const { globalData } = getApp()
const { baseImgUrl, thumbnail } = globalData
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseImgUrl,
    thumbnail,
    isLoaded: 0,
    isLoad:false,
    title: '',
    pageNo: 1,
    pageSize: 10,
    isAll: false,
    navIndex: 0,
    list: [],
    isAllCheck: 0,
    isBatch:false,
    isManage: 0,
    totalNum: 0,
    number:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    options.vipId = getGlobalVal('vipId', `vipId_${getGlobalVal('userId')}`)
    options.libId = getGlobalVal('list').length > 0 ? getGlobalVal('list')[0].libId : ''
    options.gradeList = JSON.parse(options.gradeList)
    wx.setNavigationBarTitle({
      title: `${options.theme}`,
    })
    this.setData(options)
    this.setData({isAllCheck: options.status == 1 })
    
  },

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

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

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

  },

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

  },

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

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    const { isAll } = this.data
    if (isAll) return
    this.setData({ isLoad: true })
    this.getData(() => {
      this.setData({ isLoad: false })
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if (isFn(sharePage)) return sharePage()
  },
  /**
   * 调入
   */
  addBook: function (e) {
    const { isbn13, detailid, infoid, size, number, index } = e.currentTarget.dataset
    const continuousFn = { fn: this.addBook, param: { ...arguments } }
    const { libId, list } = this.data
    var numbers = number;
    console.log(list)
    var temp = {};
    if (numbers < size) {
      numbers = numbers + 1;
      this.setData({ number: numbers })
      temp[`list[${index}].number`] = numbers
      this.setData(temp)
      CallInBooks({ data: { libId, bookInfoId: infoid, isbn13 }, continuousFn }).then(res => {
        wx.showToast({
          title: `已加入调入清单`,
          icon: 'none'
        })
        // this.getData()
      })
    } else {
      if (size == 1) {
        wx.showToast({
          title: `该书籍库存只有一本了,无法再添加了`,
          icon: 'none'
        })
      } else {
        wx.showToast({
          title: `已达上限`,
          icon: 'none'
        })
      }
      return
    }
  },
  /**
   * 删除
   */
  subtractionBook: function (e) {
    const { isbn13, detailid, infoid, size, number, index } = e.currentTarget.dataset
    const continuousFn = { fn: this.subtractionBook, param: { ...arguments } }
    const { list, libId } = this.data
    let ids = [];
    ids.push(
      infoid
    )
    var numbers = number;
    var temp = {};
    console.log(number, index)
    if (numbers > 0) {
      numbers = numbers - 1;
      this.setData({ number: numbers })
      temp[`list[${index}].number`] = numbers
      this.setData(temp)
      DeleteBooks({ data: { ids, libId }, continuousFn }).then(res => {
        wx.showToast({
          title: `删除成功`,
          icon: 'none'
        })
        // this.getData()
      })
    } else {
      wx.showToast({
        title: `已经删除`,
        icon: 'none'
      })
      return
    }

  },
  /**
   * 批量选择
   */
  getBatch:function(){
    const { isBatch}=this.data
    this.setData({ isBatch: !isBatch})
  },
  /**
   * 归类书籍
   */
  getData: function (cb) {
    const continuousFn = { fn: this.getData, param: { ...arguments } }
    const { pageNo, pageSize, list, childTheme, status, isAllCheck, title, gradeList } = this.data
    GetThemeAllBook({ data: { childTheme, pageNo, pageSize, title, gradeList }, continuousFn }).then(res => {
      const newList = ((list, isCheck) => {
        for (let i in list) {
          list[i].isCheck = isCheck
          list[i].number = 0
        }
        return list
      })(res.data.list, isAllCheck)
      console.log(newList)
      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.caclulateBook()
      if (isFn(cb)) cb()
    }).catch(res => {
      if (isFn(cb)) cb()
    })
  },

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

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

  /**
   * 计算书籍
   */
  caclulateBook: function () {
    const { list } = this.data
    let num = 0
    const bookList = []
    for (const v of list) {
      const { book_detail_id, book_info_id, isbn13, isCheck } = v
      if (isCheck == 1) {
        num++
        bookList.push({
          bookInfoId: book_info_id,
          bookDetailId: book_detail_id,
          isbn13
        })
      }
    }
    this.setData({ totalNum: num, bookList, isAllCheck: bookList.length == list.length })
  },

  /**
   * 确认调入
   */
  getCallin: function () {
    const continuousFn = { fn: this.getCallin, param: { ...arguments } }
    const { bookList, vipId, libId } = this.data
    BatchCallInBooks({ data: { libId, bookList }, continuousFn }).then(res => {
      wx.showToast({
        title: `已加入调入列表`
      })
      this.getData()
    })
  },

  /**
   * 取消调入
   */
  cancelCallin: function () {
    this.setData({ isAllCheck: 1 })
    this.checkAllCtl()
  },

  /**
   * 输入搜索值
   */
  inputSearchCtl: function (e) {
    const { value } = e.detail
    const { title } = this.data
    if (title == value) return
    const temp = {}
    temp[`title`] = value
    this.setData(temp)
  },

  /**
   * 清除搜索值
   */
  clearSearchCtl: function () {
    const temp = {}
    temp[`title`] = ''
    this.setData(temp)
  },

  /**
   * 提交搜索值
   */
  submitSearchCtl: function () {
    const temp = {}
    temp[`pageNo`] = 1
    this.setData(temp)
    this.getData()
  },
})