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

import com.red.circle.common.business.core.enums.SysOriginPlatformEnum;
import com.red.circle.other.infra.database.cache.service.user.UserCpValueCacheService;
import com.red.circle.other.infra.database.mongo.entity.activity.RankQueenType;
import com.red.circle.other.infra.database.mongo.entity.gift.GiftAcceptUser;
import com.red.circle.other.infra.database.mongo.entity.gift.GiftGiveRunningWater;
import com.red.circle.other.infra.database.mongo.entity.gift.GiftValue;
import com.red.circle.other.infra.database.mongo.service.activity.RankCountService;
import com.red.circle.other.infra.database.mongo.service.activity.WeekKingQueenCountService;
import com.red.circle.other.infra.database.mongo.service.live.RoomContributionRankCountService;
import com.red.circle.other.infra.database.mongo.service.user.count.WeekCpValueCountService;
import com.red.circle.other.infra.database.mongo.service.user.count.WeekFriendshipCardCountService;
import com.red.circle.other.infra.database.rds.entity.user.user.CpRelationship;
import com.red.circle.other.infra.database.rds.entity.user.user.CpValue;
import com.red.circle.other.infra.database.rds.entity.user.user.FriendshipCard;
import com.red.circle.other.infra.database.rds.service.user.user.CpRelationshipService;
import com.red.circle.other.infra.database.rds.service.user.user.CpValueService;
import com.red.circle.other.infra.database.rds.service.user.user.FriendshipCardService;
import com.red.circle.other.inner.enums.activity.KingQueenType;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.date.LocalDateTimeUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 矫正活动数据
 *
 * @author lixiaofei on 2024/06/25
 */
@Slf4j
@Component
@AllArgsConstructor
public class ActivityCorrectionDataManager {

  private final MongoTemplate mongoTemplate;
  private final CpValueService cpValueService;
  private final RankCountService rankCountService;
  private final CpRelationshipService cpRelationshipService;
  private final FriendshipCardService friendshipCardService;
  private final UserCpValueCacheService userCpValueCacheService;
  private final WeekCpValueCountService weekCpValueCountService;
  private final WeekKingQueenCountService weekKingQueenCountService;
  private final WeekFriendshipCardCountService weekFriendshipCardCountService;
  private final RoomContributionRankCountService roomContributionRankCountService;

  /**
   * 矫正活动数据(收回贡献)
   *
   * @param roomId   房间id
   * @param userId   用户id
   * @param quantity 数量
   */
  private void correctionActivityData(Long roomId, Long userId, Long quantity) {

    // 房间贡献榜单
    roomContributionRankCountService.correctionData(BigDecimal.valueOf(quantity), roomId, userId);
    log.warn("correctionActivityData:房间贡献榜单-完成");

    // ASWAT King
    weekKingQueenCountService.correctionData(userId, quantity, KingQueenType.CHARM);
    log.warn("correctionActivityData:ASWAT King-魅力-完成");

    // 固定榜单
    rankCountService.correctionData(userId, RankQueenType.CHARM_RANK_DAY, quantity);
    log.warn("correctionActivityData:CHARM_RANK_DAY-完成");
    rankCountService.correctionData(userId, RankQueenType.CHARM_RANK_WEEK, quantity);
    log.warn("correctionActivityData:CHARM_RANK_WEEK-完成");
    rankCountService.correctionData(userId, RankQueenType.CHARM_RANK_MONTH, quantity);
    log.warn("correctionActivityData:CHARM_RANK_MONTH-完成");

    // cp
    CpRelationship cpRelationship = cpRelationshipService.getByUserId(userId);
    if (Objects.nonNull(cpRelationship)) {

      BigDecimal cpVal = cpValueService.getCpVal(cpRelationship.getCpValId());
      if (Objects.nonNull(cpVal) && cpVal.compareTo(BigDecimal.ZERO) > 0) {
        cpValueService.update()
            .setSql("cp_val=cp_val-" + (cpVal.longValue() > quantity ? cpVal.longValue() - quantity
                : 0L))
            .eq(CpValue::getId, cpRelationship.getCpValId())
            .execute();

        log.warn("correctionActivityData: 修改CP值-完成");
      }
      Long val = userCpValueCacheService
          .getValue(cpRelationship.getUserId(), cpRelationship.getCpUserId());
      if (Objects.nonNull(val) && val > 0) {
        userCpValueCacheService.incr(cpRelationship.getUserId(), cpRelationship.getCpUserId(),
            val > quantity ? -(val - quantity) : 0L);
        log.warn("correctionActivityData: 修改CP缓存-完成");
      }

      weekCpValueCountService
          .correctionData(cpRelationship.getCpUserId(), cpRelationship.getUserId(), quantity);
      log.warn("correctionActivityData: 修改CP护送榜单-完成");
    }

  }

  public void process(Long processUserId) {

//    if (!stringRedisTemplateService.setIfAbsent("recycleRedEnvelope-Activity:" + processUserId, 3,
//        TimeUnit.MINUTES)) {
//          return;
//    }

    log.warn("******开始处理******");
    // 目标收回
    List<GiftGiveRunningWater> giftGiveRunningWaters = mongoTemplate.find(
        Query.query(Criteria.where("userId").is(processUserId)
            .andOperator(
                Criteria.where("createTime").gte(LocalDateTimeUtils.convert(1668348000000L)),
                Criteria.where("createTime").lt(LocalDateTimeUtils.convert(1668405600000L))
            ))
        , GiftGiveRunningWater.class);

    if (CollectionUtils.isEmpty(giftGiveRunningWaters)) {
      log.warn("没有里查询到数据");
      return;
    }

    // 本周周星礼物
    // List<GiftConfigCO> giftConfigs = lastWeekStarGift();

    giftGiveRunningWaters.forEach(runningWaters -> {

      if (!Objects.equals(runningWaters.getSysOrigin(), SysOriginPlatformEnum.ASWAT.name())) {
        return;
      }

      // 总额
      Long sumQuantity = runningWaters.getGiftValue().getActualAmount().longValue();

      // 处理周星礼物
//      if (giftConfigs.stream()
//          .anyMatch(gift -> Objects.equals(gift.getId(), runningWaters.getGiftId()))) {
//
//        runningWaters.getAcceptUsers().forEach(acceptUser -> weekStarGiftCountService
//            .correctionData(acceptUser.getAcceptUserId(), acceptUser.getTargetAmount().longValue(),
//                runningWaters.getGiftId()));
//        log.warn("correctionActivityData: 处理周星-接收人-完成");
//
//        weekStarGiftCountService
//            .correctionData(runningWaters.getUserId(), sumQuantity, runningWaters.getGiftId());
//        log.warn("correctionActivityData: 处理周星-发送人-完成");
//      }

      // ASWAT King
      weekKingQueenCountService
          .correctionData(runningWaters.getUserId(), sumQuantity, KingQueenType.WEALTH);
      log.warn("correctionActivityData:aswat KING 財富-完成");

//
//
//      // 其余榜单
//      runningWaters.getAcceptUsers().forEach(acceptUser -> {
//        if (runningWaters.getOriginId().matches(RegexConstant.NUMBER)) {
//
//          Long roomId = Long.parseLong(runningWaters.getOriginId());
//          correctionActivityData(roomId, acceptUser.getAcceptUserId(),
//              acceptUser.getTargetAmount().longValue());
//        }
//      });
//
//      if (runningWaters.getOriginId().matches(RegexConstant.NUMBER)) {
//
//        Long roomId = Long.parseLong(runningWaters.getOriginId());
//        // 房间贡献余额
//        roomContributionBalanceService.correctionData(roomId, BigDecimal.valueOf(sumQuantity));
//        log.warn("correctionActivityData:房间贡献余额-完成");
//        // 房间时间段贡献
//        roomContributionCountService.correctionData(roomId, BigDecimal.valueOf(sumQuantity));
//        log.warn("correctionActivityData:房间贡献余额-完成");
//
//        rankCountService.correctionData(roomId, RankQueenType.ROOM_RANK_DAY, sumQuantity);
//        log.warn("correctionActivityData:ROOM_RANK_DAY-完成");
//        rankCountService.correctionData(roomId, RankQueenType.ROOM_RANK_WEEK, sumQuantity);
//        log.warn("correctionActivityData:ROOM_RANK_WEEK-完成");
//        rankCountService.correctionData(roomId, RankQueenType.ROOM_RANK_MONTH, sumQuantity);
//        log.warn("correctionActivityData:ROOM_RANK_MONTH-完成");
//      }
//
//      // cp
//      CpRelationship cpRelationship = cpRelationshipService.getByUserId(runningWaters.getUserId());
//      if (Objects.nonNull(cpRelationship)) {
//
//        BigDecimal cpVal = cpValueService.getCpVal(cpRelationship.getCpValId());
//        if (Objects.nonNull(cpVal) && cpVal.compareTo(BigDecimal.ZERO) > 0) {
//          cpValueService.update()
//              .setSql("cp_val=cp_val-" + (cpVal.longValue() > sumQuantity ? cpVal.longValue() - sumQuantity : 0L))
//              .eq(CpValue::getId, cpRelationship.getCpValId())
//              .execute();
//
//          log.warn("correctionActivityData-发送人: 修改CP值-完成");
//        }
//        Long val = userCpValueCacheService
//            .getValue(cpRelationship.getUserId(), cpRelationship.getCpUserId());
//        if (Objects.nonNull(val) && val > 0) {
//          userCpValueCacheService.incr(cpRelationship.getUserId(), cpRelationship.getCpUserId(),
//              val > sumQuantity ? -(val - sumQuantity) : 0L);
//          log.warn("correctionActivityData-发送人: 修改CP缓存-完成");
//        }
//
//        weekCpValueCountService
//            .correctionData(cpRelationship.getCpUserId(), cpRelationship.getUserId(), sumQuantity);
//        log.warn("correctionActivityData-发送人: 修改CP护送榜单-完成");
//      }
//
//      // 卡片
//      updateUserCard(runningWaters.getUserId(), runningWaters.getAcceptUsers(),
//          runningWaters.getGiftValue());
//      log.warn("correctionActivityData:关系卡 -完成");
//
//
//      rankCountService.correctionData(runningWaters.getUserId(), RankQueenType.WEALTH_RANK_MONTH, sumQuantity);
//      log.warn("correctionActivityData:CHARM_RANK_MONTH-完成");
//
//      rankCountService.correctionData(runningWaters.getUserId(), RankQueenType.WEALTH_RANK_WEEK, sumQuantity);
//      log.warn("correctionActivityData:CHARM_RANK_WEEK-完成");
//
//      rankCountService.correctionData(runningWaters.getUserId(), RankQueenType.WEALTH_RANK_DAY, sumQuantity);
//      log.warn("correctionActivityData:CHARM_RANK_DAY-完成");
    });
    log.warn("*****************完成-userId:" + processUserId + "***************");
  }

  private void updateUserCard(Long sendUserId, List<GiftAcceptUser> acceptUsers,
      GiftValue giftValue) {

    List<Long> acceptUserIds = acceptUsers.stream().map(GiftAcceptUser::getAcceptUserId)
        .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(acceptUserIds)) {
      return;
    }

    List<FriendshipCard> cards = friendshipCardService.listByCondition(sendUserId, acceptUserIds);
    if (CollectionUtils.isEmpty(cards)) {
      return;
    }

    // 在接收礼物人的关系卡中找到自己的卡片，然后累加友谊值
    friendshipCardService.updateBatchById(cards.stream().peek(card -> card.setFriendshipValue(
        card.getFriendshipValue().subtract(giftValue.getGiftValue())))
        .collect(Collectors.toList()));

    // 友谊关系卡活动
    cards.forEach(card -> {

      // Initiate 发送人永远为 userIdOne
      Long userIdOne = card.getInitiate() ? card.getAcceptUserId() : card.getSendUserId();
      Long userIdTwo = card.getInitiate() ? card.getSendUserId() : card.getAcceptUserId();

      weekFriendshipCardCountService.incrThisWeekQuantity(SysOriginPlatformEnum.ASWAT.name(),
          card.getCardType(), userIdOne, userIdTwo,
          -giftValue.getActualAmount().longValue());
    });
  }

}
