// parents/pages/borrow/borrow.js
import { routers, viewImage, sharePage, isFn, getGlobalVal } from '../../../utils/util.js'
import { GetBorrowBook, BorrowBook, GetBorrowBookNum, ScanningBooks } from '../../../utils/api.js'
const { navigateTo, redirectTo, navigateBack } = routers()
const { globalData, hasLibraryService, hasVipService } = getApp()
const { baseImgUrl, qrcodeInvalidToastText } = globalData
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseImgUrl,
    isLoaded: 0,
    navIndex: 0,
    isSuccess: 0,
    navList: [
      {
        text: '本次借阅',
        list: [],
        nodataArray: {
          text: '暂没有本次借阅书单',
          image: '../../../assets/nodata_1.png',
          hasNodataBtn: 1,
          btnText: '扫码借书'
        }
      },
      {
        text: '已借阅',
        list: [],
        nodataArray: {
          text: '暂没有正在借阅书单',
          image: '../../../assets/nodata_2.png',
          hasNodataBtn: 1,
          btnText: '扫码借书'
        }
      }
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    options.userId = getGlobalVal('userId')
    options.vipId = getGlobalVal('vipId', `vipId_${options.userId}`) || ''
    options.libId = getGlobalVal('library').id || ''
    this.setData({ options })

    const list = getGlobalVal(`borrowBook_${options.userId}_${options.libId}_${options.vipId}`) || []
    const { summary, author, detailsId, img } = options
    if (detailsId) {
      list.unshift({ summary, author, detailsId, img })
      this.resetBorrowBook(list)
    } else {
      this.resetBorrowBook(list)
    }
    this.getData(res => {
      this.setData({ isLoaded: 1 })
    })
  },

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

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

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

  },

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

  },

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

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if (isFn(sharePage)) return sharePage()
  },

  /**
   * 获取已借阅的书籍
   */
  getData: function (cb) {
    const continuousFn = { fn: this.getData, param: { ...arguments } }
    const { navIndex, navList, options } = this.data
    const { vipId, libId } = options
    if (!hasVipService()) {
      cb && cb()
      return
    }
    if (!hasLibraryService()) {
      cb && cb()
      return
    }
    GetBorrowBook({ data: { vipId, libId }, continuousFn }).then(res => {
      this.setData({ 'navList[1].list': res.data.list })
      cb && cb(res)
    }).catch(res => {
      cb && cb(res)
    })
  },

  /**
   * 选择导航栏
   */
  selectNavCtl: function (e) {
    const { index } = e.currentTarget.dataset
    const { navIndex, navList } = this.data
    if (navIndex == index) {
      return
    }
    this.setData({ navIndex: index })
    if (index == 1) {
      this.getData(res => {
        this.setData({ isLoaded: 1 })
      })
    }
  },

  /**
   * 没有数据模板按钮触发事件
   */
  nodataBtnCtl: function () {
    this.scanCtl()
  },

  /**
   * 调用微信扫一扫之前判断可借书多少本
   */
  scanCtl: function () {
    const continuousFn = { fn: this.scanCtl, param: { ...arguments } }
    const { vipId, library } = this.data.options
    const libId = library.id || ''
    if (!hasVipService()) {
      return
    }
    if (!hasLibraryService()) {
      return
    }
    GetBorrowBookNum({ data: { vipId, libId }, continuousFn }).then(res => {
      const { totalBook, lentBook } = res.data
      wx.showToast({
        title: `您还可以借${totalBook}本书`,
        icon: 'none'
      })
      if (totalBook > 0) {
        this.scanFn()
      }
      this.setData({ ...res.data })
    })
  },

  /**
   * 调用微信扫一扫
   */
  scanFn: function () {
    wx.scanCode({
      success: res => {
        const url = res.result
        const detailsId = url.split('_')[1].split('.')[0]
        if (!detailsId) {
          wx.showToast({
            title: qrcodeInvalidToastText,
            icon: 'none'
          })
          return
        }
        this.scanningBooksFn(detailsId)
      }
    })
  },

  /**
   * 扫一扫借书
   */
  scanningBooksFn: function (detailsId) {
    const continuousFn = { fn: this.scanningBooksFn, param: { ...arguments } }
    const { vipId } = this.data.options
    ScanningBooks({ data: { detailsId, vipId }, continuousFn }).then(res => {
      const { detailsId } = res.data
      if (detailsId) {
        list.unshift({ ...res.data })
        this.resetBorrowBook(list)
      }
    }).catch(res => {
      wx.showToast({
        title: res.msg,
        icon: 'none'
      })
    })
  },

  /**
   * 删除图书
   */
  delBookCtl: function (e) {
    const { navIndex, navList } = this.data
    const { index } = e.currentTarget.dataset
    const { list } = navList[navIndex]
    if (navIndex != 0) {
      return
    }
    list.splice(index, 1)
    this.resetBorrowBook(list)
  },

  /**
   * 重置全局被借阅的书籍
   */
  resetBorrowBook: function (e) {
    const { userId, libId, vipId } = this.data.options
    console.log({ userId, libId, vipId })
    wx.setStorageSync(`borrowBook_${userId}_${libId}_${vipId}`, e)
    this.setData({ 'navList[0].list': e, isLoaded: 1 })
  },

  /**
   * 确定借阅以上书籍
   */
  submitCtl: function () {
    const continuousFn = { fn: this.submitCtl, param: { ...arguments } }
    if (!hasVipService()) {
      return
    }
    const { navList, navIndex, options } = this.data
    const { vipId } = options
    const { list } = navList[navIndex]
    if (list.length == 0) {
      wx.showToast({
        title: '请添加书籍后再借',
        icon: 'none'
      })
      return
    }
    const bookDetailsId = (res => {
      const arr = []
      for (let v of res) {
        arr.push(v['detailsId'])
      }
      return arr
    })(list)
    BorrowBook({ data: { bookDetailsId, vipId }, continuousFn }).then(res => {
      const { borrowList = [] } = res.data
      wx.showToast({
        title: '借阅成功',
        icon: 'none'
      })
      setTimeout(() => {
        navigateTo({ url: 'parents/pages/borrow_success/borrow_success', paras: { list: JSON.stringify(borrowList), isSuccess: 1 }, zindex: 3 })
      }, 800)
    })
  }
})