package com.yupi.project.service.impl;

import com.yupi.project.model.entity.RobotTask;
import com.yupi.project.service.RobotTaskService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
@RequiredArgsConstructor
public class TaskTimeoutHandler {

    private final RobotTaskService robotTaskService;

    @Value("${mqtt.task.timeoutSeconds:300}") // 默认5分钟超时
    private int taskTimeoutSeconds;

    // 默认每分钟检查一次，可以根据实际需求调整
    // cron = "秒 分 时 日 月 周"
    // 例如 "0 * * * * ?" 每分钟的第0秒执行
    // fixedRate = 60000 (毫秒) 每隔60秒执行一次，从上一次任务开始时计时
    // fixedDelay = 60000 (毫秒) 每隔60秒执行一次，从上一次任务完成时计时
    @Scheduled(fixedRateString = "${mqtt.task.timeoutCheckRateMs:60000}") // 默认每60秒执行一次
    public void checkAndHandleTimedOutTasks() {
        log.info("Scheduled task: Checking for timed-out robot tasks (timeout: {}s).", taskTimeoutSeconds);
        try {
            List<RobotTask> timedOutTasks = robotTaskService.findAndMarkTimedOutTasks(taskTimeoutSeconds);
            if (timedOutTasks != null && !timedOutTasks.isEmpty()) {
                log.warn("Marked {} tasks as TIMED_OUT: {}", timedOutTasks.size(), timedOutTasks.stream().map(RobotTask::getId).collect(Collectors.toList()));
                // 可选：在这里添加进一步处理逻辑，例如通知、更新其他关联实体的状态等
                // 这部分逻辑将在第三阶段 ChargingSession 模块实现后补充。
                // for (RobotTask task : timedOutTasks) {
                //     if (task.getRelatedSessionId() != null) {
                //         // chargingSessionService.markSessionAsTaskTimedOut(task.getRelatedSessionId());
                //     }
                // }
            } else {
                log.info("No tasks found to be timed out during this check.");
            }
        } catch (Exception e) {
            log.error("Error during scheduled task execution of checkAndHandleTimedOutTasks: ", e);
        }
    }
} 