package com.kxs.system.biz.service.impl;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kxs.common.core.util.R;
import com.kxs.system.api.model.KxsCamp;
import com.kxs.system.biz.constant.enums.SysErrorTypeEnum;
import com.kxs.system.biz.mapper.KxsCampBonusLogMapper;
import com.kxs.system.api.model.KxsCampBonusLog;
import com.kxs.system.biz.mapper.KxsCampMapper;
import com.kxs.system.biz.service.KxsCampBonusLogService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * 训练营奖金池日志表(KxsCampBonusLog)表服务实现类
 *
 * @author 系统
 * @since 2024-04-08 15:44:02
 */
@Service("kxsCampBonusLogService")
@RequiredArgsConstructor
public class KxsCampBonusLogServiceImpl extends ServiceImpl<KxsCampBonusLogMapper, KxsCampBonusLog> implements KxsCampBonusLogService {

    private final KxsCampMapper kxsCampMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R changeBonus(KxsCampBonusLog param) {

        KxsCamp kxsCamp = kxsCampMapper.selectById(param.getCampId());
        if(kxsCamp == null){
            return R.failed(SysErrorTypeEnum.NOT_DATA.getDescription());
        }

        param.setBeforeAmount(kxsCamp.getBonusPool());
        BigDecimal subAmt = NumberUtil.sub(kxsCamp.getBonusPool(), param.getAmount());
        if(subAmt.compareTo(BigDecimal.ZERO) < 0){
            return R.failed("扣除金额不能大于奖金池金额");
        }

        //更新奖金池金额
        kxsCamp.setBonusPool(subAmt);
        kxsCampMapper.updateById(kxsCamp);

        //添加扣除记录
        param.setAfterAmount(subAmt);
        baseMapper.insert(param);

        return R.ok();
    }
}

