// pages/user/purse.js
const api = require('../../utils/api.js')
const util = require('../../utils/util.js')
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    sharePath: 'pages/share/share',
    shareInfo: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let timer = setInterval(() => {
      if (app.globalData.PageCallback) {
        api.getUserInfo().then(res => {
          this.setData({
            userInfo: res.data
          })
        }, err => {
          console.log(err)
        })
        this.getIncomeList()
        this.getShareInfo()
        clearInterval(timer)
      }
    }, 200)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

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

  },

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

  },

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

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

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

  },

  routeUser: function (e) {
    app.globalData.openGZH = true
    wx.switchTab({
      url: '/pages/user/index?open=1',
    })
  },

  routeTo: function (e) {
    util.routeTo(e.currentTarget.dataset.to)
  },

  getShareInfo: function () {
    api.getShareInfo({
      data: {
        path: this.data.sharePath
      }
    }).then(res => {
      this.setData({
        shareInfo: res.data
      })
    }).catch(err => {
      console.log('getShare', err)
    })
  },

  // 获取今日收益列表
  getIncomeList: function () {
    const d = new Date()
    let today = d.getFullYear() + "-"
    today += ((d.getMonth() + 1) < 10 ? '0' : '') + (d.getMonth() + 1) + '-'
    today += ((d.getDate() + 1) < 10 ? '0' : '') + d.getDate()
    api.getIncomeList({
      start_time: today,
      end_time: today,
      page: 1,
      offset: 1000
    }).then(res => {
      let sum = 0
      res.data.list.forEach((item, ids) => {
        item.amount = (item.amount).toFixed(2)
        item.create_time = util.formatTime(item.create_time, 'yyyy/MM/dd')

        sum += +item.amount
      })
      this.setData({
        // sum: (res.data.sum ? res.data.sum.sum_agent_gain : 0).toFixed(2)
        sum: sum.toFixed(2)
      })
    })
  }
})