import com.yupi.project.model.entity.RobotTask;
import com.yupi.project.service.ChargingSessionService;
import com.yupi.project.service.RobotTaskService;
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.util.List;

@Component
@Slf4j
public class TaskTimeoutHandler {

    @Resource
    private RobotTaskService robotTaskService;

    @Resource
    private ChargingSessionService chargingSessionService;

    @Value("${mqtt.task.timeoutSeconds:300}")
    private int taskTimeoutSeconds;

    @Scheduled(fixedRateString = "${mqtt.task.timeoutCheckRateMs:60000}")
    public void checkForTimedOutTasks() {
        log.debug("开始检查超时的机器人任务 (超时阈值: {}s)", taskTimeoutSeconds);
        List<RobotTask> timedOutTasks = robotTaskService.findAndMarkTimedOutTasks(taskTimeoutSeconds);

        if (timedOutTasks.isEmpty()) {
            log.debug("没有发现超时的机器人任务。");
            return;
        }

        log.warn("发现 {} 个超时的机器人任务。", timedOutTasks.size());
        for (RobotTask task : timedOutTasks) {
            log.warn("任务ID: {} (RobotUID: {}, Command: {}, Status: {}, SentTime: {}) 已超时。",
                    task.getId(), task.getRobotId(), task.getCommandType(), task.getStatus(), task.getSentTime());
            
            if (task.getRelatedSessionId() != null) {
                log.info("任务 {} 超时与充电会话 {} 相关联，将通知会话服务处理。", task.getId(), task.getRelatedSessionId());
                try {
                    chargingSessionService.handleSessionTaskTimeout(task.getId());
                } catch (Exception e) {
                    log.error("调用 chargingSessionService.handleSessionTaskTimeout 失败 for task ID {}: ", task.getId(), e);
                }
            } else {
                log.warn("任务 {} 超时，但未关联任何充电会话。", task.getId());
            }
        }
    }
} 