package com.red.circle.other.app.command.sys.query;

import com.google.common.collect.Lists;
import com.red.circle.other.app.convertor.user.UserProfileAppConvertor;
import com.red.circle.other.app.dto.clientobject.sys.SysActivityCountRankCO;
import com.red.circle.other.app.dto.cmd.sys.SysActivityRankQryCmd;
import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.infra.database.mongo.entity.sys.SysActivityCount;
import com.red.circle.other.infra.database.mongo.service.sys.SysActivityCountService;
import com.red.circle.other.inner.model.dto.sys.SysActivityCountType;
import com.red.circle.other.inner.model.dto.user.UserProfileDTO;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.num.NumUtils;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 系统活动排行榜.
 *
 * @author pengliang on 2022/8/16
 */
@Component
@RequiredArgsConstructor
public class SysActivityRankQryExe {

  private final UserProfileGateway userProfileGateway;
  private final UserProfileAppConvertor userProfileAppConvertor;
  private final SysActivityCountService sysActivityCountService;

  public List<SysActivityCountRankCO> execute(SysActivityRankQryCmd cmd) {

    List<SysActivityCount> sysActivityCounts = sysActivityCountService.listRank(cmd.getActivityId(),
        SysActivityCountType.valueOf(cmd.getType()), 20);
    if (CollectionUtils.isEmpty(sysActivityCounts)) {
      return Lists.newArrayList();
    }

    Map<Long, UserProfileDTO> userProfileMap = userProfileAppConvertor.toMapUserProfileDTO(
        userProfileGateway.mapByUserIds(
            sysActivityCounts.stream().map(SysActivityCount::getUserId).collect(
                Collectors.toSet())));

    List<SysActivityCountRankCO> countRanks = sysActivityCounts.stream().map(count ->
        new SysActivityCountRankCO()
            .setUserProfile(userProfileMap.get(count.getUserId()))
            .setQuantity(count.getQuantity())
            .setQuantityFormat(NumUtils.formatLong(count.getQuantity()))
    ).toList();

    if (CollectionUtils.isEmpty(countRanks)) {
      return Lists.newArrayList();
    }

    List<Long> activityIds = List.of(1617012565612761089L, 1617009314783891458L,
        1617007388159705090L);

    if (activityIds.contains(cmd.getActivityId())) {
      for (int index = 0; index < countRanks.size(); index++) {
        if (index <= 2) {
          SysActivityCountRankCO rank = countRanks.get(index);
          rank.setQuantityFormat("***");
        }
      }
    }
    return countRanks;
  }
}
