package com.fs.app.task;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import com.fs.common.annotation.Log;
import com.fs.course.domain.MarketPush;
import com.fs.course.service.IMarketPushService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
@Slf4j
@Component
public class MarketPushScheduler {

    /*@Autowired
    private IMarketPushService marketPushService;

    private final Map<Long, ScheduledFuture<?>> scheduledTasks = new ConcurrentHashMap<>();
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(10);

    *//**
     * 初始化所有启用的推送任务
     *//*
    *//*@PostConstruct
    public void init() {
        reloadPushTasks();
    }*//*

    *//**
     * 重新加载所有启用的推送任务
     *//*
    public void reloadPushTasks() {
        // 取消所有已存在的任务
        cancelAllTasks();

        // 重新从数据库获取所有启用的推送任务
        List<MarketPush> enabledPushes = marketPushService.getEnabledMarketPushes();
        for (MarketPush push : enabledPushes) {
            schedulePushTask(push);
        }
    }

    *//**
     * 为单个推送任务创建定时任务
     *//*
    public void schedulePushTask(MarketPush push) {
        long intervalMillis = push.getPushTime();  // 从数据库获取推送周期（毫秒）

        Runnable task = () -> {
            // 这里执行推送逻辑
            try {
                System.out.println("推送任务 [" + push.getTitle() + "] 仍在运行...");
                if (scheduler.isShutdown() || scheduler.isTerminated()) {
                    System.out.println("线程池已关闭，重新初始化...");
                    reloadPushTasks(); // 重新加载任务
                }
                System.out.println("推送任务执行：" + push.getTitle() + "，当前时间：" + new Date());
                marketPushService.sendPushNotification(push);
            } catch (Exception e) {
                System.err.println("推送任务 [" + push.getTitle() + "] 执行异常：" + e.getMessage());
                e.printStackTrace();
            }

        };
        // 以固定频率执行任务
        ScheduledFuture<?> future = scheduler.scheduleAtFixedRate(task, intervalMillis, intervalMillis, TimeUnit.MILLISECONDS);
        scheduledTasks.put(push.getId(), future);
    }
    *//**
     * 取消所有推送任务
     *//*
    public void cancelAllTasks() {
        for (ScheduledFuture<?> future : scheduledTasks.values()) {
            future.cancel(true);
        }
        scheduledTasks.clear();
    }
*/
}
