package shop.alien.job.jobhandler;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import shop.alien.entity.SecondVideoTask;
import shop.alien.job.feign.SecondGoodsFeign;
import shop.alien.mapper.system.SecondVideoTaskMapper;

import java.util.List;

/**
 * 视频审核任务XXL-JOB处理器
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class VideoModerationJobHandler {

    /**
     * 视频审核任务Mapper
     */
    private final SecondVideoTaskMapper videoModerationTaskMapper;

    /**
     * 二级商品服务Feign客户端
     */
    private final SecondGoodsFeign secondGoodsFeign;
    
    /**
     * 视频审核结果拉取任务
     * 每30秒执行一次
     */
    @XxlJob("videoModerationResultJobHandler")
    public ReturnT<String> videoModerationResultJobHandler(String param) {
        try {
            log.info("开始执行视频审核结果拉取任务");
            
            // 查询待处理的审核任务（状态为SUBMITTED或PROCESSING）
            List<SecondVideoTask> pendingTasks = videoModerationTaskMapper.selectPendingTasks();
            
            if (pendingTasks.isEmpty()) {
                log.info("没有待处理的视频审核任务");
                return ReturnT.SUCCESS;
            }
            
            log.info("共找到 {} 个待处理的视频审核任务", pendingTasks.size());
            
            // 处理每个任务
            int successCount = 0;
            for (SecondVideoTask task : pendingTasks) {
                try {
                    boolean success = secondGoodsFeign.processTask(task.getTaskId());
                    if (success) {
                        successCount++;
                        // 处理视频审核结果，更新商品状态
                        log.info("处理第 {} 个task", successCount);
                        log.info("TaskId:开始 {} ", task.getTaskId());
                        secondGoodsFeign.processVideoResult(task.getTaskId());
                        log.info("TaskId:结束 {} ", task.getTaskId());
                    }
                } catch (Exception e) {
                    log.error("处理视频审核任务时发生异常，任务ID: {}", task.getTaskId(), e);
                }
            }
            
            log.info("视频审核结果拉取任务执行完成，成功处理 {} 个任务", successCount);
            return ReturnT.SUCCESS;
        } catch (Exception e) {
            log.error("执行视频审核结果拉取任务时发生异常", e);
            return ReturnT.FAIL;
        }
    }
}