package com.fs.his.task;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.fs.course.service.IFsUserCourseOrderService;
import com.fs.his.config.StoreConfig;
import com.fs.his.domain.FsPackageOrder;
import com.fs.his.domain.FsStoreOrder;
import com.fs.his.param.FsPackageOrderCancelParam;
import com.fs.his.service.IFsPackageOrderService;
import com.fs.his.service.IFsStoreOrderService;
import com.fs.system.domain.SysConfig;
import com.fs.system.service.ISysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;

@Slf4j
@Component("orderTask")
public class OrderTask {
    @Autowired
    private IFsStoreOrderService orderService;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private IFsUserCourseOrderService userCourseOrderService;
    @Autowired
    private IFsPackageOrderService packageOrderService;

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;


    public void cancelOrder(){
        //查询超时订单
        SysConfig sysConfig= sysConfigService.selectConfigByConfigKey("his.store");
        StoreConfig config= JSONUtil.toBean(sysConfig.getConfigValue(),StoreConfig.class);
        Integer unPayTime = config.getUnPayTime(); //分钟
        if (unPayTime == null){
            return ;
        }
        //1.处方订单
        //查询超时未支付订单
        List<FsStoreOrder> orderList = orderService.selectOutTimeOrderList(unPayTime);
        //取消订单
        List<CompletableFuture<Void>> orderFutures = cancelOrdersAsync(orderList, order -> {
            orderService.cancelOrder(order.getOrderId());
        });

//        //2.课程订单
//        //查询超时未支付订单
//        List<FsUserCourseOrder> courseOrderlist = userCourseOrderService.selectOutTimeOrderList(unPayTime);
//        //取消订单
//        courseOrderlist.forEach(order->{
//            userCourseOrderService.cancelOrder(order.getOrderId());
//        });
        //3.服务包订单
        //查询超时未支付订单
        List<FsPackageOrder> packageOrderList = packageOrderService.selectOutTimeOrderList(unPayTime);
        //取消订单
        List<CompletableFuture<Void>> packageOrderFutures = cancelOrdersAsync(packageOrderList, order -> {
            FsPackageOrderCancelParam param = new FsPackageOrderCancelParam();
            param.setOrderId(order.getOrderId());
            packageOrderService.cancel(param);
        });

        // 等待所有任务完成
        waitForAllTasksToComplete(orderFutures);
        waitForAllTasksToComplete(packageOrderFutures);
    }

    /**
     * 异步取消订单
     * @param orders 订单列表
     * @param cancelAction 取消订单的逻辑
     * @param <T> 订单类型
     * @return CompletableFuture列表
     */
    private <T> List<CompletableFuture<Void>> cancelOrdersAsync(List<T> orders, Consumer<T> cancelAction) {
        List<CompletableFuture<Void>> futures = new ArrayList<>();
        for (T order : orders) {
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                try {
                    cancelAction.accept(order);
                } catch (Exception e) {
                    // 记录异常日志
                    System.err.println("Failed to cancel order: " + order + ", Error: " + e.getMessage());
                }
            }, threadPoolTaskExecutor);
            futures.add(future);
        }
        return futures;
    }

    /**
     * 等待所有任务完成
     * @param futures CompletableFuture列表
     */
    private void waitForAllTasksToComplete(List<CompletableFuture<Void>> futures) {
        CompletableFuture<Void> allFutures = CompletableFuture.allOf(
                futures.toArray(new CompletableFuture[0])
        );
        allFutures.join(); // 等待所有任务完成
    }
}
