// pages/payment/record/record.js
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,
    record: {},
  },

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

  setYears() {
    const years = [];
    for (let i = now; i >= 1990; i--) {
      years.push(`${i}年`);
    }
    this.setData({
      years
    })
    this.setMonths();
  },
  setMonths() {
    let months = [];
    for (let i = 1; i <= 12; i++) {
      months.push({
        title: `${i}月`,
        id: i
      });
    }
    this.setData({
      months,
      record: {}
    })
    this.getPayRecordDetail(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();
  },
  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.getPayRecordDetail(this.data.curYear, this.data.curMonth);
  },
  getPayRecordDetail(year, month) {
    wx.showNavigationBarLoading();
    app.$http.get('/user/getPayRecordDetail', {
      year,
      month
    }).then(({
      status,
      data = []
    }) => {
      wx.hideNavigationBarLoading();
      if (status == 0) {
        data.forEach(v => {
          v.remaining = app.$util.numberFormat(v.remaining, 2);
          v.fee = app.$util.numberFormat(v.fee, 2);
          v.method = v.paywayname.indexOf('现金') != -1 ? 1 : v.paywayname.indexOf('微信') != -1 ? 2 : v.paywayname.indexOf('支付宝') != -1 ? 3 : 4;
        })
        this.setData({
          [`record.${this.data.activeTab}`]: data
        })
      }
    }).catch(() => {
      wx.hideNavigationBarLoading();
    })
  },
  toOtherPage(e) {
    const {
      url
    } = e.target.dataset;
    wx.navigateTo({
      url: `/pages/${url}/${url}`,
    })
  },
})