package edu.whut.trigger.job;
import edu.whut.domain.order.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 超时关单
 */
@Slf4j
@Component()
public class TimeoutCloseOrderJob {

    @Resource
    private IOrderService orderService;

    /**
     * 每 3 分钟执行一次，扫描超时未支付订单 ，尽快让用户释放锁单。
     */
    @Scheduled(cron = "0 0/3 * * * ?")
    public void exec() {
        try {
            log.info("任务：每隔3分钟查询是否有订单超15分钟仍未支付。");
            List<String> orderIds = orderService.queryTimeoutCloseOrderList();
            if (null == orderIds || orderIds.isEmpty()) {
                log.info("定时任务，超时15分钟订单关闭，暂无超时未支付订单 orderIds is null");
                return;
            }
            // 遍历订单，逐一关闭并记录结果
            for (String orderId : orderIds) {
                // 设置 STATUS为CLOSE
                boolean status = orderService.changeOrderClose(orderId);
                log.info("定时任务，超时15分钟订单关闭 orderId: {} status：{}", orderId, status);
            }
        } catch (Exception e) {
            log.error("定时任务，超时15分钟订单关闭失败", e);
        }
    }

}
