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

import com.google.common.collect.Sets;
import com.red.circle.common.business.dto.cmd.AppExtCommand;
import com.red.circle.other.app.convertor.material.GiftAppConvertor;
import com.red.circle.other.app.dto.clientobject.gift.GiftConfigCO;
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.GiftCacheService;
import com.red.circle.other.inner.model.dto.material.GiftConfigDTO;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.text.StringUtils;

import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 获取礼物配置列表.
 *
 * @author pengliang on 2020/11/18
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class SysGiftConfigListQryExe {

  private final GiftAppConvertor giftAppConvertor;
  private final GiftCacheService giftCacheService;
  private final UserRegionGateway userRegionGateway;
  private final UserProfileGateway userProfileGateway;


  public List<GiftConfigCO> execute(AppExtCommand cmd) {

    List<GiftConfigDTO> giftConfigCaches = giftCacheService
        .listBySysOrigin(cmd.requireReqSysOriginEnum());

    if (CollectionUtils.isEmpty(giftConfigCaches)) {
      return CollectionUtils.newArrayList();
    }

    // 使用Stream API将List<User>中的userId转换为Set<Long>
    Set<Long> userIds = giftConfigCaches.stream()
            .map(GiftConfigDTO::getUserId)
            .collect(Collectors.toSet());
    List<UserProfile> userProfiles = !userIds.isEmpty() ? userProfileGateway.listByUserIds(userIds) : new ArrayList<>();

    // 获得用户区域
    String regionId = userRegionGateway.getRegionId(cmd.requiredReqUserId());

    log.info("userRegionId:{}", regionId);

    // 过滤
    List<GiftConfigCO> giftConfigs = giftAppConvertor.toListGiftConfigCO(
        giftConfigCaches.stream()
            .filter(giftConfigCache ->
                StringUtils.isBlank(giftConfigCache.getRegions()) || giftConfigCache.getRegions().contains(regionId != null ? regionId : "null"))
            .map(giftConfigDTO -> giftConfigDTO.setGiftCandy(giftConfigDTO.getGiftCandy().setScale(0, RoundingMode.DOWN)))
            .toList());

    if (!userIds.isEmpty()) {
      giftConfigs.forEach(item -> {
        if (item.getUserId() != null) {
          userProfiles.stream().filter(user -> user.getId().equals(item.getUserId())).findFirst().ifPresent(userProfile -> item.setAccount(userProfile.getActualAccount()));
        }
      });
    }
    return giftConfigs;

  }

}
