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


import com.google.common.collect.Lists;
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.game.fruit.infrastructure.database.dao.GameFruitUserOpenedAwardDAO;
import com.red.circle.game.fruit.infrastructure.database.entity.GameFruitUserOpenedAward;
import com.red.circle.game.fruit.infrastructure.database.repository.GameFruitUserOpenedAwardService;
import com.red.circle.tool.core.date.LocalDateUtils;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户已开的宝箱奖励 服务实现类.
 * </p>
 *
 * @author zongpubin on 2023-12-12 14:19
 */
@Service
public class GameFruitUserOpenedAwardServiceImpl extends
    BaseServiceImpl<GameFruitUserOpenedAwardDAO, GameFruitUserOpenedAward> implements
    GameFruitUserOpenedAwardService {

  @Override
  public Map<Long, GameFruitUserOpenedAward> getByUserIdAndDate(Long userId, Integer date) {
    return Optional.ofNullable(
            query().eq(GameFruitUserOpenedAward::getUserId, userId)
                .eq(GameFruitUserOpenedAward::getOpenDate, date).list()
        ).map(openedAwards -> openedAwards.stream()
            .collect(
                Collectors.toMap(GameFruitUserOpenedAward::getRuleId, Function.identity(),
                    (v0, v1) -> v0)))
        .orElse(Maps.newHashMap());
  }

  @Override
  public GameFruitUserOpenedAward checkOpenBox(Long userId, Long ruleId) {
    return Optional.ofNullable(query().eq(GameFruitUserOpenedAward::getUserId, userId)
            .eq(GameFruitUserOpenedAward::getOpenDate, LocalDateUtils.nowToInteger())
            .eq(GameFruitUserOpenedAward::getRuleId, ruleId).last(PageConstant.LIMIT_ONE).getOne())
        .orElse(null);
  }

  @Override
  public void deleteByUserId(Long userId, String boxType) {
    delete().eq(GameFruitUserOpenedAward::getUserId, userId)
        .eq(GameFruitUserOpenedAward::getOpenDate, LocalDateUtils.nowToInteger())
        .eq(GameFruitUserOpenedAward::getBoxType,boxType)
        .execute();
  }

  @Override
  public List<GameFruitUserOpenedAward> getByUserId(Long userId, String boxType) {
    return Optional.ofNullable(query().eq(GameFruitUserOpenedAward::getUserId, userId)
            .eq(GameFruitUserOpenedAward::getOpenDate, LocalDateUtils.nowToInteger())
            .eq(GameFruitUserOpenedAward::getBoxType,boxType)
            .list())
        .orElse(Lists.newArrayList());
  }
}
