package com.red.circle.other.adapter.app.user.user;

import com.red.circle.common.business.dto.cmd.UserIdCmd;
import com.red.circle.order.inner.endpoint.TotalRechargeClient;
import com.red.circle.order.inner.model.dto.UserTotalRechargeDTO;
import com.red.circle.other.app.dto.clientobject.user.user.UserGuardCountCO;
import com.red.circle.other.app.service.user.user.UserCountService;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户个人统计服务.
 *
 * @author pengliang on 2021/11/15
 * @eo.api-type http
 * @eo.groupName 用户服务.个人统计
 * @eo.path /user/count
 */
@RequiredArgsConstructor
@RestController
@RequestMapping(value = "/user/count", produces = MediaType.APPLICATION_JSON_VALUE)
public class UserCountRestController {

  private final UserCountService userCountService;
  private final TotalRechargeClient totalRechargeClient;

  /**
   * 守护列表.
   *
   * @param cmd {@eo.required}
   * @eo.name 守护列表.
   * @eo.url /guard
   * @eo.method get
   * @eo.request-type formdata
   */
  @GetMapping("/guard")
  public List<UserGuardCountCO> listUserGuardCountTop(@Validated UserIdCmd cmd) {
    return userCountService.listUserGuardCountTop(cmd);
  }

  /**
   * 用户累计充值
   */
  @GetMapping("/total-recharge")
  public BigDecimal getTotalRecharge(UserIdCmd cmd) {
    Set<Long> uIdSet = new HashSet<>();
    uIdSet.add(cmd.getReqUserId());
    Map<Long, List<UserTotalRechargeDTO>> userTotalRechargeMap = totalRechargeClient.mapGroup(uIdSet).getBody();

    return Optional.ofNullable(userTotalRechargeMap.get(cmd.getReqUserId()))
        .map(totalRecharges -> totalRecharges.stream().map(UserTotalRechargeDTO::getAmount)
            .reduce(BigDecimal.ZERO, BigDecimal::add)
            .setScale(2, RoundingMode.DOWN))
        .orElse(BigDecimal.ZERO);
  }

}
