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

Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseImgUrl,
    isLoaded: 0,
    pageSize: 10,
    pageNo: 1,
    isAll: 0,
    nodataArray: {
      text: "暂无阅读计划",
      margin: '140rpx auto'
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    options.vipId = getGlobalVal('vipId', `vipId_${getGlobalVal('userId')}`)
    // options.vipId = '306330bd-5c8c-41aa-8a00-0f0c296ebb29',
    options.libId = getGlobalVal('library').id || ''
    this.setData({ options })
    console.log(options)
    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 { isAll} = this.data
    this.setData({ pageNo: 1 })
    this.getData(res => {
      wx.stopPullDownRefresh()
    })
  },

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


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

  
  /**
   * 获取数据
   */
  getData: function (cb) {
    const continuousFn = { fn: this.getData, param: { ...arguments } }
    const { pageNo, pageSize, options, list} = this.data
    const { vipId, code } = options
    ThemeBorrowedList({ data: { pageNo, pageSize, vipId, code }, continuousFn }).then(res => {
      const { pages } = res.data
      const newList = res.data.list
      const listTemp = (res => {
        for (let i in res) {
          if (res[i].summary.length > 30) {
            res[i].summary = res[i].summary.slice(0, 30) + '...'
          } else {
            res[i].summary = res[i].summary
          }
        }
        return res
      })(newList)
      let arr = []
      if (pageNo == 1) {
        arr = [...listTemp]
      } else {
        arr = [...list, ...listTemp]
      }
      this.setData({ list: arr, pages, isAll: newList.length < pageSize, pageNo: newList.length == pageSize ? pageNo + 1 : pageNo, isLoaded: true })
      cb && cb()
    }).catch(res => {
      this.setData({ isLoaded: true })
      cb && cb()
    })
  },
  
})