package com.qqchen.deploy.backend.schedule.service;

import com.qqchen.deploy.backend.schedule.dto.JobStatusDTO;
import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 任务进度报告工具
 * 供长时间执行的任务手动报告进度
 * 
 * @author qichen
 */
@Slf4j
@Component
public class JobProgressReporter {

    @Resource
    private JobStatusRedisService jobStatusRedisService;

    // 线程本地变量，存储当前任务信息
    private static final ThreadLocal<JobInfo> CURRENT_JOB = new ThreadLocal<>();

    /**
     * 设置当前任务（由AOP调用）
     */
    public void setCurrentJob(Long jobId, String jobName, LocalDateTime startTime,
                              String beanName, String methodName, String methodParams) {
        CURRENT_JOB.set(new JobInfo(jobId, jobName, startTime, beanName, methodName, methodParams));
    }

    /**
     * 清除当前任务（由AOP调用）
     */
    public void clearCurrentJob() {
        CURRENT_JOB.remove();
    }

    /**
     * 更新进度（业务代码调用）
     */
    public void updateProgress(Integer progress, String message) {
        JobInfo jobInfo = CURRENT_JOB.get();
        if (jobInfo == null) {
            log.warn("当前线程没有任务信息，无法更新进度");
            return;
        }

        JobStatusDTO statusDTO = JobStatusDTO.builder()
                .jobId(jobInfo.getJobId())
                .jobName(jobInfo.getJobName())
                .status("RUNNING")
                .progress(progress)
                .currentStep(message)
                .message(message)
                .startTime(jobInfo.getStartTime())
                .build();

        jobStatusRedisService.saveJobStatus(jobInfo.getJobId(), statusDTO);
        log.debug("任务进度更新: jobId={}, progress={}, message={}",
                jobInfo.getJobId(), progress, message);
    }

    /**
     * 任务信息
     */
    @Data
    @AllArgsConstructor
    private static class JobInfo {
        private Long jobId;
        private String jobName;
        private LocalDateTime startTime;
        private String beanName;
        private String methodName;
        private String methodParams;
    }
}

