package shop.alien.second.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyun.green20220302.models.VideoModerationResponse;
import com.aliyun.green20220302.models.VideoModerationResultResponse;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import shop.alien.entity.SecondVideoTask;
import shop.alien.mapper.system.SecondVideoTaskMapper;
import shop.alien.second.service.SecondGoodsService;
import shop.alien.second.service.VideoModerationService;
import shop.alien.util.common.safe.video.VideoModerationUtil;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 视频审核业务服务类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class VideoModerationServiceImpl extends ServiceImpl<SecondVideoTaskMapper, SecondVideoTask> implements VideoModerationService {

    /**
     * 视频审核工具类
     */
    private final VideoModerationUtil videoModerationUtil;

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

    /**
     * 二手商品服务（使用@Lazy避免循环依赖）
     */
    @Lazy
    @Autowired
    private SecondGoodsService secondGoodsService;

    /**
     * 提交视频审核任务
     *
     * @param videoUrl 视频URL
     * @return 任务ID
     */
    public String submitVideoModerationTask(String videoUrl) {
        try {
            // 生成dataId
            String dataId = "video_" + UUID.randomUUID().toString().replace("-", "");

            // 调用阿里云接口提交任务
            VideoModerationResponse response = videoModerationUtil.submitVideoModerationTask(videoUrl, dataId);

            if (response.getStatusCode() == 200 && response.getBody() != null &&
                    response.getBody().getCode() != null && response.getBody().getCode() == 200) {

                // 保存任务信息到数据库
                SecondVideoTask task = new SecondVideoTask();
                task.setDataId(dataId);
                task.setVideoUrl(videoUrl);
                task.setTaskId(response.getBody().getData().getTaskId());
                task.setStatus("SUBMITTED");
                task.setCreateTime(new Date());
                task.setUpdateTime(new Date());

                videoModerationTaskMapper.insert(task);

                log.info("视频审核任务提交成功，任务ID: {}", task.getTaskId());
                return task.getTaskId();
            } else {
                log.error("提交视频审核任务失败，响应: {}", JSON.toJSONString(response));
                throw new RuntimeException("提交视频审核任务失败: " + (response.getBody() != null ? response.getBody().getMessage() : "未知错误"));
            }
        } catch (Exception e) {
            log.error("提交视频审核任务异常", e);
            throw new RuntimeException("提交视频审核任务异常: " + e.getMessage());
        }
    }

    /**
     * 根据任务ID查询任务详情
     *
     * @param taskId 任务ID
     * @return 任务详情
     */
    public SecondVideoTask getTaskByTaskId(String taskId) {
        try {
            return videoModerationTaskMapper.selectByTaskId(taskId);
        } catch (Exception e) {
            log.error("查询视频审核任务详情异常，任务ID: {}", taskId, e);
            throw new RuntimeException("查询视频审核任务详情异常: " + e.getMessage());
        }
    }
    
    /**
     * 根据任务ID查询任务详情
     * 
     * @param taskId 任务ID
     * @return 任务详情
     */
    public SecondVideoTask getTaskById(String taskId) {
        try {
            return videoModerationTaskMapper.selectByTaskId(taskId);
        } catch (Exception e) {
            log.error("查询视频审核任务详情异常，任务ID: {}", taskId, e);
            throw new RuntimeException("查询视频审核任务详情异常: " + e.getMessage());
        }
    }

    /**
     * 查询视频审核结果
     *
     * @param taskId 任务ID
     * @return 审核结果
     */
    public SecondVideoTask queryVideoModerationResult(String taskId) {
        try {
            // 查询数据库中的任务
            SecondVideoTask task = videoModerationTaskMapper.selectByTaskId(taskId);
            if (task == null) {
                throw new RuntimeException("未找到任务ID为 " + taskId + " 的审核任务");
            }

            // 调用阿里云接口获取审核结果
            VideoModerationResultResponse response = videoModerationUtil.getVideoModerationResult(taskId);

            if (response.getStatusCode() == 200 && response.getBody() != null &&
                    response.getBody().getCode() != null && response.getBody().getCode() == 200) {

                // 更新数据库中的任务结果
                String status = "SUCCESS";
                String riskLevel = response.getBody().getData().getRiskLevel();
                String result = JSON.toJSONString(response.getBody().getData());

                videoModerationTaskMapper.updateTaskResult(taskId, status, riskLevel, result);

                // 更新任务对象并返回
                task.setStatus(status);
                task.setRiskLevel(riskLevel);
                task.setResult(result);
                task.setUpdateTime(new Date());

                log.info("获取视频审核结果成功，任务ID: {}", taskId);
                return task;
            } else {
                log.error("获取视频审核结果失败，响应: {}", JSON.toJSONString(response));
                throw new RuntimeException("获取视频审核结果失败: " + (response.getBody() != null ? response.getBody().getMessage() : "未知错误"));
            }
        } catch (Exception e) {
            log.error("获取视频审核结果异常，任务ID: {}", taskId, e);
            throw new RuntimeException("获取视频审核结果异常: " + e.getMessage());
        }
    }

    /**
     * 处理单个审核任务
     *
     * @param task 审核任务
     * @return 是否处理成功
     */
    public boolean processTask(SecondVideoTask task) {
        try {
            // 调用阿里云接口获取审核结果
            VideoModerationResultResponse response = videoModerationUtil.getVideoModerationResult(task.getTaskId());

            if (response.getStatusCode() == 200 && response.getBody() != null) {
                Integer code = response.getBody().getCode();
                if (code != null && code == 200) {
                    // 审核完成，更新任务结果
                    String status = "SUCCESS";
                    String riskLevel = response.getBody().getData().getRiskLevel();
                    String result = JSON.toJSONString(response.getBody().getData());

                    videoModerationTaskMapper.updateTaskResult(task.getTaskId(), status, riskLevel, result);

                    log.info("视频审核任务处理成功，任务ID: {}", task.getTaskId());
                    return true;
                } else if (code != null && code == 500) {
                    // 审核仍在进行中，更新状态
                    videoModerationTaskMapper.updateTaskStatus(task.getTaskId(), "PROCESSING");
                    log.info("视频审核任务仍在处理中，任务ID: {}", task.getTaskId());
                    return false;
                } else {
                    // 审核失败
                    videoModerationTaskMapper.updateTaskStatus(task.getTaskId(), "PROCESSING");
                    log.error("视频审核任务处理失败，任务ID: {}，错误信息: {}", task.getTaskId(), response.getBody().getMessage());
                    return false;
                }
            } else {
                // HTTP请求失败
                log.error("获取视频审核结果HTTP请求失败，任务ID: {}，状态码: {}", task.getTaskId(), response.getStatusCode());
                return false;
            }
        } catch (Exception e) {
            log.error("处理视频审核任务异常，任务ID: {}", task.getTaskId(), e);

            // 增加重试次数
            videoModerationTaskMapper.incrementRetryCount(task.getId());

            // 如果重试次数超过3次，标记为失败
            if (task.getRetryCount() >= 3) {
                videoModerationTaskMapper.updateTaskStatus(task.getTaskId(), "FAILED");
            }

            return false;
        }
    }

    /**
     * 处理所有待处理的视频审核任务
     * @return 处理结果
     */
    @Override
    public String processAllPendingVideoTasks() {
        try {
            log.info("开始执行视频审核结果处理");

            // 查询待处理的审核任务（状态为SUBMITTED或PROCESSING）
            List<SecondVideoTask> pendingTasks = videoModerationTaskMapper.selectPendingTasks();

            if (pendingTasks.isEmpty()) {
                log.info("没有待处理的视频审核任务");
                return "没有待处理的视频审核任务";
            }

            log.info("共找到 {} 个待处理的视频审核任务", pendingTasks.size());

            int successCount = 0;
            int processingCount = 0;
            int failCount = 0;

            for (SecondVideoTask task : pendingTasks) {
                try {
                    // 1. 拉取视频审核结果
                    boolean success = processTask(task);
                    if (success) {
                        successCount++;
                        // 2. 视频审核完成后，更新商品业务状态
                        log.info("TaskId:开始处理商品状态 {}", task.getTaskId());
                        SecondVideoTask updatedTask = videoModerationTaskMapper.selectByTaskId(task.getTaskId());
                        if (updatedTask != null) {
                            secondGoodsService.processVideoModerationResult(updatedTask);
                        }
                        log.info("TaskId:商品状态处理完成 {}", task.getTaskId());
                    } else {
                        // 检查任务状态判断是处理中还是失败
                        SecondVideoTask updatedTask = videoModerationTaskMapper.selectByTaskId(task.getTaskId());
                        if (updatedTask != null && "PROCESSING".equals(updatedTask.getStatus())) {
                            processingCount++;
                        } else {
                            failCount++;
                        }
                    }
                } catch (Exception e) {
                    log.error("处理视频审核任务时发生异常，任务ID: {}", task.getTaskId(), e);
                    failCount++;
                }
            }

            String result = String.format("视频审核结果处理完成，成功:%d，处理中:%d，失败:%d", successCount, processingCount, failCount);
            log.info(result);
            return result;
        } catch (Exception e) {
            log.error("执行视频审核结果处理任务时发生异常", e);
            return "执行异常: " + e.getMessage();
        }
    }
}