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

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.red.circle.common.business.core.enums.SysOriginPlatformEnum;
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.GameKingActivityRecordDAO;
import com.red.circle.other.infra.database.rds.entity.game.GameKingActivityRecord;
import com.red.circle.other.infra.database.rds.service.game.GameKingActivityRecordService;
import com.red.circle.tool.core.collection.CollectionUtils;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 游戏王临时统计表 服务实现类.
 * </p>
 *
 * @author pengshigang
 * @since 2021-12-28
 */
@Service
@RequiredArgsConstructor
public class GameKingActivityRecordServiceImpl extends
    BaseServiceImpl<GameKingActivityRecordDAO, GameKingActivityRecord> implements
    GameKingActivityRecordService {

  private final GameKingActivityRecordDAO gameKingActivityRecordDAO;

  @Override
  public Map<Long, List<GameKingActivityRecord>> listFiveWeeks(SysOriginPlatformEnum sysOrigin,
      List<Long> rounds) {

    if (CollectionUtils.isEmpty(rounds) || rounds.size() <= 0) {
      return Maps.newHashMap();
    }

    return Optional.ofNullable(
            query()
                .eq(GameKingActivityRecord::getSysOrigin, sysOrigin.name())
                .in(GameKingActivityRecord::getRounds, rounds)
                .orderByDesc(GameKingActivityRecord::getProcess)
                .last(PageConstant.formatLimit(2000))
                .list()
        ).map(recordList -> recordList.stream()
            .collect(Collectors.groupingBy(GameKingActivityRecord::getRounds)))
        .orElse(Maps.newHashMap());

  }

  @Override
  public List<Long> listFiveWeeksRounds(SysOriginPlatformEnum sysOrigin) {
    return Optional.ofNullable(gameKingActivityRecordDAO.listFiveWeeksRounds(sysOrigin.name()))
        .orElse(Lists.newArrayList());
  }

  @Override
  public Set<Long> userIdsByRounds(List<Long> rounds, SysOriginPlatformEnum sysOrigin) {
    return Optional.ofNullable(query()
            .eq(GameKingActivityRecord::getSysOrigin, sysOrigin.name())
            .in(GameKingActivityRecord::getRounds, rounds)
            .list()).map(recordList -> recordList.stream()
            .map(GameKingActivityRecord::getUserId).collect(Collectors.toSet()))
        .orElse(Sets.newHashSet());
  }
}
