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

import com.google.api.client.util.Maps;
import com.red.circle.framework.mybatis.constant.PageConstant;
import com.red.circle.framework.mybatis.service.impl.BaseServiceImpl;
import com.red.circle.order.infra.database.rds.dao.count.TotalRechargeDAO;
import com.red.circle.order.infra.database.rds.entity.count.TotalRecharge;
import com.red.circle.order.infra.database.rds.service.count.TotalRechargeService;
import com.red.circle.order.inner.model.enums.MonthlyRechargeType;
import com.red.circle.tool.core.collection.CollectionUtils;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 累计用户充值总额 服务实现类.
 * </p>
 *
 * @author pengshigang
 * @since 2022-05-27
 */
@Service
public class TotalRechargeServiceImpl extends
    BaseServiceImpl<TotalRechargeDAO, TotalRecharge> implements TotalRechargeService {


  @Override
  public void incrAmount(Long userId, BigDecimal amount, MonthlyRechargeType type) {
    TotalRecharge totalRecharge = query()
        .eq(TotalRecharge::getUserId, userId)
        .eq(TotalRecharge::getType, type)
        .last(PageConstant.LIMIT_ONE)
        .getOne();
    if (Objects.isNull(totalRecharge)) {
      save(new TotalRecharge()
          .setUserId(userId)
          .setAmount(amount)
          .setType(type.name())
      );
      return;
    }
    update()
        .setSql("amount=amount+" + amount)
        .eq(TotalRecharge::getId, totalRecharge.getId())
        .execute();
  }

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

    TotalRecharge totalRecharge = query()
        .eq(TotalRecharge::getUserId, userId)
        .eq(TotalRecharge::getType, type)
        .last(PageConstant.LIMIT_ONE)
        .getOne();

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

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

  }

  @Override
  public Map<Long, List<TotalRecharge>> mapGroup(Set<Long> userIds) {
    if (CollectionUtils.isEmpty(userIds)) {
      return CollectionUtils.newHashMap();
    }
    return Optional.ofNullable(query().in(TotalRecharge::getUserId, userIds).list())
        .map(userTotalRecharges -> userTotalRecharges.stream()
            .collect(Collectors.groupingBy(TotalRecharge::getUserId)))
        .orElseGet(Maps::newHashMap);
  }
}
