package cn.reghao.tnb.user.app.service;

import cn.reghao.tnb.user.app.db.mapper.WalletBillMapper;
import cn.reghao.tnb.user.app.model.constant.BillType;
import cn.reghao.tnb.user.app.model.po.Wallet;
import cn.reghao.tnb.user.app.model.po.WalletBill;
import cn.reghao.tnb.user.app.model.vo.BillRecord;
import cn.reghao.tnb.user.app.model.vo.WalletDetail;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
/**
 * @author reghao
 * @date 2024-04-16 16:13:30
 */
public class WalletService {
    private final WalletBillMapper walletBillMapper;

    public WalletService(WalletBillMapper walletBillMapper) {
        this.walletBillMapper = walletBillMapper;
    }

    public synchronized void pay(double quantity, long owner) throws Exception {
        double balance = getBalance(owner);
        if (balance < quantity) {
            String errMsg = "余额不足";
            throw new Exception(errMsg);
        }

        WalletBill walletBill = new WalletBill(BillType.Expenditure.getCode(), quantity, owner);
        walletBillMapper.save(walletBill);
    }

    public Wallet getUserWallet(long owner) {
        double balance = getBalance(owner);
        return new Wallet(owner, balance);
    }

    public List<BillRecord> getWalletBill(long owner) {
        int pageSize = 10;
        List<WalletBill> list = walletBillMapper.findByOwner(pageSize, owner);
        return list.stream().map(BillRecord::new).collect(Collectors.toList());
    }

    public double getBalance(long owner) {
        WalletDetail income = walletBillMapper.findByTypeAndOwner(BillType.InCome.getCode(), owner);
        if (income == null) {
            return 0;
        }

        WalletDetail expenditure = walletBillMapper.findByTypeAndOwner(BillType.Expenditure.getCode(), owner);
        if (expenditure == null) {
            return income.getTotal();
        }

        return income.getTotal() - expenditure.getTotal();
    }
}
