// pages/payment/history/history.js
const moment = require('../../../utils/moment');
const app = getApp();
const now = new Date().getFullYear();
const tabIndex = new Date().getMonth();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    index: 0,
    years: [],
    curYear: now,
    months: [],
    activeTab: tabIndex,
    curMonth: tabIndex + 1,
    history: {},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setYears();
  },

  setYears() {
    const years = [];
    for (let i = now; i >= 1990; i--) {
      years.push(`${i}年`);
    }
    this.setData({
      years
    })
    this.setMonths();
  },
  setMonths(val) {
    let months = [];
    for (let i = 1; i <= 12; i++) {
      months.push({
        title: `${i}月`,
        id: i
      });
    }
    this.setData({
      months,
      history: {}
    })
    this.getHisitoryBillDetail(this.data.curYear, this.data.curMonth);
  },
  bindPickerChange(e) {
    const year = this.data.years[e.detail.value].substr(0, 4);
    this.setData({
      index: e.detail.value,
      curYear: year
    })
    this.setMonths(year);
  },
  onTabClick(e) {
    const index = e.detail.index
    this.setData({
      activeTab: index,
      curMonth: this.data.months[index].id
    })
  },

  onChange(e) {
    const index = e.detail.index;
    this.setData({
      activeTab: index,
      curMonth: this.data.months[index].id
    })
    this.getHisitoryBillDetail(this.data.curYear, this.data.curMonth);
  },
  getHisitoryBillDetail(year, month) {
    wx.showNavigationBarLoading();
    app.$http.get('/user/getHisitoryBillDetail', {
      year,
      month
    }).then(({
      status,
      data = []
    }) => {
      wx.hideNavigationBarLoading();
      if (status == 0) {
        data.forEach(v => {
          v.reading = app.$util.numberFormat(v.reading, 1);
          v.payamount = app.$util.numberFormat(v.payamount, 1);
          v.receivefee = app.$util.numberFormat(v.receivefee, 2);
          v.debt = app.$util.numberFormat(v.debt, 2);
          v.debt = app.$util.numberFormat(v.debt, 2);
          v.recorddate = v.recorddate ? moment(v.recorddate).format('YYYY.MM.DD') : '-';
          v.lastrecorddate = v.lastrecorddate ? moment(v.lastrecorddate).format('YYYY.MM.DD') : '-';
          Object.keys(v.feelist).forEach(k => {
            v.feelist[k] = app.$util.numberFormat(v.feelist[k], 2);
          })
        })
        this.setData({
          [`history.${this.data.activeTab}`]: data
        })
      }
    }).catch(() => {
      wx.hideNavigationBarLoading();
    })
  },
})