package com.test.test.task;

import com.test.test.domain.PerformanceTest;
import com.test.test.mapper.PerformanceTestMapper;
import com.test.test.service.IPerformanceTestCaseReportService;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.stream.Collectors;

@Component
@Slf4j
public class DynamicTaskManager {


    @Value("${test.jmeterHomePath:/opt/apache-jmeter}")
    private String jmeterHomePath;

    @Resource
    private PerformanceTestMapper performanceTestMapper;
    
    @Resource
    private TaskScheduler taskScheduler;

    @Resource
    private IPerformanceTestCaseReportService performanceTestCaseReportService;
    
    private final Map<Long, ScheduledFuture<?>> scheduledTasks = new ConcurrentHashMap<>();
    private final Map<Long, PerformanceTest> taskCache = new ConcurrentHashMap<>();
    
    @PostConstruct
    public void init() {
        loadTasks(); // 初始加载
//        taskScheduler.scheduleWithFixedDelay(this::refreshTasks, 60000); // 每1分钟刷新
    }

    public  void updateTask(PerformanceTest task) {
        log.info("update task {}", task.getId());
        Long taskId = task.getId();
        // 先取消现有任务
        if (scheduledTasks.containsKey(taskId)) {
            scheduledTasks.get(taskId).cancel(true);
            scheduledTasks.remove(taskId);
            taskCache.remove(taskId);
        }

        // 如果任务状态是启用(1)且没有被删除，则重新调度
        if (task.getCrontabStatus() == 1 && "0".equals(task.getDelFlag())) {
            log.info("启动任务:{}", task.getId());
            scheduleTask(task);
        }
    }

    /**
     * 添加新任务到定时调度
     * @param task 性能测试任务
     */
    public void addNewTask(PerformanceTest task) {
        // 只有当任务状态是启用(1)且没有被删除时才创建定时任务
        if (task.getCrontabStatus() == 1 && "0".equals(task.getDelFlag())) {
            log.info("加入定时任务:{}", task.getId());
            scheduleTask(task);
        }
    }

    /**
     * 移除定时任务
     * @param taskId 任务ID
     */
    public void removeTask(Long taskId) {
        if (scheduledTasks.containsKey(taskId)) {
            scheduledTasks.get(taskId).cancel(true);
            scheduledTasks.remove(taskId);
            taskCache.remove(taskId);
            log.info("已移除定时任务: {}", taskId);
        }
    }
    /**
     * 批量移除定时任务
     * @param taskIds 任务ID数组
     */
    public void removeTasks(Long[] taskIds) {
        for (Long taskId : taskIds) {
            removeTask(taskId);
        }
    }

    private void loadTasks() {
        PerformanceTest performanceTest =new PerformanceTest();
        performanceTest.setCrontabStatus(1);
        performanceTest.setDelFlag("0");
        List<PerformanceTest> tasks = performanceTestMapper.selectPerformanceTestList(performanceTest);
        tasks.forEach(this::scheduleTask);
    }
    
    private void scheduleTask(PerformanceTest task) {
        try {
            CronTrigger trigger = new CronTrigger(task.getCrontab());
            ScheduledFuture<?> future = taskScheduler.schedule(
                () -> executeTask(task), trigger
            );
            scheduledTasks.put(task.getId(), future);
            taskCache.put(task.getId(), task);
        } catch (IllegalArgumentException e) {
            // 处理无效cron表达式
            log.error("无效的cron表达式: " + task.getCrontab());
        }
    }
    
    private void executeTask(PerformanceTest task) {
        // 执行业务逻辑
        log.info("执行任务: " + task.getId());
        try{
            performanceTestCaseReportService.executePerformanceTestAndReport(task.getId(),jmeterHomePath,1);
        } catch (Exception e) {
            log.error("执行失败!",e);
        }
    }
    
    private void refreshTasks() {
        PerformanceTest performanceTest =new PerformanceTest();
        performanceTest.setCrontabStatus(1);
        performanceTest.setDelFlag("0");
        List<PerformanceTest> currentTasks = performanceTestMapper.selectPerformanceTestList(performanceTest);
        Set<Long> currentIds = currentTasks.stream()
            .map(PerformanceTest::getId)
            .collect(Collectors.toSet());
        
        // 处理新增或更新的任务
        currentTasks.forEach(task -> {
            Long taskId = task.getId();
            if (!scheduledTasks.containsKey(taskId)) {
                scheduleTask(task); // 新增任务
            } else {
                PerformanceTest cached = taskCache.get(taskId);
                if (!task.getCrontab().equals(cached.getCrontab())) {
                    // 取消旧任务并重新调度
                    scheduledTasks.get(taskId).cancel(true);
                    scheduleTask(task);
                }
            }
        });

        // 移除已禁用或删除的任务
        new HashSet<>(scheduledTasks.keySet()).forEach(existingId -> {
            if (!currentIds.contains(existingId)) {
                scheduledTasks.get(existingId).cancel(true);
                scheduledTasks.remove(existingId);
                taskCache.remove(existingId);
            }
        });
    }
}