package com.zsElectric.boot.business.quartz;

import com.zsElectric.boot.business.service.ChargeOrderInfoService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;

/**
 * 订单补偿定时任务
 * 针对异常订单做补偿机制
 *
 * @author zsElectric
 * @since 2026-01-21
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class CompensateOrderJob {

    private final ChargeOrderInfoService chargeOrderInfoService;

    @Autowired
    @Qualifier("businessTaskExecutor")
    private ThreadPoolTaskExecutor businessTaskExecutor;

    /**
     * 充电订单补偿定时任务 - 每10分钟执行一次
     * 查找状态为3(已完成)或5(未成功充电)且充电数据为0的订单
     * 优先通过third_party_api_log表获取推送数据，备选通过third_party_charge_status表查询
     */
//    @Scheduled(cron = "0 0/10 * * * ?")
    public void compensateChargeOrder() {
        log.info("开始执行充电订单补偿定时任务");

        try {
            CompletableFuture<String> stringCompletableFuture = executeTaskWithResult();
            log.info("充电订单补偿定时任务执行完成: {}", stringCompletableFuture.get());
        } catch (Exception e) {
            log.error("执行充电订单补偿任务失败", e);
        }
    }

    /**
     * 执行有返回值的异步任务
     */
    public CompletableFuture<String> executeTaskWithResult() {
        // 使用 supplyAsync 并指定自定义线程池
        return CompletableFuture.supplyAsync(() -> {
            // 这里是你的异步任务逻辑
            System.out.println("执行线程: " + Thread.currentThread().getName());
            String result = chargeOrderInfoService.compensateUnprocessedOrders();
            return "处理结果: " + result;
        }, businessTaskExecutor); // 关键：传入线程池实例
    }
}