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

  /**
   * 页面的初始数据
   */
  data: {
    baseImgUrl,
    thumbnail,
    isLoaded: 0,
    bookList: [
    {
        bookExchangeNum: '',
        bookInNum: ''
    }
    ],
    isDown:false,
    navIndex: 0,
    pageSize: 10,
    pageNo: 1,
    navList: [
      {
        text: '批量删减',
        list: [],
        pageSize: 10,
        pageNo: 1,
        isAll: 0,
        isSend: 0,
        num: 0
      },
      {
        text: '确定调入',
        list: [],
        pageSize: 10,
        pageNo: 1,
        isAll: 0,
        isSend: 0,
        num: 0
      },
    ],
    footerData: {
      actIndex: 2,
      list: [
        {
          text: '在馆书籍',
          icon: '../../../assets/zai_guan_shu_ji_gray.png',
          actIcon: '../../../assets/zai_guan_shu_ji_blue.png',
          url: 'president/pages/library_books/library_books',
          zindex: 3
        },
        {
          text: '好书推荐',
          icon: '../../../assets/wish_gray.png',
          actIcon: '../../../assets/wish_blue.png',
          url: 'president/pages/good_books_new/good_books_new',
          zindex: 3
        },
        {
          text: '调书清单',
          icon: '../../../assets/diao_shu_qing_dan_gray.png',
          actIcon: '../../../assets/diao_shu_qing_dan_blue.png',
          url: 'president/pages/book_inventory/book_inventory',
          zindex: 3
        }
      ]
    },
    nodataArray: {
      text: "调书清单空空的,快去选书吧"
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    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 () {
    // debugger
    const show = wx.getStorageSync('hiddenGetallModel')
    this.setData({ hiddenGetallModel: show })
    this.getData(() => {
      this.setData({ pageNo:1})
    })
  },

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

  },

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

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    const temp = {}
    temp[`navList[${navIndex}].pageNo`] = 1
    this.setData(temp)
    this.getData(() => {
      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()
  },

  /**
   * 选择导航栏
   */
  selectNavCtl: function (e) {
    const { index } = e.currentTarget.dataset
    const { navIndex, navList } = this.data
    // if (navIndex == index) return
    if (index == 0) {
      navigateTo({
        url: 'president/pages/book_delete_list/book_delete_list',
      })
    }
    if (index == 1) {
      wx.showToast({
        title: '请准备需要调走的图书,等待“送书侠”上门领走哦',
        icon: 'none',
        duration: 3000
      })
      this.saveLocking()
    }
    // this.setData({ navIndex: index })
    // const { list } = navList[index]
    // if (list.length > 0) return
    // this.getData()
  },
  /**
 * 提示框隐藏
 */
  allShowModel: function () {
    wx.setStorageSync('hiddenGetallModel', false)
    this.setData({ hiddenGetallModel: false })
  },
    /**
   * 申请书单
   */
  applybookLists: function () {
    navigateTo({
      url: 'president/pages/apply_bookLists/apply_booklists',
    })
  },
  /**
   * 调入与调出
   */
  getData: function (cb) {
    const continuousFn = { fn: this.getData, param: { ...arguments } }
    const { pageNo, pageSize, libId } = this.data
    CallInList({ data: { libId, pageNo, pageSize, callType:1 }, continuousFn}).then(res => {
      const { readNum = 0, bookExchangeNum = 0, booksSize = 0,bookInNum = 0, isSend = false } = res.data
      const { list } = res.data
      const correctListTemp = (res => {
        // console.log(res)
        var d = []
        for (let i in res) {
          res[i].number = res[i].select_size
        }
        return res
      })(list)
      let listTemp = []
      if (pageNo == 1) {
        listTemp = [].concat(correctListTemp)
      } else {
        listTemp = [].concat(this.data.list, correctListTemp)
      }
      // console.log(listTemp)
      this.setData({ 
        bookExchangeNum,
        bookInNum,
        list: listTemp,
        pageNo: list.length == pageSize ? pageNo + 1 : pageNo,
        isAll: list.length < pageSize,
        isLoaded: true
         })
      if (isFn(cb)) cb()
    }).catch(res => {
      this.setData({ isLoaded: true })
      if (isFn(cb)) cb()
    })
  },
 
  /**
   * 调入
   */
  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 that=this;
    var numbers = number;
    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'
        })
        that.getData(() => {
          that.setData({ pageNo:1})
        })
      })
    } 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
    var that = this;
    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'
        })
        that.getData(() => {
          that.setData({ pageNo: 1 })
        })
      })
    } else {
      this.setData({ number: 0 })
    }

  },
  /**
   * 馆长提交锁定库存
   */
  saveLocking: function () {
    const continuousFn = { fn: this.saveLocking, param: { ...arguments } }
    const { libId } = this.data;
    SaveLocking({ data: { libId }, continuousFn }).then(res => {
      wx.showToast({
        title: res.msg || '调度员已确认你馆调书申请,请等待调度员与你联系!',
        icon: 'none',
        duration: 5000
      })
      this.getData()
    }).catch(res => {
      // wx.showToast({
      //   title: res.data.msg || '你馆阅读会员数量还不足35名,请继续加油达到目标哦~',
      //   icon: 'none',
      //   duration: 5000
      // })
    })
  }
})