package com.red.circle.other.infra.database.rds.service.game.impl;

import com.google.common.collect.Maps;
import com.red.circle.framework.mybatis.constant.PageConstant;
import com.red.circle.framework.mybatis.service.impl.BaseServiceImpl;
import com.red.circle.other.infra.database.rds.dao.game.LuckyGiftProbabilityDAO;
import com.red.circle.other.infra.database.rds.entity.game.LuckyGiftProbability;
import com.red.circle.other.infra.database.rds.service.game.LuckyGiftProbabilityService;
import com.red.circle.other.inner.model.cmd.game.GameLuckGiftProbabilityConfigQryCmd;
import com.red.circle.tool.core.text.StringUtils;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 礼物规格概率基础配置.
 * </p>
 *
 * @author pengshigang on 2023-05-05 17:18
 */
@Service
public class LuckyGiftProbabilityServiceImpl extends
    BaseServiceImpl<LuckyGiftProbabilityDAO, LuckyGiftProbability> implements
    LuckyGiftProbabilityService {

  @Override
  public List<LuckyGiftProbability> listByStandardId(Long standardId) {

    return query()
        .eq(LuckyGiftProbability::getStandardId, standardId)
        .last(PageConstant.formatLimit(5))
        .list();
  }

  @Override
  public LuckyGiftProbability getOneByStandardIdByQuantity(Long standardId, Integer quantity) {

    return query()
        .eq(LuckyGiftProbability::getGiftQuantity, quantity)
        .eq(LuckyGiftProbability::getStandardId, standardId)
        .last(PageConstant.LIMIT_ONE)
        .getOne();
  }

  @Override
  public Map<Long, List<LuckyGiftProbability>> getLuckyGiftProbabilityMap(Set<Long> standardIds) {
    return Optional.ofNullable(query().in(LuckyGiftProbability::getStandardId, standardIds).list())
        .map(probabilityList -> probabilityList.stream()
            .collect(Collectors.groupingBy(LuckyGiftProbability::getStandardId)))
        .orElse(Maps.newHashMap());
  }

  @Override
  public List<LuckyGiftProbability> getLuckyGiftProbabilityByStandardId(Long id) {
    return query()
        .eq(Objects.nonNull(id), LuckyGiftProbability::getStandardId, id).list();
  }

  @Override
  public Boolean deleteByStandardId(Long id) {
    return delete().eq(LuckyGiftProbability::getStandardId, id).execute();
  }

  @Override
  public List<LuckyGiftProbability> getLuckyGiftProbabilityConfig(
      GameLuckGiftProbabilityConfigQryCmd query) {
    return query().eq(
            StringUtils.isNotBlank(query.getSysOrigin()), LuckyGiftProbability::getSysOrigin,
            query.getSysOrigin())
        .eq(Objects.nonNull(query.getStandardId()), LuckyGiftProbability::getStandardId,
            query.getStandardId())
        .orderByAsc(LuckyGiftProbability::getSort)
        .list();
  }

}
