package com.rj.scheduler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rj.config.AliyunConfig;
import com.rj.entity.DetectVideoTemplate;
import com.rj.mapper.DetectVideoTemplateMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 检测视频模板任务状态检查定时器
 * 每6分钟检查一次PENDING或RUNNING状态的任务，调用阿里云API查询任务状态并更新数据库
 * 
 * @author rj
 * @date 2025-01-09
 */
@Slf4j
@Component
public class DetectVideoTemplateStatusScheduler {

    @Autowired
    private DetectVideoTemplateMapper detectVideoTemplateMapper;

    @Autowired
    private AliyunConfig aliyunConfig;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 每6分钟执行一次任务状态检查
     */
 //   @Scheduled(fixedRate = 6 * 60 * 1000) // 6分钟 = 6 * 60 * 1000毫秒
    public void checkDetectVideoTemplateStatus() {
        try {
            log.info("开始执行检测视频模板任务状态检查...");
            
            // 查询所有PENDING或RUNNING状态的任务
            List<DetectVideoTemplate> pendingTasks = getPendingTasks();
            
            if (pendingTasks.isEmpty()) {
                log.info("没有找到PENDING或RUNNING状态的检测视频模板任务");
                return;
            }
            
            log.info("找到{}个PENDING或RUNNING状态的检测视频模板任务，开始检查状态", pendingTasks.size());
            
            // 遍历每个任务，检查状态
            for (DetectVideoTemplate task : pendingTasks) {
                try {
                    checkAndUpdateTaskStatus(task);
                } catch (Exception e) {
                    log.error("检查检测视频模板任务状态失败，任务ID: {}, 错误: {}", task.getTaskId(), e.getMessage(), e);
                }
            }
            
            log.info("检测视频模板任务状态检查完成");
            
        } catch (Exception e) {
            log.error("检测视频模板任务状态检查执行失败", e);
        }
    }

    /**
     * 查询所有PENDING或RUNNING状态的任务
     */
    private List<DetectVideoTemplate> getPendingTasks() {
        QueryWrapper<DetectVideoTemplate> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("task_status", "PENDING", "RUNNING");
        queryWrapper.isNotNull("task_id");
        queryWrapper.ne("task_id", "");
        
        return detectVideoTemplateMapper.selectList(queryWrapper);
    }

    /**
     * 检查并更新单个任务状态
     */
    private void checkAndUpdateTaskStatus(DetectVideoTemplate task) {
        try {
            log.info("检查检测视频模板任务状态，任务ID: {}", task.getTaskId());
            
            if (task == null || task.getTaskId() == null || task.getTaskId().isEmpty()) {
                log.warn("任务ID为空，跳过检查");
                return;
            }
            
            // 调用阿里云API检查任务状态
            String apiUrl = "https://dashscope.aliyuncs.com/api/v1/tasks/" + task.getTaskId();
            
            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", "Bearer " + aliyunConfig.getApiKey());
            headers.set("Content-Type", "application/json");
            
            HttpEntity<String> entity = new HttpEntity<>(headers);
            
            ResponseEntity<String> response = restTemplate.exchange(
                apiUrl, 
                HttpMethod.GET, 
                entity, 
                String.class
            );
            
            if (response.getStatusCode().is2xxSuccessful()) {
                String responseBody = response.getBody();
                log.info("检测视频模板API响应: {}", responseBody);
                
                // 解析响应并更新数据库
                updateTaskFromResponse(task, responseBody);
            } else {
                log.error("检测视频模板API调用失败，状态码: {}, 任务ID: {}", response.getStatusCode(), task.getTaskId());
            }
            
        } catch (Exception e) {
            log.error("检查检测视频模板任务状态异常，任务ID: {}, 错误: {}", task.getTaskId(), e.getMessage(), e);
        }
    }

    /**
     * 根据API响应更新任务状态
     */
    private void updateTaskFromResponse(DetectVideoTemplate task, String responseBody) {
        try {
            JSONObject responseJson = JSON.parseObject(responseBody);
            
            if (responseJson.containsKey("output")) {
                JSONObject output = responseJson.getJSONObject("output");
                
                // 更新任务状态
                if (output.containsKey("task_status")) {
                    String taskStatus = output.getString("task_status");
                    task.setTaskStatus(taskStatus);
                    log.info("更新任务状态: {} -> {}", task.getTaskId(), taskStatus);
                    
                    // 根据任务状态判断是否成功
                    boolean isSuccess = "SUCCEEDED".equalsIgnoreCase(taskStatus) || "COMPLETED".equalsIgnoreCase(taskStatus);
                    task.setSuccess(isSuccess);
                    
                    // 如果任务完成，更新响应时间
                    if (isSuccess || "FAILED".equalsIgnoreCase(taskStatus) || "CANCELLED".equalsIgnoreCase(taskStatus)) {
                        task.setResponseTime(LocalDateTime.now());
                    }
                }
                
                // 更新模板ID
                if (output.containsKey("template_id")) {
                    String templateId = output.getString("template_id");
                    task.setTemplateId(templateId);
                    log.info("更新模板ID: {} -> {}", task.getTaskId(), templateId);
                }
                
                // 更新请求ID（如果API返回了新的request_id）
                if (responseJson.containsKey("request_id")) {
                    String requestId = responseJson.getString("request_id");
                    task.setRequestId(requestId);
                    log.info("更新请求ID: {} -> {}", task.getTaskId(), requestId);
                }
                
                // 更新响应数据
                task.setResponseData(responseBody);
                
                // 保存到数据库
                detectVideoTemplateMapper.updateById(task);
                
                log.info("检测视频模板任务状态更新成功，任务ID: {}, 状态: {}, 成功: {}", 
                    task.getTaskId(), task.getTaskStatus(), task.getSuccess());
                
            } else {
                log.warn("API响应中没有output字段，任务ID: {}", task.getTaskId());
            }
            
        } catch (Exception e) {
            log.error("解析API响应失败，任务ID: {}, 错误: {}", task.getTaskId(), e.getMessage(), e);
        }
    }
}
