const app = getApp();
Page({
    data: {
        sid: -1,
        showSetMoney: false,
        currentMoney: 0,
        currentMoneyText: 0,
        expendBalance: 0,
        incomeBalance: 0,
        priceError: false,
        visible : false,
        dateRangeText : null,
        dateRange : null,
        minDate: new Date().getTime() - 365 * 24 * 60 * 60 * 1000,
        maxDate: new Date().getTime(),
        incomeList : [],
        payList : []
    },
    onLoad: function (options) {
        let sid = options.sid
        let currentMoney = options.balance
        let currentMoneyText = options.balance
        this.setData({sid,currentMoney,currentMoneyText})
        let dateRange = [new Date().getTime()- 24 * 60 * 60 * 1000,new Date().getTime()]
        let dateRangeText = app.$utils.formatDate(new Date(dateRange[0])) + '至' +
            (dateRange[1] ? app.$utils.formatDate(new Date(dateRange[1])) : app.$utils.formatDate(new Date()));
        this.setData({dateRange,dateRangeText})
    },
    onShow() {
        app.$api.listBillByAccount({
            sid:this.data.sid,
            dateRange:this.data.dateRangeText,
        }).then(res => {
            if (res.data){
                let incomeList = res.data.incomeList;
                let payList = res.data.payList;
                let expendBalance = res.data.expendBalance ? res.data.expendBalance : 0;
                let incomeBalance = res.data.incomeBalance ? res.data.incomeBalance : 0;
                this.setData({
                    incomeList,payList,expendBalance,incomeBalance
                })
            }
        })
    },
    handleCalendar() {
        this.setData({ visible: true });
    },
    handleConfirm(e) {
        const { value } = e.detail;
        console.log(value);
        let valueText = app.$utils.formatDate(new Date(value[0])) + '至' +
            (value[1] ? app.$utils.formatDate(new Date(value[1])) : app.$utils.formatDate(new Date()));
        this.setData({
            visible: false,
            dateRange: value,
            dateRangeText: valueText
        });
    },

    showDialog() {
        this.setData({
            showSetMoney: true,
            currentMoney: this.data.currentMoneyText
        })
    },
    onPriceInput(e) {
        this.setData({
            currentMoney: e.detail.value
        })
    },
    onConfirm () {
        const isNumber = /^\d+(\.\d+)?$/.test(this.data.currentMoney);
        if (!isNumber) {
            this.setData({
                priceError: true
            })
            return;
        }
        this.setData({
            currentMoneyText:this.data.currentMoney,
            priceError: false
        })
        app.$api.editAccount({sid:this.data.sid,balance:this.data.currentMoney}).then(res => {
            if (res){
                this.closeDialog()
            }
        })
    },
    closeDialog() {
        this.setData({
            showSetMoney: false
        })
    }
});
