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

import com.red.circle.common.business.dto.cmd.app.AppUserIdCmd;
import com.red.circle.other.app.dto.clientobject.gift.GiftWallCO;
import com.red.circle.other.infra.database.rds.entity.gift.GiftConfig;
import com.red.circle.other.infra.database.rds.entity.gift.GiftWall;
import com.red.circle.other.infra.database.rds.service.gift.GiftConfigService;
import com.red.circle.other.infra.database.rds.service.gift.GiftWallService;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.json.JacksonUtils;
import com.red.circle.tool.core.num.NumUtils;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 用户礼物墙.
 *
 * @author pengliang on 2021/1/12
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class UserGiftWallListQryExe {

  private final GiftWallService giftWallService;
  private final GiftConfigService giftConfigService;

  public List<GiftWallCO> execute(AppUserIdCmd cmd) {
    List<GiftWall> giftWalls = giftWallService.listTopByUserId(cmd.getUserId());

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

    Map<Long, GiftConfig> giftConfigInfoMap = giftConfigService
        .mapByIds(giftWalls.stream().map(GiftWall::getGiftId)
            .filter(Objects::nonNull)
            .collect(Collectors.toSet()));

    return giftWalls.stream().map(giftWall -> {
      GiftConfig giftConfig = giftConfigInfoMap.get(giftWall.getGiftId());
      if (Objects.isNull(giftConfig)) {
        log.warn("User gift data error：{},{}", JacksonUtils.toJson(cmd),
            JacksonUtils.toJson(giftWall));
        return null;
      }
      return new GiftWallCO()
          .setId(giftWall.getId())
          .setUserId(giftWall.getUserId())
          .setGiftId(giftConfig.getId())
          .setGiftPhoto(giftConfig.getGiftPhoto())
          .setQuantity(NumUtils.formatLong(giftWall.getQuantity()));
    }).filter(Objects::nonNull).collect(Collectors.toList());
  }
}
