package com.red.circle.other.infra.database.rds.service.game.impl;

import com.red.circle.common.business.core.enums.SysOriginPlatformEnum;
import com.red.circle.framework.mybatis.service.impl.BaseServiceImpl;
import com.red.circle.other.infra.database.rds.dao.game.GameLuckyBoxUserProfitLossDAO;
import com.red.circle.other.infra.database.rds.entity.game.GameLuckyBoxUserProfitLoss;
import com.red.circle.other.infra.database.rds.service.game.GameLuckyBoxUserProfitLossService;
import java.math.BigDecimal;
import java.util.Objects;
import java.util.Optional;
import org.springframework.stereotype.Service;

/**
 * <p>
 * Lucky Box用户盈利亏损记录 服务实现类.
 * </p>
 *
 * @author pengshigang
 * @since 2021-07-13
 */
@Service
public class GameLuckyBoxUserProfitLossServiceImpl extends
    BaseServiceImpl<GameLuckyBoxUserProfitLossDAO, GameLuckyBoxUserProfitLoss> implements
    GameLuckyBoxUserProfitLossService {

  @Override
  public BigDecimal getProfitLossAmountByUserId(Long userId) {
    return Optional.ofNullable(query().eq(GameLuckyBoxUserProfitLoss::getUserId, userId).getOne())
        .map(GameLuckyBoxUserProfitLoss::getProfitLossAmount).orElse(BigDecimal.ZERO);
  }

  @Override
  public void save(Long userId, BigDecimal amount, SysOriginPlatformEnum sysOrigin) {
    if (Objects.isNull(amount)) {
      return;
    }
    GameLuckyBoxUserProfitLoss gameLucky = query().eq(GameLuckyBoxUserProfitLoss::getUserId, userId)
        .getOne();

    if (Objects.isNull(gameLucky)) {
      save(new GameLuckyBoxUserProfitLoss()
          .setSysOrigin(sysOrigin.name())
          .setUserId(userId)
          .setProfitLossAmount(amount)
      );
      return;
    }
    update().set(GameLuckyBoxUserProfitLoss::getProfitLossAmount, amount)
        .eq(GameLuckyBoxUserProfitLoss::getUserId, userId).execute();
  }
}
