package com.zanxiang.game.data.serve.task;

import com.zanxiang.game.data.serve.service.IOrderCostMonitorAlarmService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author ZhangXianyu
 * @version 1.0
 * @description: 表监控告警定时任务 (监控订单表、头条广告消耗表、腾讯广告消耗表)
 * @date 2024-03-20 15:25:44
 */
@Slf4j
@Component
public class OrderCostMonitorAlarmTask {

    @Resource
    private IOrderCostMonitorAlarmService orderCostMonitorAlarmService;

    @Value("${sys-config.task_is_run}")
    private boolean run;

    private ExecutorService taskScheduler = Executors.newSingleThreadExecutor();




    @Deprecated
    public void run() {
        log.info("订单与消耗监控告警定时任务开始.");
        Future<?> future =  taskScheduler.submit(() -> {
            //本地不运行
            if (!run) {
                return;
            }
            //0点0分到0点30分不执行
            LocalDateTime now = LocalDateTime.now();
            if (now.getHour() == 0 && now.getMinute() <= 30) {
                return;
            }
//        log.info("订单与消耗监控告警定时任务开始.");
            try {
                //监控订单表
                orderCostMonitorAlarmService.monitorDataStatus();
                //监控头条广告消耗表
                orderCostMonitorAlarmService.monitorHeadCostStatus();
                //监控腾讯广告消耗表
                orderCostMonitorAlarmService.monitorTencentCostStatus();
                log.info("订单与消耗监控告警定时任务结束.");
            } catch (Exception e) {
                log.error("定时任务订单与消耗监控告警出错", e);
            }
        });
        try {
            //两分钟执行不完就超时
            future.get(120, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("定时任务订单与消耗监控告警超时", e);
            future.cancel(true);
        }
    }


    /**
     * 任务每30分钟运行一次
     */
    @Scheduled(cron = "0 0/30 * * * ? ")
    public void runTask(){
        log.info("订单与消耗监控告警定时任务开始.");
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        Runnable task = ()->{
            try {
                //0点0分到0点30分不执行
                LocalDateTime now = LocalDateTime.now();
                if (now.getHour() == 0 && now.getMinute() <= 30) {
                    return;
                }
                //监控订单表
                orderCostMonitorAlarmService.monitorDataStatus();
                //监控头条广告消耗表
                orderCostMonitorAlarmService.monitorHeadCostStatus();
                //监控腾讯广告消耗表
                orderCostMonitorAlarmService.monitorTencentCostStatus();
                log.info("订单与消耗监控告警定时任务结束.");
            }catch (Exception e){
                log.error("定时任务订单与消耗监控告警超时", e);
            }
        };
        scheduler.submit(task);
        // 使用shutdown()优雅关闭
        scheduler.shutdown();
        try {
            // 等待所有任务完成，最多等待120秒
            if (!scheduler.awaitTermination(120, TimeUnit.SECONDS)) {
                log.info("线程池关闭超时，可能有任务未完成");
            }
        } catch (InterruptedException e) {
            // 当前线程被中断，通常应重新中断自己
            log.info("线程池关闭时当前线程被中断");
            Thread.currentThread().interrupt();

        }

        // 或使用shutdownNow()强制关闭
        List<Runnable> notStartedTasks = scheduler.shutdownNow();
        log.info("已取消 " + notStartedTasks.size() + " 个任务");
    }

}
