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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.red.circle.common.business.dto.cmd.AppExtCommand;
import com.red.circle.other.app.dto.clientobject.gift.ActivityGiftCO;
import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.domain.gateway.user.ability.UserRegionGateway;
import com.red.circle.other.domain.model.user.UserProfile;
import com.red.circle.other.infra.database.cache.service.other.BannerCacheService;
import com.red.circle.other.infra.database.mongo.entity.sys.ActivityConfig;
import com.red.circle.other.infra.database.mongo.service.sys.ActivityConfigService;
import com.red.circle.other.infra.database.rds.entity.gift.GiftConfig;
import com.red.circle.other.infra.database.rds.entity.sys.BannerConfig;
import com.red.circle.other.infra.database.rds.service.gift.GiftConfigService;
import com.red.circle.other.infra.database.rds.service.sys.BannerConfigService;
import com.red.circle.tool.core.collection.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

import com.red.circle.tool.core.text.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 获取活动礼物列表.
 *
 * @author system
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ActivityGiftListQryExe {

  private final ActivityConfigService activityConfigService;
  private final GiftConfigService giftConfigService;
  private final BannerConfigService bannerConfigService;
  private final UserProfileGateway userProfileGateway;
  private final UserRegionGateway userRegionGateway;

  public List<ActivityGiftCO> execute(AppExtCommand cmd) {
    // 获取进行中的活动
    List<ActivityConfig> activities = activityConfigService.listOngoingActivities(cmd.getReqSysOrigin().getOriginChild());

    if (CollectionUtils.isEmpty(activities)) {
      return new ArrayList<>();
    }

    // 构建 giftId -> bannerId 的映射（取第一个遇到的 bannerId）
    Map<Long, ActivityConfig> giftIdToBannerIdMap = new HashMap<>();
    List<Long> giftIds = new ArrayList<>();

    for (ActivityConfig activity : activities) {
      if (CollectionUtils.isNotEmpty(activity.getGiftIds())) {
        for (Object giftIdObj : activity.getGiftIds()) {
          Long giftId = Long.valueOf(giftIdObj.toString());
          if (!giftIdToBannerIdMap.containsKey(giftId)) {
            giftIdToBannerIdMap.put(giftId, activity);
            giftIds.add(giftId);
          }
        }
      }
    }

    if (giftIds.isEmpty()) {
      return new ArrayList<>();
    }

    String regionId = userRegionGateway.getRegionId(cmd.requiredReqUserId());
    UserProfile userProfile = userProfileGateway.getByUserId(cmd.requiredReqUserId());
    String countryCode = userProfile.getCountryCode();

    // 收集所有需要查询的 bannerId（去重）
      List<Long> bannerIds = giftIdToBannerIdMap.values().stream()
              .filter(Objects::nonNull).map(ActivityConfig::getBannerId).distinct().collect(Collectors.toList());

    Map<Long, BannerConfig> bannerUrlMap;
    if (!bannerIds.isEmpty()) {
      LambdaQueryWrapper<BannerConfig> query = Wrappers.<BannerConfig>lambdaQuery()
              .in(BannerConfig::getId, bannerIds);
      bannerUrlMap = bannerConfigService.list(query).stream()
              .filter(bannerCache -> StringUtils.isBlank(bannerCache.getRegions()) || bannerCache.getRegions().contains(regionId))
              .filter(bannerCache -> StringUtils.isBlank(bannerCache.getCountryCode()) || bannerCache.getCountryCode().contains(countryCode))
              .collect(Collectors.toMap(BannerConfig::getId, e -> e, (u1, u2) -> u1));
    } else {
        bannerUrlMap = new HashMap<>();
    }
      // 查询礼物配置
    List<GiftConfig> giftConfigs = giftConfigService.listByIds(giftIds);
    giftConfigs = giftConfigs.stream().filter(gift -> StringUtils.isBlank(gift.getRegions()) || gift.getRegions().contains(regionId != null ? regionId : "null")).toList();
    if (CollectionUtils.isEmpty(giftConfigs)) {
      return new ArrayList<>();
    }

    // 转换为 CO，并设置 bannerUrl
    return giftConfigs.stream()
            .map(giftConfig -> convertToActivityGiftCO(giftConfig, giftIdToBannerIdMap, bannerUrlMap))
            .collect(Collectors.toList());
  }

  private ActivityGiftCO convertToActivityGiftCO(GiftConfig giftConfig,
                                                 Map<Long, ActivityConfig> giftIdToBannerIdMap,
                                                 Map<Long, BannerConfig> bannerUrlMap) {
    ActivityGiftCO activityGiftCO = new ActivityGiftCO();
    activityGiftCO.setId(giftConfig.getId());
    activityGiftCO.setGiftCode(giftConfig.getGiftCode());
    activityGiftCO.setGiftPhoto(giftConfig.getGiftPhoto());
    activityGiftCO.setGiftSourceUrl(giftConfig.getGiftSourceUrl());
    activityGiftCO.setGiftCandy(giftConfig.getGiftCandy());
    activityGiftCO.setSpecial(giftConfig.getSpecial());
    activityGiftCO.setType(giftConfig.getType());
    activityGiftCO.setGiftTab(giftConfig.getGiftTab());
    activityGiftCO.setGiftName(giftConfig.getGiftName());
    activityGiftCO.setExpiredTime(giftConfig.getExpiredTime());

    // 设置 bannerUrl
    ActivityConfig activityConfig = giftIdToBannerIdMap.get(giftConfig.getId());
    BannerConfig bannerConfig = (activityConfig.getBannerId() != null) ? bannerUrlMap.get(activityConfig.getBannerId()) : null;
    if (bannerConfig != null) {
      activityGiftCO.setBannerUrl(bannerConfig.getCover());
      activityGiftCO.setJumpUrl(bannerConfig.getParams());
    }

    activityGiftCO.setActivityId(activityConfig.getId());

    return activityGiftCO;
  }
}
