package com.red.circle.order.infra.database.rds.service.count.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.red.circle.framework.dto.PageResult;
import com.red.circle.framework.mybatis.constant.PageConstant;
import com.red.circle.framework.mybatis.convertor.MybatisConvertor;
import com.red.circle.framework.mybatis.service.impl.BaseServiceImpl;
import com.red.circle.order.infra.database.rds.dao.count.TotalRechargeUserDAO;
import com.red.circle.order.infra.database.rds.entity.count.TotalRechargeUser;
import com.red.circle.order.infra.database.rds.service.count.TotalRechargeUserService;
import com.red.circle.order.inner.model.dto.TotalRechargeUserDTO;
import com.red.circle.tool.core.sequence.IdWorkerUtils;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 充值过的用户 服务实现类.
 * </p>
 *
 * @author pengshigang on 2022/5/27
 */
@Service
@RequiredArgsConstructor
public class TotalRechargeUserServiceImpl extends
    BaseServiceImpl<TotalRechargeUserDAO, TotalRechargeUser> implements TotalRechargeUserService {

  private final TotalRechargeUserDAO totalRechargeUserDAO;


  @Override
  public List<TotalRechargeUserDTO> listUserRechargeTotal(String sysOrigin) {
    return totalRechargeUserDAO.listUserRechargeTotal(sysOrigin);
  }

  @Override
  public void incAmount(Long userId, BigDecimal amount) {
    totalRechargeUserDAO.saveIfAbsent(new TotalRechargeUser()
        .setId(IdWorkerUtils.getId())
        .setUserId(userId)
    );

    update()
        .setSql("amount=amount+" + amount)
        .eq(TotalRechargeUser::getUserId, userId)
        .execute();
  }

  @Override
  public void decr(Long userId, BigDecimal amount) {

    TotalRechargeUser rechargeUser = query()
        .eq(TotalRechargeUser::getUserId, userId)
        .last(PageConstant.LIMIT_ONE)
        .getOne();

    if (Objects.isNull(rechargeUser)) {
      return;
    }

    update()
        .setSql("amount=amount-" + amount)
        .eq(TotalRechargeUser::getId, rechargeUser.getId())
        .last(PageConstant.LIMIT_ONE)
        .execute();

  }

  @Override
  public PageResult<TotalRechargeUser> opsPageQuery(IPage<TotalRechargeUser> pageQuery,
      String sysOrigin, Long userId) {
    return MybatisConvertor.toPageResult(
        totalRechargeUserDAO.opsPageQuery(pageQuery, sysOrigin, userId)
    );
  }

}
