package com.red.circle.other.app.dto.cmd.gift;

import com.red.circle.common.business.dto.cmd.AppExtCommand;
import com.red.circle.tool.core.collection.CollectionUtils;
import jakarta.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.hibernate.validator.constraints.Range;

/**
 * @author pengliang on 2020/6/1
 */
@Data
@EqualsAndHashCode(callSuper = false)
public class GiveAwayGiftBatchCmd extends AppExtCommand {

  /**
   * 第三方弹幕游戏ID
   */
  private Integer gameId;

  /**
   * 接收人.
   */
  private List<Long> acceptUserIds;

  /**
   * 接收信息.
   */
  private List<GiveAwayGiftRoomAccepts> accepts;

  /**
   * 礼物编号.
   */
  @NotNull(message = "giftId required.")
  private Long giftId;

  /**
   * 礼物数量.
   */
  @Range(min = 1, max = 7777, message = "quantity range 1~7777")
  @NotNull(message = "quantity required.")
  private Integer quantity;

  /**
   * 是否为连击赠送(true:是).
   */
  private Boolean checkCombo;

  /**
   * 房间id.
   */
  private Long roomId;

  /**
   * 动态id.
   */
  private Long dynamicContentId;

  /**
   * 已点歌曲唯一标识ID(不是歌曲配置id而是已点歌曲id).
   */
  private Long songId;

  public List<GiveAwayGiftRoomAccepts> acceptsDistinct() {
    if (CollectionUtils.isNotEmpty(getAccepts())) {
      return new ArrayList<>(getAccepts().stream()
          .collect(Collectors.toMap(GiveAwayGiftRoomAccepts::getAcceptUserId,
              Function.identity(), (v0, v1) -> v1))
          .values());
    }

    return CollectionUtils.newArrayList();
  }

  private List<Long> getUserIds() {

    List<GiveAwayGiftRoomAccepts> accepts = getAccepts();
    if (CollectionUtils.isEmpty(accepts)) {
      return Optional.ofNullable(getAcceptUserIds()).map(
          userIds -> userIds.stream().filter(Objects::nonNull).distinct()
              .collect(Collectors.toList())).orElse(CollectionUtils.newArrayList());
    }

    return accepts.stream().map(GiveAwayGiftRoomAccepts::getAcceptUserId)
        .filter(Objects::nonNull).distinct().collect(Collectors.toList());
  }

  public BigDecimal calculateConsumeGolds(BigDecimal giftGolds) {
    return giftGolds.multiply(BigDecimal.valueOf(quantity))
        .multiply(BigDecimal.valueOf(getUserIds().size()));
  }

  public List<Long> filterAcceptUserId() {
    return getUserIds();
  }
}
