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

import com.red.circle.framework.mybatis.service.impl.BaseServiceImpl;
import com.red.circle.order.infra.database.rds.dao.order.OrderApplePendingRenewalInfoDAO;
import com.red.circle.order.infra.database.rds.dto.AppleRenewalDTO;
import com.red.circle.order.infra.database.rds.entity.order.OrderApplePendingRenewalInfo;
import com.red.circle.order.infra.database.rds.service.order.OrderApplePendingRenewalInfoService;
import com.red.circle.tool.core.date.LocalDateTimeUtils;
import com.red.circle.tool.core.date.TimestampUtils;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * <p>
 * ios等待订阅信息 服务实现类
 * </p>
 *
 * @author pengliang
 * @since 2020-04-05
 */
@RequiredArgsConstructor
@Service
public class OrderApplePendingRenewalInfoServiceImpl extends
    BaseServiceImpl<OrderApplePendingRenewalInfoDAO, OrderApplePendingRenewalInfo> implements
    OrderApplePendingRenewalInfoService {

  private final OrderApplePendingRenewalInfoDAO orderApplePendingRenewalInfoDAO;

  @Override
  public void saveLatestPendingRenewalInfo(
      OrderApplePendingRenewalInfo orderApplePendingRenewalInfo) {
    OrderApplePendingRenewalInfo pendingRenewalInfo = query()
        .eq(OrderApplePendingRenewalInfo::getUserId, orderApplePendingRenewalInfo.getUserId())
        .eq(OrderApplePendingRenewalInfo::getProductId, orderApplePendingRenewalInfo.getProductId())
        .eq(OrderApplePendingRenewalInfo::getOriginalTransactionId,
            orderApplePendingRenewalInfo.getOriginalTransactionId())
        .getOne();

    if (Objects.isNull(pendingRenewalInfo)) {
      save(orderApplePendingRenewalInfo);
      return;
    }
    orderApplePendingRenewalInfo.setId(pendingRenewalInfo.getId());
    orderApplePendingRenewalInfo.setUpdateTime(TimestampUtils.now());
    updateSelectiveById(orderApplePendingRenewalInfo);
  }

  @Override
  public List<AppleRenewalDTO> getExpiringSoonReceipt(LocalDateTime checkDate, Long lastId,
      Integer limit) {
    return orderApplePendingRenewalInfoDAO.findExpiringSoonUserSubscription(
        LocalDateTimeUtils.format(checkDate, "yyyy-MM-dd HH:mm:ss")
        , lastId, limit);
  }

}
