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

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.order.infra.database.rds.dao.order.OrderPurchaseHistoryDAO;
import com.red.circle.order.infra.database.rds.entity.order.OrderPurchaseHistory;
import com.red.circle.order.infra.database.rds.service.order.OrderPurchaseHistoryService;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 购买记录 服务实现类
 * </p>
 *
 * @author pengliang
 * @since 2020-03-20
 */
@Service
public class OrderPurchaseHistoryServiceImpl extends
    BaseServiceImpl<OrderPurchaseHistoryDAO, OrderPurchaseHistory> implements
    OrderPurchaseHistoryService {

  @Override
  public boolean existOrder(String orderId) {
    return Optional.ofNullable(
            query().select(OrderPurchaseHistory::getId)
                .eq(OrderPurchaseHistory::getOrderId, orderId)
                .getOne())
        .map(orderPurchaseHistory -> Objects.nonNull(orderPurchaseHistory.getId()))
        .orElse(false);
  }

  @Override
  public boolean existById(String id) {
    return Optional.ofNullable(
            query().select(OrderPurchaseHistory::getId)
                .eq(OrderPurchaseHistory::getId, id)
                .getOne())
        .map(orderPurchaseHistory -> Objects.nonNull(orderPurchaseHistory.getId()))
        .orElse(false);
  }

  @Override
  public OrderPurchaseHistory getOrder(String orderId) {
    return query()
        .eq(OrderPurchaseHistory::getOrderId, orderId)
        .last(PageConstant.LIMIT_ONE)
        .getOne();
  }

  @Override
  public Long getUserIdByOrderId(String orderId) {
    return Optional.ofNullable(query()
            .select(OrderPurchaseHistory::getUserId)
            .eq(OrderPurchaseHistory::getOrderId, orderId)
            .orderByDesc(OrderPurchaseHistory::getId)
            .last(PageConstant.LIMIT_ONE)
            .getOne())
        .map(OrderPurchaseHistory::getUserId)
        .orElse(null);
  }

  @Override
  public BigDecimal purchaseTodayTotal() {
    return baseDAO.purchaseTodayTotal();
  }

  @Override
  public BigDecimal purchaseTodayTotalBySysOrigin(SysOriginPlatformEnum sysOrigin) {
    return baseDAO.purchaseTodayTotalBySysOrigin(sysOrigin);
  }

  @Override
  public List<OrderPurchaseHistory> purchaseTodayBySysOrigin(String sysOrigin, Set<Long> userIds) {
    return baseDAO.purchaseTodayBySysOrigin(sysOrigin, userIds);
  }

  public BigDecimal getPurchaseTotalByUserId(Long userId) {
    return baseDAO.getPurchaseTotalByUserId(userId);
  }

}
