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

import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import com.red.circle.other.app.convertor.material.GiftAppConvertor;
import com.red.circle.other.app.dto.clientobject.gift.GiftConfigCO;
import com.red.circle.other.app.dto.cmd.activity.WeekStarGiftQueryCmd;
import com.red.circle.other.infra.database.rds.service.gift.GiftConfigService;
import com.red.circle.other.infra.database.rds.service.sys.WeekStarGiftService;
import com.red.circle.other.infra.database.rds.service.sys.WeekStarGroupService;
import com.red.circle.other.inner.enums.activity.WeekStarGiftTypeEnum;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 获取当前周星礼物.
 *
 * @author pengliang on 2021/4/23
 */
@Component
@RequiredArgsConstructor
public class WeekStarThisWeeksGiftQueryExe {

  private final GiftConfigService giftConfigService;
  private final GiftAppConvertor giftAppConvertor;
  private final WeekStarGiftService weekStarGiftService;
  private final WeekStarGroupService weekStarGroupService;

  public List<GiftConfigCO> execute(WeekStarGiftQueryCmd cmd) {
    return listWeeksGift(cmd);
  }

  private List<GiftConfigCO> listWeeksGift(WeekStarGiftQueryCmd cmd) {
    return Optional.ofNullable(getGiftConfig(cmd))
        .map(this::sortedGiftGoldsAsc)
        .orElse(Lists.newArrayList());
  }

  private List<GiftConfigCO> sortedGiftGoldsAsc(List<GiftConfigCO> giftConfigs) {
    return giftConfigs.stream()
        .sorted(Comparator.comparing(GiftConfigCO::getGiftCandy)).collect(Collectors.toList());
  }

  private List<GiftConfigCO> getGiftConfig(WeekStarGiftQueryCmd cmd) {
    return weekStarGroupService.getByTypeOne(cmd.requireReqSysOriginEnum(), cmd.getType())
        .map(weekStarGroup -> giftAppConvertor.toGiftConfigCO(giftConfigService
            .listByIds(weekStarGiftService.listGiftIdsByGroupId(weekStarGroup.getId()))))
        .orElseGet(
            // 无数据填充
            () -> Objects.equals(cmd.getType(), WeekStarGiftTypeEnum.THIS_WEEK)
                ? weekStarGroupService.getByTypeOne(cmd.requireReqSysOriginEnum(),
                    WeekStarGiftTypeEnum.THIS_WEEK)
                .map(weekStarGroup -> giftAppConvertor.toGiftConfigCO(giftConfigService
                    .listByIds(weekStarGiftService.listGiftIdsByGroupId(weekStarGroup.getId()))))
                .orElse(Lists.newArrayList())
                : Lists.newArrayList());
  }

}
