package com.izouma.dingdong.service;

import com.izouma.dingdong.domain.MoneyRecord;
import com.izouma.dingdong.domain.User;
import com.izouma.dingdong.enums.FinancialType;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.MoneyRecordRepo;
import com.izouma.dingdong.repo.UserRepo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
@AllArgsConstructor
public class MoneyRecordService {

    private MoneyRecordRepo moneyRecordRepo;
    private UserRepo        userRepo;

    public void money(Long userId, FinancialType type, BigDecimal amount, String content, String remark) {
        User user = userRepo.findById(userId).orElseThrow(new BusinessException("无用户"));
        if (FinancialType.INCOME.equals(type)) {
            user.setMoney(user.getMoney().add(amount));
        } else {
            user.setMoney(user.getMoney().subtract(amount));
        }
        userRepo.save(user);

        moneyRecordRepo.save(MoneyRecord.builder()
                .content(content)
                .remark(remark)
                .build());
    }

    /*
    算收入
     */
    public BigDecimal income(Long userId, LocalDateTime start, LocalDateTime end) {

        List<MoneyRecord> records = moneyRecordRepo.findAllByUserIdAndTimeBetween(userId, start, end);
        BigDecimal money = BigDecimal.ZERO;
        for (MoneyRecord m : records) {
            if (FinancialType.INCOME.equals(m.getType())) {
                money = money.add(m.getAmount());
            } else {
                money = money.subtract(m.getAmount());
            }
        }

        return money;
    }
}
