package com.red.circle.order.infra.database.rds.service.pay.impl;

import com.red.circle.framework.mybatis.service.impl.BaseServiceImpl;
import com.red.circle.order.infra.database.rds.dao.pay.PayApplicationCommodityDAO;
import com.red.circle.order.infra.database.rds.entity.pay.PayApplicationCommodity;
import com.red.circle.order.infra.database.rds.service.pay.PayApplicationCommodityService;
import com.red.circle.order.inner.model.enums.PayApplicationCommodityType;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.text.StringUtils;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 应用商品 服务实现类.
 * </p>
 *
 * @author pengshigang
 * @since 2021-12-08
 */
@Service
public class PayApplicationCommodityServiceImpl extends
    BaseServiceImpl<PayApplicationCommodityDAO, PayApplicationCommodity> implements
    PayApplicationCommodityService {

  @Override
  public PayApplicationCommodity getAppCommodity(Long id, Long applicationId) {
    return query()
        .eq(PayApplicationCommodity::getId, id)
        .eq(PayApplicationCommodity::getApplicationId, applicationId)
        .getOne();
  }


  @Override
  public List<PayApplicationCommodity> listCommodityByApplicationCountry(Long applicationId,
      Long payCountryId, PayApplicationCommodityType type, String regionId) {

    return query()
        .eq(PayApplicationCommodity::getApplicationId, applicationId)
        .eq(PayApplicationCommodity::getType, type)
        .eq(PayApplicationCommodity::getShelf, Boolean.TRUE)
        // 为了兼容多个系统,这两个需要判断
        .eq(StringUtils.isNotBlank(regionId), PayApplicationCommodity::getRegionId, regionId)
        .eq(Objects.nonNull(payCountryId), PayApplicationCommodity::getPayCountryId, payCountryId)
        .list();
  }

  @Override
  public Map<Long, List<PayApplicationCommodity>> mapCommodityListByCondition(Long applicationId,
      Set<Long> payCountryIds, PayApplicationCommodityType type, String regionId) {

    List<PayApplicationCommodity> commodities = query()
        .eq(PayApplicationCommodity::getApplicationId, applicationId)
        .in(PayApplicationCommodity::getPayCountryId, payCountryIds)
        .eq(PayApplicationCommodity::getType, type)
        .eq(PayApplicationCommodity::getRegionId, regionId)
        .eq(PayApplicationCommodity::getShelf, Boolean.TRUE)
        .orderByAsc(PayApplicationCommodity::getAmountUsd)
        .list();

    if (CollectionUtils.isEmpty(commodities)) {
      return CollectionUtils.newHashMap();
    }

    return commodities.stream()
        .collect(Collectors.groupingBy(PayApplicationCommodity::getPayCountryId));
  }
}
