const app = getApp()
Page({
    data: {
        sumBudget: "0.00",
        sumUsed: "0.00",
        sumBalance: "0.00",

        showSetBudget : false,
        changeType: "main",
        currentId: -1,
        currentMoney: "0.00",
        priceError: false,
        payTypeList : [],
    },
    onLoad: function (options) {

    },
    onShow() {
        this.updateBudget();
    },
    updateBudget(){
        app.$api.getBudget().then(res => {
            if (res.data){
                let sumBudget = res.data.sumBudget
                let sumUsed = res.data.sumUsed
                let sumBalance = res.data.sumBalance
                let payTypeList = res.data.payTypeList
                this.setData({sumBudget,sumUsed,sumBalance,payTypeList})
            }
        })
    },
    changeBudget(e) {
        let {type,id} = e.currentTarget.dataset
        console.log(id);
        console.log(type);
        let tCurrentMoney = 0.00;
        if (type == 'count'){
            tCurrentMoney = this.data.sumBudget
        }else {
            this.data.payTypeList.forEach(item => {
                if (item.expendId == id){
                    tCurrentMoney = item.budget
                }
            })
        }
        this.setData({
            showSetBudget: true,
            changeType: type,
            currentId: id,
            currentMoney: tCurrentMoney
        })
    },
    onPriceInput(e) {
        this.setData({
            currentMoney: e.detail.value
        })
    },
    onConfirm (e) {
        const { priceError } = this.data;
        const isNumber = /^\d+(\.\d+)?$/.test(this.data.currentMoney);
        if (priceError === isNumber) {
            this.setData({
                priceError: !isNumber,
            });
        }
        if (this.data.priceError) {
            this.setData({
                currentMoney: "0.00",
                priceError: false
            })
            return;
        }
        let expendId = this.data.currentId
        if (this.data.changeType == 'count'){
            expendId = -1
        }
        app.$api.editBudget({
            expendId:expendId,
            budget:this.data.currentMoney
        }).then(res=>{
            if(res){
                this.updateBudget();
                this.closeDialog();
            }
        })
    },
    closeDialog() {
        this.setData({
            showSetBudget: false
        })
    }
});
