package com.seer.teach.mall.app.order.job;

import com.seer.teach.mall.app.order.service.IAppOrderService;
import com.seer.teach.mall.entity.OrderEntity;
import com.seer.teach.mall.request.OrderUpdateReq;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
@ConditionalOnProperty(prefix = "mall.order", name = "confirm-receive.enabled", havingValue = "true", matchIfMissing = true)
public class OrderAutoConfirmReceiveJob {

    @Autowired
    private IAppOrderService orderService;

    // 自动确认收货时间
    @Value("${mall.order.confirm-receive.days:15}")
    private int autoConfirmReceiveDays;

    @XxlJob("autoConfirmReceiptJob")
    public void processAutoConfirmReceive() {
        log.info("开始处理订单自动确认收货任务");

        // 查询超过15天未确认收货的订单
        List<OrderEntity> overdueOrders = orderService.getOverdueOrders(autoConfirmReceiveDays);

        for (OrderEntity order : overdueOrders) {
            try {
                // 执行自动确认收货逻辑
                OrderUpdateReq req = new OrderUpdateReq();
                req.setOrderId(order.getId());
                orderService.receiveOrder(req);

                log.info("订单自动确认收货成功，订单号: {}", order.getOrderSn());
            } catch (Exception e) {
                log.error("订单自动确认收货失败，订单号: {}", order.getOrderSn(), e);
            }
        }

        log.info("自动确认收货任务执行完成，共处理 {} 笔订单", overdueOrders.size());
    }
}
