import dayjs from "../../utils/dayjs"
import { getDayCalcList } from "../../service/calc"
import { alertError } from "../../utils/index";
import request from "../../utils/request"
const { OK } = request

// pages/meterBalanceRecord/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    time: "",
    timeStamp: undefined,
    list: [],
    page: 1,
    size: 999,
    header: [
      { key: 'day', title: '日期', },
      { key: "money", title: '充值金额', renderBody: (item) => {
        if (item.type === 1 || item.type === 7) {
          return item.topFee
        } else if (item.type === 5 || item.type === 6 || item.type === 8) {
          return `-${item.topFee}`
        } else {
          return 0
        }
      } },
      { key: 'overall', title: '电费', renderBody: (item) => {
        if (item.type == 1 || item.type === 5 || item.type === 6 || item.type === 7 || item.type === 8) {
          return 0;
        } else {
          return item.money
        }
      } },
      { key: 'balance', title: '电表余额' },
    ],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const { id } = options
    const that = this;
    this.setData({
      id,
      time: dayjs().format("YYYY-MM"),
      timeStamp: Date.now()
    }, () => {
      that.getList()
    })
  },
  clickTime() {
    this.setData({
      timeVisible: true
    })
  },
  async getList() {
    const { id, time, page, size } = this.data;
    const { code, message, data } = await getDayCalcList({ 
      page, 
      size, 
      startTime: dayjs(time).subtract(1, 'month').endOf('month').format("YYYY-MM-DD"), 
      endTime: dayjs(time).endOf('month').format("YYYY-MM-DD"),
      codeId: id,
    })
    if (code !== OK) {
      alertError(message)
      return
    }
    this.setData({
      list: data?.map(item => {
        item.day = dayjs(item.endTime).format("DD日")
        return item;
      })
    })
  },
  onTimeConfirm(e) {
    const { time } = e.detail;
    const that = this;
    this.setData({
      time,
      timeStamp: new Date(time).getTime(),
      timeVisible: false,
    }, () => {
      that.getList()
    })
  },
  onTimeCancel() {
    this.setData({
      timeVisible: false,
    })
  },
  onTimeClose() {
    this.setData({
      timeVisible: false,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

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

  },

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

  },

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

  },

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

  },

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

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})