package cn.iocoder.yudao.module.system.service.loan;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.system.controller.admin.loan.vo.LoanPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.loan.vo.LoanSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.loan.LoanDO;
import cn.iocoder.yudao.module.system.dal.mysql.loan.LoanMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;

/**
 * 借支管理 Service 实现类
 *
 * @author 符溶馨
 */
@Service
@Validated
public class LoanServiceImpl implements LoanService {

    @Resource
    private LoanMapper loanMapper;

    @Override
    public void createLoan(LoanSaveReqVO createReqVO) {

        // 判断该借支用户 是否已存在借支记录
        LoanDO loanDO = loanMapper.selectOne(new LambdaQueryWrapperX<LoanDO>()
                .eq(LoanDO::getUserId, createReqVO.getUserId())
                .eq(LoanDO::getLoanType, createReqVO.getLoanType()));
        if (loanDO != null) {
            // 借支用户已存在借支记录，则更新该借支用户记录
            LoanDO updateDO = new LoanDO()
                    .setId(loanDO.getId())
                    .setAmount(loanDO.getAmount().add(createReqVO.getAmount()))
                    .setReturnAmount(loanDO.getReturnAmount().add(createReqVO.getReturnAmount()));
            // 更新
            loanMapper.updateById(updateDO);
        }else {
            // 借支用户不存在借支记录，则插入一条新记录
            LoanDO createDO = BeanUtils.toBean(createReqVO, LoanDO.class);
            loanMapper.insert(createDO);
        }
    }

    @Override
    public LoanDO getLoan(Long id) {
        return loanMapper.selectById(id);
    }

    @Override
    public PageResult<LoanDO> getLoanPage(LoanPageReqVO pageReqVO) {
        return loanMapper.selectPage(pageReqVO);
    }

    @Override
    public LoanDO getByUserId(Long userId, Integer loanType) {
        return loanMapper.selectOne(new LambdaQueryWrapperX<LoanDO>()
                .eq(LoanDO::getUserId, userId)
                .eq(LoanDO::getLoanType, loanType));
    }

    @Override
    public List<LoanDO> getListByUserId(Collection<Long> userIds, Integer loanType) {
        return loanMapper.selectList(new LambdaQueryWrapperX<LoanDO>()
                .in(LoanDO::getUserId, userIds)
                .eq(LoanDO::getLoanType, loanType));
    }

    @Override
    public List<LoanDO> getListByMonth(Collection<Long> userId, String month) {

        return loanMapper.selectListByMonth(userId, month);
    }
}