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.stereotype.Service;
import shop.alien.entity.SecondVideoTask;
import shop.alien.mapper.system.SecondVideoTaskMapper;
import shop.alien.second.service.VideoModerationService;
import shop.alien.util.common.safe.video.VideoModerationUtil;

import java.util.Date;
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;

    /**
     * 提交视频审核任务
     *
     * @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(), "FAILED");
                    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;
        }
    }
}