package com.red.circle.game.fruit.infrastructure.database.repository.impl;


import com.red.circle.framework.mybatis.constant.PageConstant;
import com.red.circle.framework.mybatis.service.impl.BaseServiceImpl;
import com.red.circle.game.fruit.infrastructure.database.dao.GameFruitUserTaskReceiveDAO;
import com.red.circle.game.fruit.infrastructure.database.entity.GameFruitUserTaskReceive;
import com.red.circle.game.fruit.infrastructure.database.repository.GameFruitUserTaskReceiveService;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.date.LocalDateUtils;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 摩天轮游戏任务领取用户 服务实现类.
 * </p>
 *
 * @author zongpubin on 2023-12-15 15:05
 */
@Service
@RequiredArgsConstructor
public class GameFruitUserTaskReceiveServiceImpl extends
    BaseServiceImpl<GameFruitUserTaskReceiveDAO, GameFruitUserTaskReceive> implements
    GameFruitUserTaskReceiveService {

  @Override
  public Map<Long, GameFruitUserTaskReceive> getByUserIdAndAwardId(Long userId,
      Set<Long> awardIds) {
    if (CollectionUtils.isEmpty(awardIds)) {
      return CollectionUtils.newHashMap();
    }
    return Optional.ofNullable(query().eq(GameFruitUserTaskReceive::getUserId, userId)
            .in(GameFruitUserTaskReceive::getAwardId, awardIds)
            .in(GameFruitUserTaskReceive::getReceiveDate,
                Arrays.asList(LocalDateUtils.nowToInteger(), LocalDateUtils.nowWeekMondayToInteger()))
            .list())
        .map(taskReceives -> taskReceives.stream()
            .filter(Objects::nonNull)
            .collect(Collectors.toMap(GameFruitUserTaskReceive::getAwardId, v -> v)))
        .orElse(CollectionUtils.newHashMap());
  }

  @Override
  public Set<Long> getReceiveUsers(String originSys) {

    return query().eq(GameFruitUserTaskReceive::getSysOrigin, originSys)
        .orderByDesc(GameFruitUserTaskReceive::getCreateTime).last(
            PageConstant.formatLimit(30)).list().stream().map(GameFruitUserTaskReceive::getUserId)
        .collect(
            Collectors.toSet());
  }

  @Override
  public GameFruitUserTaskReceive checkReceive(Long awardId, Long userId, Integer receiveDate) {
    return query().eq(GameFruitUserTaskReceive::getAwardId, awardId)
        .eq(GameFruitUserTaskReceive::getUserId, userId)
        .eq(GameFruitUserTaskReceive::getReceiveDate, receiveDate)
        .last(PageConstant.LIMIT_ONE).getOne();
  }
}
