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

import com.google.common.collect.Lists;
import com.red.circle.common.business.core.enums.SysOriginPlatformEnum;
import com.red.circle.common.business.dto.cmd.app.AppRoomIdCmd;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.CommonErrorCode;
import com.red.circle.other.app.dto.clientobject.activity.RoomContributionCountCO;
import com.red.circle.other.domain.gateway.user.ability.UserRegionGateway;
import com.red.circle.other.infra.database.mongo.entity.activity.RoomContributionActivityCount;
import com.red.circle.other.infra.database.mongo.entity.live.RoomProfile;
import com.red.circle.other.infra.database.mongo.service.activity.RoomContributionActivityCountService;
import com.red.circle.other.infra.database.mongo.service.live.RoomProfileManagerService;
import com.red.circle.other.inner.model.dto.user.reigon.SysRegionAssistProbabilityDTO;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.date.ZonedDateTimeAsiaRiyadhUtils;
import com.red.circle.tool.core.num.NumUtils;
import com.red.circle.tool.core.text.StringUtils;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.springframework.stereotype.Component;

/**
 * <p>
 * 房间贡献查询 .
 * </p>
 *
 * @author pengshigang
 * @since 2022-10-27
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class RoomContributionActivityQueryCmdExe {

  private final UserRegionGateway userRegionGateway;
  private final RoomProfileManagerService roomProfileManagerService;
  private final RoomContributionActivityCountService roomContributionActivityCountService;

  public RoomContributionCountCO execute(AppRoomIdCmd cmd) {

    // 印度特殊地区， 刘占洋 2023/07/07
    /*String regionCode="";
    if (Objects.equals(cmd.getReqSysOrigin().getOrigin(),
        SysOriginPlatformEnum.ASWAT.getSysOrigin())) {
      regionCode = userRegionGateway.getRegionCode(cmd.getReqUserId());
      List<String> regions = List.of("IN2", "IN");

      if (regions.contains(regionCode.toUpperCase())) {
        ResponseAssert.failure(CommonErrorCode.SYSTEM_IS_DOWN);
      }
    }*/

    Long roomId = roomProfileManagerService.getRoomId(cmd.getReqUserId());
    ResponseAssert.notNull(CommonErrorCode.NOT_FOUND_RECORD_INFO, roomId);
    // 是否为请求人自己的房间
    boolean isOwn = Objects.equals(roomId, cmd.getRoomId());

    // 是否为本周一
    boolean isThisMonday = Objects.equals(ZonedDateTimeAsiaRiyadhUtils.getThisMonday(),
        ZonedDateTimeAsiaRiyadhUtils.nowDateToInt());

    RoomProfile roomProfile = roomProfileManagerService.getProfileById(cmd.getRoomId());
    ResponseAssert.notNull(CommonErrorCode.NOT_FOUND_RECORD_INFO, roomProfile);
    ResponseAssert.notNull(CommonErrorCode.NOT_FOUND_RECORD_INFO, roomProfile.getId());

    // 获得金币可领取比例
    SysRegionAssistProbabilityDTO activityRatio = getAssistRoomContributionActivityRatio(
        roomProfile);

    // 非本周且没有领取且积分大于最低领取要求的数据集合
    List<RoomContributionActivityCount> activityCounts = roomContributionActivityCountService
        .listRoomContribution(cmd.getRoomId(), cmd.requireReqSysOriginEnum());

    //如果是菲律宾数据查询的数据从0开始
//    if(Objects.equals(regionCode,"PH")){
//      activityCounts = roomContributionActivityCountService
//          .listRoomContributionByPH(cmd.getRoomId(), new BigDecimal(0));
//    }
//    //如果是巴基斯坦地区从100000开始
//    if(Objects.equals(regionCode,"PK")){
//      activityCounts = roomContributionActivityCountService
//          .listRoomContributionByPH(cmd.getRoomId(), new BigDecimal(100000));
//    }

    ImmutablePair<String, BigDecimal> thisWeekData = getThisWeekData(cmd, activityRatio.getRatio());
    if (CollectionUtils.isEmpty(activityCounts)) {
      return new RoomContributionCountCO()
          .setThisWeekIntegral(thisWeekData.getLeft())
          .setThisWeekAmount(thisWeekData.getRight())
          .setAvailableAmount(BigDecimal.ZERO)
          .setIsNotHighProportion(activityRatio.getRatio().compareTo(BigDecimal.valueOf(0.05)) <= 0)
          .setIsShowReceiveButton(Boolean.FALSE)
          .setImgUrl(activityRatio.getImgUrl());
    }
    // 可领取金额（不含本周）
    BigDecimal availableAmount = getAvailableAmount(cmd, activityRatio, activityCounts);

    return new RoomContributionCountCO()
        .setThisWeekIntegral(thisWeekData.getLeft())
        .setThisWeekAmount(thisWeekData.getRight())
        .setAvailableAmount(availableAmount)
        .setIsNotHighProportion(activityRatio.getRatio().compareTo(BigDecimal.valueOf(0.05)) <= 0)
        .setIsShowReceiveButton(
            isOwn && isThisMonday && availableAmount.compareTo(BigDecimal.ZERO) > 0)
        .setImgUrl(activityRatio.getImgUrl());
  }

  private BigDecimal getAvailableAmount(AppRoomIdCmd cmd,
      SysRegionAssistProbabilityDTO activityRatio,
      List<RoomContributionActivityCount> activityCounts) {
    if (CollectionUtils.isEmpty(activityCounts)) {
      return BigDecimal.ZERO;
    }

//    // 这几个区域调整了金币价值， 4月低 刘占洋 下降41% 流水不变领取点下降
//    String userRegionCode = userRegionGateway.getRegionCode(cmd.getReqUserId());
//
//    if (isExistsRegion(List.of("NG1", "NG", "PH", "PH1"), userRegionCode)) {
//      var historyIntegral = getAvailableAmount(cmd, new BigDecimal("0.1"), activityCounts.stream()
//          .filter(activityCount -> activityCount.getDateNumber() < 20230501)
//          .map(RoomContributionActivityCount::getContributionValue)
//          .filter(Objects::nonNull)
//          .toList());
//
//      var historyIntegralAvailableAmount = historyIntegral.subtract(
//              historyIntegral.multiply(new BigDecimal("0.41")))
//          .setScale(0, RoundingMode.DOWN);
//
//      var newIntegral = getAvailableAmount(cmd, activityRatio.getRatio(), activityCounts.stream()
//          .filter(activityCount -> activityCount.getDateNumber() >= 20230501)
//          .map(RoomContributionActivityCount::getContributionValue)
//          .filter(Objects::nonNull)
//          .toList());
//
//      return historyIntegralAvailableAmount.add(newIntegral);
//    }

    return getAvailableAmount(cmd, activityRatio.getRatio(), activityCounts.stream()
        .map(RoomContributionActivityCount::getContributionValue)
        .filter(Objects::nonNull)
        .toList());
  }

  private boolean isExistsRegion(List<String> regions, String regionCode) {
    if (CollectionUtils.isEmpty(regions) || StringUtils.isBlank(regionCode)) {
      return false;
    }
    for (String region : regions) {
      if (StringUtils.equalsIgnoreCase(regionCode, region)) {
        return true;
      }
    }
    return false;
  }


  private BigDecimal getAvailableAmount(AppRoomIdCmd cmd, BigDecimal ratio,
      List<BigDecimal> integralList) {
    //加一个区域值 不同的区域可能会有不同的开始计算点
    String regionCode = userRegionGateway.getRegionCode(cmd.getReqUserId());
    return roomContributionActivityCountService
        .getAvailableAmount(cmd.requireReqSysOriginEnum(),regionCode, integralList, ratio);
  }

  private SysRegionAssistProbabilityDTO getAssistRoomContributionActivityRatio(
      RoomProfile roomProfile) {
    return userRegionGateway.getAssistRoomContributionActivityRatioDTO(roomProfile.getUserId());
  }

  private ImmutablePair<String, BigDecimal> getThisWeekData(AppRoomIdCmd cmd,
      BigDecimal ratio) {

    RoomContributionActivityCount count = roomContributionActivityCountService
        .getThisWeekData(cmd.getRoomId());
    if (Objects.isNull(count)) {
      return ImmutablePair.of("0", BigDecimal.ZERO);
    }

    if (Objects.isNull(count.getContributionValue())) {
      return ImmutablePair.of("0", BigDecimal.ZERO);
    }
    return ImmutablePair.of(NumUtils.formatBigDecimal(count.getContributionValue()),
        getAvailableAmount(cmd, ratio, Lists.newArrayList(count.getContributionValue())));
  }

}
