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


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.pet.PetIncomeReceiveDAO;
import com.red.circle.other.infra.database.rds.entity.pet.PetIncomeReceive;
import com.red.circle.other.infra.database.rds.enums.pet.PetIncomeType;
import com.red.circle.other.infra.database.rds.service.pet.PetIncomeReceiveService;
import com.red.circle.tool.core.collection.CollectionUtils;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
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
 * @since 2021-10-14
 */
@Service
public class PetIncomeReceiveServiceImpl extends
    BaseServiceImpl<PetIncomeReceiveDAO, PetIncomeReceive> implements PetIncomeReceiveService {

  @Override
  public List<PetIncomeReceive> flowIncome(Long userId, Long lastId) {
    return query()
        .eq(PetIncomeReceive::getIncomeUserId, userId)
        .lt(Objects.nonNull(lastId), PetIncomeReceive::getId, lastId)
        .orderByDesc(PetIncomeReceive::getId)
        .last(PageConstant.DEFAULT_LIMIT)
        .list();
  }

  @Override
  public List<PetIncomeReceive> flowStolen(Long userId, Long lastId) {
    return query()
        .eq(PetIncomeReceive::getPetUserId, userId)
        .eq(PetIncomeReceive::getType, PetIncomeType.STEAL)
        .lt(Objects.nonNull(lastId), PetIncomeReceive::getId, lastId)
        .orderByDesc(PetIncomeReceive::getId)
        .last(PageConstant.DEFAULT_LIMIT)
        .list();
  }

  @Override
  public Map<Long, Boolean> mapNotStealableByIncomeDetailsIds(Long userId,
      Set<Long> incomeDetailsIds) {
    if (CollectionUtils.isEmpty(incomeDetailsIds) || Objects.isNull(userId)) {
      return CollectionUtils.newHashMap();
    }

    return Optional.ofNullable(query()
            .select(PetIncomeReceive::getIncomeDetailsId)
            .eq(PetIncomeReceive::getIncomeUserId, userId)
            .eq(PetIncomeReceive::getType, PetIncomeType.STEAL)
            .in(PetIncomeReceive::getIncomeDetailsId, incomeDetailsIds)
            .list())
        .map(petIncomeReceives -> petIncomeReceives.stream()
            .collect(Collectors.groupingBy(PetIncomeReceive::getIncomeDetailsId))
            .entrySet()
            .stream()
            .collect(Collectors.toMap(Entry::getKey,
                entry -> CollectionUtils.isNotEmpty(entry.getValue())))
        )
        .orElseGet(CollectionUtils::newHashMap);
  }
}
