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

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.red.circle.framework.core.dto.CommonCommand;
import com.red.circle.other.app.convertor.user.UserProfileAppConvertor;
import com.red.circle.other.app.dto.clientobject.activity.InviteActivityCO;
import com.red.circle.other.app.dto.clientobject.activity.InviteActivityCO.InviteActivityInfoCO;
import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.infra.database.mongo.entity.activity.InviteRegisterRecordCount;
import com.red.circle.other.infra.database.mongo.service.activity.InviteActivityCountService;
import com.red.circle.other.inner.model.dto.user.UserProfileDTO;
import com.red.circle.tool.core.collection.CollectionUtils;
import java.util.Collection;
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;

/**
 * <p>
 * 足球活动 .
 * </p>
 *
 * @author pengshigang
 * @since 2022-05-25
 */
@Component
@RequiredArgsConstructor
public class InviteActivityCmdExe {

  private final UserProfileGateway userProfileGateway;
  private final UserProfileAppConvertor userProfileAppConvertor;
  private final InviteActivityCountService inviteActivityCountService;

  public InviteActivityCO execute(CommonCommand cmd) {

    List<InviteRegisterRecordCount> records = getInviteRegisterRecordCounts(cmd);
    if (CollectionUtils.isEmpty(records)) {
      return new InviteActivityCO();
    }

    Map<Long, UserProfileDTO> mapUser = getMapUser(records);
    if (CollectionUtils.isEmpty(mapUser)) {
      return new InviteActivityCO();
    }

    List<List<Long>> toUserIds = getToUserIds(records);
    if (CollectionUtils.isEmpty(toUserIds)) {
      return new InviteActivityCO();
    }

    InviteActivityCO co = new InviteActivityCO()
        .setUsers(records.stream().map(record -> {

          InviteActivityInfoCO agentUser = new InviteActivityInfoCO();
          agentUser
              .setUserProfile(mapUser.get(record.getToUserId()));
          if (Objects.isNull(record.getQuantity()) || record.getQuantity() <= 0) {
            agentUser.setAwardMoney(0L);
            return agentUser;
          }
          long balance = record.getQuantity() / 150000L;
          agentUser.setAwardMoney(balance <= 0 ? 0 : balance * 5);
          return agentUser;
        }).toList());

    Long money = co.getUsers().stream().mapToLong(InviteActivityInfoCO::getAwardMoney).sum();
    co.setTotalAmount(money);
    co.setUserAmount(money);

    Map<Long, Long> mapAgentCount = mapAgentCount(toUserIds);
    if (CollectionUtils.isEmpty(mapAgentCount)) {
      return co;
    }

    List<InviteActivityInfoCO> agentUsers = Lists.newArrayList();
    mapAgentCount.forEach((agentUserId, number) -> {
      InviteActivityInfoCO agentUser = new InviteActivityInfoCO();
      agentUser
          .setUserProfile(mapUser.get(agentUserId));
      if (Objects.isNull(number) || number <= 0) {
        agentUser.setAwardMoney(0L);
        agentUser.setAnchorNumber(0L);
        agentUsers.add(agentUser);
        return;
      }
      long balance = number / 10;
      agentUser.setAnchorNumber(number);
      agentUser.setAwardMoney(balance <= 0 ? 0 : balance * 5);
      agentUsers.add(agentUser);
    });
    money = agentUsers.stream().mapToLong(InviteActivityInfoCO::getAwardMoney).sum();
    co.setAgentUsers(agentUsers);
    co.setAgentAmount(money);
    co.setTotalAmount(co.getAgentAmount() + co.getUserAmount());
    return co;
  }

  private Map<Long, Long> mapAgentCount(List<List<Long>> toUserIds) {
    // 新代理系统， 不做兼容
//    List<RoomAgentBaseInfo> agentList = Lists.newArrayList();
//    for (List<Long> userIds : toUserIds) {
//      List<RoomAgentBaseInfo> list = roomAgentBaseInfoService.listByUserIds(userIds);
//      if (CollectionUtils.isEmpty(list)) {
//        continue;
//      }
//      agentList.addAll(list);
//    }
//    if (CollectionUtils.isEmpty(agentList)) {
//      return null;
//    }
//    return roomAnchorStatisticsDailyService.mapAgentAndMemberCountByAgentUserIds(
//        agentList.stream().map(RoomAgentBaseInfo::getUserId).collect(Collectors.toSet()));
    return Maps.newHashMap();
  }

  private List<List<Long>> getToUserIds(List<InviteRegisterRecordCount> records) {

    List<Long> toUserIds = records.stream().map(InviteRegisterRecordCount::getToUserId)
        .toList();
    if (CollectionUtils.isEmpty(toUserIds)) {
      return Lists.newArrayList();
    }
    return Lists.partition(toUserIds, 100);
  }

  private Map<Long, UserProfileDTO> getMapUser(List<InviteRegisterRecordCount> records) {
    return userProfileAppConvertor.toMapUserProfileDTO(
        userProfileGateway.mapByUserIds(records.stream().map(record ->
                List.of(record.getUserId(), record.getToUserId())).flatMap(Collection::stream)
            .collect(Collectors.toSet())));
  }

  private List<InviteRegisterRecordCount> getInviteRegisterRecordCounts(CommonCommand cmd) {
    return inviteActivityCountService.list(cmd.getReqUserId());
  }


}
