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.xxl.job.core.context.XxlJobHelper;
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.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

/**
 * 订单过期处理任务
 * 仅在未启用 RocketMQ 延迟消息时启动
 */
@Slf4j
@Component
@ConditionalOnProperty(prefix = "mall.order", name = "delay.enabled", havingValue = "false", matchIfMissing = false)
public class OrderExpireJob {

    @Autowired
    private IAppOrderService orderService;

    // 订单过期时间（分钟）
    @Value("${mall.order.expire.time:30}")
    private int orderExpireTime;


    /**
     * 订单过期检查任务
     * 每5分钟执行一次
     */
    @XxlJob("orderExpireCheckJob")
    public void orderExpireCheckJob() {
        try {
            log.info("开始执行订单过期检查任务");

            processExpiredOrders();

            log.info("订单过期检查任务执行完成");
        } catch (Exception e) {
            log.error("订单过期检查任务执行异常", e);

        }
    }

    /**
     * 处理过期订单
     */
    public void processExpiredOrders() {
        try {
            log.info("开始处理过期订单，订单过期时间: {}分钟", orderExpireTime);
            // 1. 查询所有未支付的订单
            List<OrderEntity> unpaidOrders = orderService.getUnpaidOrders();
            log.info("查询到未支付订单数量: {}", unpaidOrders.size());

            // 2. 遍历订单，检查是否过期
            int expiredCount = 0;
            for (OrderEntity order : unpaidOrders) {
                if (isOrderExpired(order)) {
                    try {
                        // 3. 处理过期订单
                        orderService.expireOrder(order);
                        expiredCount++;
                        log.info("订单过期处理完成，订单号: {}, 创建时间: {}",
                                order.getOrderSn(), order.getCreateTime());
                    } catch (Exception e) {
                        log.error("处理订单过期失败，订单号: {}", order.getOrderSn(), e);
                    }
                }
            }

            log.info("过期订单处理完成，总共处理: {}个订单", expiredCount);
        } catch (Exception e) {
            log.error("处理过期订单异常", e);
            XxlJobHelper.handleFail(e.getMessage());
        }
    }

    /**
     * 判断订单是否过期
     * @param order 订单实体
     * @return 是否过期
     */
    private boolean isOrderExpired(OrderEntity order) {
        if (order.getAddTime() == null) {
            return false;
        }

        // 计算订单创建时间到现在的时间差
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime orderCreateTime = order.getAddTime();
        long minutesBetween = ChronoUnit.MINUTES.between(orderCreateTime, now);

        // 如果时间差大于配置的过期时间，则订单已过期
        boolean expired = minutesBetween >= orderExpireTime;

        if (expired) {
            log.debug("订单已过期，订单号: {}, 创建时间: {}, 当前时间: {}, 时间差: {}分钟, 过期时间: {}分钟",
                    order.getOrderSn(), orderCreateTime, now, minutesBetween, orderExpireTime);
        }

        return expired;
    }
}
