package com.izouma.nineth.service;

import com.izouma.nineth.config.GeneralProperties;
import com.izouma.nineth.domain.Order;
import com.izouma.nineth.enums.OrderStatus;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.OrderRepo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
@AllArgsConstructor
public class OrderCancelService {
    private final GeneralProperties generalProperties;
    private final OrderRepo         orderRepo;
    private final OrderService      orderService;

    @Scheduled(fixedRate = 30000)
    public void batchCancel() {
        List<Order> orders = orderRepo.findByStatusAndCreatedAtBeforeAndDelFalse(OrderStatus.NOT_PAID,
                LocalDateTime.now().minusSeconds(210));
        orders.parallelStream().forEach(o -> {
            try {
                Order order = orderRepo.findById(o.getId()).orElseThrow(new BusinessException("订单不存在"));
                if (order.getStatus() == OrderStatus.NOT_PAID) {
                    orderService.cancel(order);
                }
            } catch (Exception e) {
                log.error("取消订单错误 " + o.getId(), e);
            }
        });
    }
}
