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

import com.google.common.collect.Lists;
import com.red.circle.common.business.core.enums.SysOriginPlatformEnum;
import com.red.circle.common.business.dto.cmd.AppExtCommand;
import com.red.circle.other.app.dto.clientobject.activity.ActivityAgentAnchorContentCO;
import com.red.circle.other.domain.gateway.props.ActivitySourceGroupGateway;
import com.red.circle.other.infra.database.mongo.entity.team.team.TeamMember;
import com.red.circle.other.infra.database.mongo.service.activity.ActivityAgentAnchorCountService;
import com.red.circle.other.infra.database.mongo.service.activity.ActivityRewardReceiveMarkService;
import com.red.circle.other.infra.database.mongo.service.team.team.TeamMemberService;
import com.red.circle.other.inner.enums.activity.PropsActivityTypeEnum;
import com.red.circle.other.inner.enums.task.ReceiveStatusEnum;
import com.red.circle.other.inner.model.dto.activity.props.ActivityResource;
import com.red.circle.other.inner.model.dto.activity.props.ActivityRewardProps;
import com.red.circle.other.inner.model.dto.activity.rule.CommonContent;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.date.ZonedDateTimeAsiaRiyadhUtils;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.tuple.ImmutableTriple;
import org.springframework.stereotype.Component;

/**
 * 主播当月总积分.
 *
 * @author pengshigang on 2023/2/27.
 */
@Component
@RequiredArgsConstructor
public class ActivityAnchorMonthTargetRewardCmdExe {

  private final TeamMemberService teamMemberService;
  private final ActivitySourceGroupGateway activitySourceGroupGateway;
  private final ActivityAgentAnchorCountService activityAgentAnchorCountService;
  private final ActivityRewardReceiveMarkService activityRewardReceiveMarkService;

  public ImmutableTriple<Long, List<ImmutableTriple<ReceiveStatusEnum, ActivityAgentAnchorContentCO,
      List<ActivityRewardProps>>>, Long> execute(AppExtCommand cmd) {

    TeamMember teamMember = teamMemberService.getByMemberId(cmd.getReqUserId());
    if (Objects.isNull(teamMember)) {
      return ImmutableTriple.of(0L, Lists.newArrayList(), null);
    }

    List<ActivityResource> configList = getActivityResource(cmd.requireReqSysOriginEnum());
    if (CollectionUtils.isEmpty(configList)) {
      return ImmutableTriple.of(0L, Lists.newArrayList(), null);
    }

    // 已领取的奖励
    List<Long> rewardIds = getRewardIdsByCondition(cmd.getReqUserId());

    // 获得数量
    Long count = activityAgentAnchorCountService
        .getCountQuantity(cmd.getReqUserId(),
            PropsActivityTypeEnum.ACTIVE_ANCHOR_MONTH_TARGET_REWARD.name(), getThisMonthDate());

    return ImmutableTriple.of(count, configList.stream().map(config -> {
      ActivityAgentAnchorContentCO anchorContentCO = new ActivityAgentAnchorContentCO()
          .setRuleId(config.getRule().getId())
          .setQuantity(CommonContent.serializable(config.getRule().getJsonData()).getQuantity());
      if (rewardIds.contains(anchorContentCO.getRuleId())) {
        return ImmutableTriple.of(ReceiveStatusEnum.RECEIVED, anchorContentCO,
            toRewardPoolCO(config.getPropsGroupActivityRewardProps()));
      }

      if (count >= anchorContentCO.getQuantity()) {
        return ImmutableTriple.of(ReceiveStatusEnum.AVAILABLE, anchorContentCO,
            toRewardPoolCO(config.getPropsGroupActivityRewardProps()));
      }

      return ImmutableTriple.of(ReceiveStatusEnum.UN_CLAIMABLE, anchorContentCO,
          toRewardPoolCO(config.getPropsGroupActivityRewardProps()));
    }).collect(Collectors.toList()), null);

  }

  private List<Long> getRewardIdsByCondition(Long teamId) {
    return Optional.ofNullable(activityRewardReceiveMarkService
            .getRewardIdsByCondition(teamId,
                PropsActivityTypeEnum.ACTIVE_ANCHOR_MONTH_TARGET_REWARD.name(), getThisMonthDate()))
        .orElse(Lists.newArrayList());
  }

  private Integer getThisMonthDate() {
    return ZonedDateTimeAsiaRiyadhUtils.nowYearMonthToInt();
  }


  private List<ActivityRewardProps> toRewardPoolCO(
      List<ActivityRewardProps> activityPropsGroups) {

    return activityPropsGroups.stream()
        .map(rewardProps -> new ActivityRewardProps()
            .setId(rewardProps.getId())
            .setCover(rewardProps.getCover())
            .setGroupId(rewardProps.getGroupId())
            .setSort(rewardProps.getSort())
            .setQuantity(rewardProps.getQuantity())
            .setType(rewardProps.getType())
            .setAmount(rewardProps.getAmount())
            .setContent(rewardProps.getContent()))
        .collect(Collectors.toList());
  }

  /**
   * 获得活动组配置数据.
   */
  private List<ActivityResource> getActivityResource(SysOriginPlatformEnum sysOrigin) {
    return activitySourceGroupGateway.listActivityResource(sysOrigin,
        PropsActivityTypeEnum.ACTIVE_ANCHOR_MONTH_TARGET_REWARD);
  }


}
