package com.red.circle.other.app.command.activity;

import com.google.common.collect.Lists;
import com.red.circle.other.app.convertor.user.UserProfileAppConvertor;
import com.red.circle.other.app.dto.clientobject.activity.InviteUserCO;
import com.red.circle.other.app.dto.cmd.activity.InviteUserActivityLimitCmd;
import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.infra.database.rds.entity.user.user.InviteUserRegister;
import com.red.circle.other.infra.database.rds.service.user.user.InviteUserRegisterService;
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.Objects;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 邀请用户注册活动 邀请用户总额.
 *
 * @author pengshigang
 * @since 2022-05-24
 */
@Component
@RequiredArgsConstructor
public class InviteUserListExe {

  private final UserProfileGateway userProfileGateway;
  private final UserProfileAppConvertor userProfileAppConvertor;
  private final InviteUserRegisterService inviteUserRegisterService;

  public List<InviteUserCO> execute(InviteUserActivityLimitCmd cmd) {

    List<InviteUserRegister> page = inviteUserRegisterService
        .pageByCommissionDesc(cmd.getPageNumber(), cmd.getReqUserId());

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

    Map<Long, UserProfileDTO> userMap = getUserMap(page);

    return page.stream().map(userRegister -> {
      UserProfileDTO user = userMap.get(userRegister.getInviteUserId());
      if (Objects.isNull(user)) {
        return null;
      }
      return new InviteUserCO()
          .setUserId(user.getId())
          .setUserAvatar(user.getUserAvatar())
          .setUserNickname(user.getUserNickname())
          .setTotalCommission(NumUtils.formatBigDecimal(userRegister.getCommission()))
          .setCreateTime(userRegister.getCreateTime());

    }).filter(Objects::nonNull).toList();

  }

  private Map<Long, UserProfileDTO> getUserMap(List<InviteUserRegister> page) {
    return userProfileAppConvertor.toMapUserProfileDTO(userProfileGateway
        .mapByUserIds(page.stream().map(InviteUserRegister::getInviteUserId).collect(
            Collectors.toSet()))
    );
  }

}
