package com.qs.mp.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.qs.mp.common.enums.CoinLogTypeEnum;
import com.qs.mp.user.domain.UserCoin;
import com.qs.mp.user.domain.UserCoinLog;
import com.qs.mp.user.mapper.UserCoinMapper;
import com.qs.mp.user.service.IUserCoinLogService;
import com.qs.mp.user.service.IUserCoinService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

/**
 * <p>
 * 用户代币 服务实现类
 * </p>
 *
 * @author quanshu
 * @since 2022-03-07
 */
@Service
public class UserCoinServiceImpl extends ServiceImpl<UserCoinMapper, UserCoin> implements IUserCoinService {

  @Autowired
  private IUserCoinLogService userCoinLogService;

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void produce(Long userId, Integer logCoin, String bizId, CoinLogTypeEnum coinLogTypeEnum) {
    UserCoin userCoin = getById(userId);
    if (null == userCoin) {
      userCoin = new UserCoin();
      userCoin.setUserId(userId);
      userCoin.setCoin(logCoin);
      save(userCoin);
    } else {
      boolean rtn = update(new LambdaUpdateWrapper<UserCoin>().set(UserCoin::getCoin, userCoin.getCoin() + logCoin)
          .eq(UserCoin::getUserId, userId).eq(UserCoin::getCoin, userCoin.getCoin()));
      Assert.isTrue(rtn, "更新盲豆余额失败。userId:" + userId);
      userCoin.setCoin(userCoin.getCoin() + logCoin);
    }

    UserCoinLog userCoinLog = new UserCoinLog();
    userCoinLog.setUserId(userId);
    userCoinLog.setType(coinLogTypeEnum);
    userCoinLog.setMoney(userCoin.getCoin());
    userCoinLog.setLogMoney(logCoin);
    userCoinLog.setIncomeExpense(CoinLogTypeEnum.INCOME);
    userCoinLog.setLogText(coinLogTypeEnum.getDesc());
    userCoinLog.setBizTime(new Date());
    userCoinLog.setRefId(bizId);
    userCoinLogService.save(userCoinLog);
  }

  @Override
  @Transactional
  public void consume(Long userId, Integer logCoin, String bizId) {
    UserCoin userCoin = getById(userId);

    boolean rtn = update(new LambdaUpdateWrapper<UserCoin>().set(UserCoin::getCoin, userCoin.getCoin() - logCoin)
          .eq(UserCoin::getUserId, userId).eq(UserCoin::getCoin, userCoin.getCoin()));
    Assert.isTrue(rtn, "更新盲豆余额失败。userId:" + userId);

    UserCoinLog userCoinLog = new UserCoinLog();
    userCoinLog.setUserId(userId);
    userCoinLog.setType(CoinLogTypeEnum.EXCHANGE);
    userCoinLog.setMoney(userCoin.getCoin() - logCoin);
    userCoinLog.setLogMoney(0 - logCoin);
    userCoinLog.setIncomeExpense(CoinLogTypeEnum.EXPENSES);
    userCoinLog.setLogText("兑换商品");
    userCoinLog.setBizTime(new Date());
    userCoinLog.setRefId(bizId);
    userCoinLogService.save(userCoinLog);
  }
}
