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

  /**
   * 页面的初始数据
   */
  data: {
    baseImgUrl,
    isLoaded: false,
    pageNo: 1,
    pageSize: 10,
    isAll: 0,
    list: [],
    nodataArray: {
      text: '暂没有成长记录',
      image: '../../../assets/nodata_2.png'
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    options.userId = getGlobalVal('userId')
    options.vipId = getGlobalVal('vipId', `vipId_${options.userId}`) || ''
    options.libId = getGlobalVal('library').id || ''
    this.setData({ 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 () {
    this.setData({ pageNo: 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 { pageNo, pageSize, options, list } = this.data
    const { vipId, libId } = options
    GetGrowthRecord({ data: { pageNo, pageSize, vipId, libId }, continuousFn }).then(res => {
      const newList = res.data.list
      let listTemp = []
      if (pageNo == 1) {
        listTemp = [].concat(newList)
      } else {
        listTemp = [].concat(list, newList)
      }
      this.setData({ list: listTemp, isAll: newList.length < pageSize, pageNo: newList.length == pageSize ? pageNo + 1 : pageNo, isLoaded: true })
      cb && cb()
    }).catch(res => {
      this.setData({ isLoaded: true })
      cb && cb()
    })
  }
})