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


import com.red.circle.framework.mybatis.constant.PageConstant;
import com.red.circle.framework.mybatis.service.impl.BaseServiceImpl;
import com.red.circle.tool.core.date.TimestampUtils;
import com.red.circle.tool.core.sequence.IdWorkerUtils;
import com.red.circle.other.infra.database.rds.dao.user.user.InviteUserSummaryDAO;
import com.red.circle.other.infra.database.rds.entity.user.user.InviteUserSummary;
import com.red.circle.other.infra.database.rds.service.user.user.InviteUserSummaryService;
import java.math.BigDecimal;
import java.util.Objects;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 邀请用户充值佣金与数量累计 服务实现类.
 * </p>
 *
 * @author pengshigang
 * @since 2022-05-24
 */
@Service
public class InviteUserSummaryServiceImpl extends
    BaseServiceImpl<InviteUserSummaryDAO, InviteUserSummary> implements InviteUserSummaryService {

  @Override
  public void incrUser(Long userId, Integer quantity) {

    InviteUserSummary summary = getSummary(userId);
    if (Objects.isNull(summary)) {
      InviteUserSummary tmp = new InviteUserSummary()
          .setId(IdWorkerUtils.getId())
          .setCommission(BigDecimal.ZERO)
          .setUserId(userId)
          .setQuantity(1L);
      tmp.setCreateUser(userId);
      tmp.setCreateTime(TimestampUtils.now());
      save(tmp);
      return;
    }
    update().set(InviteUserSummary::getUpdateTime, TimestampUtils.now())
        .setSql("quantity=quantity+" + quantity)
        .eq(InviteUserSummary::getUserId, userId)
        .last(PageConstant.LIMIT_ONE)
        .execute();
  }

  private InviteUserSummary getSummary(Long userId) {
    return query().eq(InviteUserSummary::getUserId, userId)
        .last(PageConstant.LIMIT_ONE).getOne();
  }

  @Override
  public void incrCommission(Long userId, BigDecimal commission) {

    InviteUserSummary summary = getSummary(userId);
    if (Objects.isNull(summary)) {
      InviteUserSummary tmp = new InviteUserSummary()
          .setId(IdWorkerUtils.getId())
          .setCommission(commission)
          .setUserId(userId)
          .setQuantity(0L);
      tmp.setCreateUser(userId);
      tmp.setCreateTime(TimestampUtils.now());
      save(tmp);
      return;
    }

    update().set(InviteUserSummary::getUpdateTime, TimestampUtils.now())
        .setSql("commission=commission+" + commission)
        .eq(InviteUserSummary::getUserId, userId)
        .last(PageConstant.LIMIT_ONE)
        .execute();
  }

  @Override
  public InviteUserSummary getByUserId(Long userId) {

    return query().eq(InviteUserSummary::getUserId, userId).last(PageConstant.LIMIT_ONE).getOne();
  }
}
