package cn.iocoder.yudao.module.partner.service.impl;


import cn.iocoder.yudao.module.partner.entity.PartnerBalance;
import cn.iocoder.yudao.module.partner.entity.PartnerBalanceDetail;
import cn.iocoder.yudao.module.partner.mapper.PartnerBalanceMapper;
import cn.iocoder.yudao.module.partner.service.IPartnerBalanceDetailService;
import cn.iocoder.yudao.module.partner.service.IPartnerBalanceService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ruoyi
 * @date 2023-08-16
 */
@Service
public class PartnerBalanceServiceImpl extends ServiceImpl<PartnerBalanceMapper, PartnerBalance> implements IPartnerBalanceService
{
    @Autowired
    private IPartnerBalanceDetailService balanceDetailService;
    private Lock balanceLock = new ReentrantLock();


    @Override
    public void addSellBalance(Long partnerId, Long amount,String title) {
        try {
            balanceLock.lock();
            LambdaQueryWrapper<PartnerBalance> queryWrapper =new LambdaQueryWrapper<>();
            queryWrapper.eq(PartnerBalance::getPartnerId,partnerId);
            PartnerBalance partnerBalance = baseMapper.selectOne(queryWrapper);
            partnerBalance.setAmount(partnerBalance.getAmount()+amount);
            partnerBalance.setTotalRevenue(partnerBalance.getTotalRevenue()+amount);
            baseMapper.updateById(partnerBalance);
            //处理明细
            PartnerBalanceDetail detail = new PartnerBalanceDetail();
            detail.setPartnerBalanceId(partnerBalance.getId());
            detail.setType("0");
            detail.setChangeAmount(amount);
            detail.setChangeTime(new Date());
            detail.setReason(title);
            balanceDetailService.save(detail);
            balanceLock.unlock();
        }catch (Exception e){
            log.error(e.getMessage());
        }

    }
}
