package com.izouma.dingdong.service.rider;

import com.izouma.dingdong.domain.MoneyRecord;
import com.izouma.dingdong.domain.User;
import com.izouma.dingdong.domain.rider.Rider;
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 com.izouma.dingdong.repo.rider.RiderRepo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Service
@AllArgsConstructor
public class RiderService {

    private RiderRepo riderRepo;
    private UserRepo userRepo;
    private MoneyRecordRepo moneyRecordRepo;

    /*
    骑手签到
     */
    public void sign(Long riderId) {

    }

    /*
    骑手收入，且保存到记录表
     */
    public void income(Long riderId, Long fromUserId, BigDecimal amount, FinancialType type) {
        //骑手应得  riderRepo.findUserIdById(riderId)
        User riderUser = userRepo.findById(riderId).orElseThrow(new BusinessException("无用户"));
        riderUser.setMoney(riderUser.getMoney().add(amount));
        userRepo.save(riderUser);

        //购买的user
        User user = userRepo.findById(fromUserId).orElseThrow(new BusinessException("无用户"));

        moneyRecordRepo.save(MoneyRecord.builder()
                .amount(amount)
                .avatar(user.getAvatar())
                .name(user.getNickname())
                .type(type)
                .fromUserId(fromUserId)
                .userId(riderUser.getId())
                .time(LocalDateTime.now())
                .enabled(true)
                .build());

    }
}
