package com.wzj.soopin.content.service.impl;

import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.vod.v20180717.VodClient;
import com.tencentcloudapi.vod.v20180717.models.DescribeTaskDetailRequest;
import com.tencentcloudapi.vod.v20180717.models.DescribeTaskDetailResponse;
import com.tencentcloudapi.vod.v20180717.models.PullUploadRequest;
import com.tencentcloudapi.vod.v20180717.models.PullUploadResponse;
import com.tencentcloudapi.vod.v20180717.models.SearchMediaRequest;
import com.tencentcloudapi.vod.v20180717.models.SearchMediaResponse;
import com.wzj.soopin.content.domain.vo.CommentVO;
import com.wzj.soopin.content.service.VlogUploadService;
import com.wzj.soopin.content.utils.TencentCloudUtil;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.redis.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class VlogUploadServiceImpl implements VlogUploadService {

    @Autowired
    private TencentCloudUtil tencentCloudUtil;

    @Autowired
    private com.wzj.soopin.content.mapper.VlogMapper vlogMapper;
    @Autowired
    private com.wzj.soopin.content.service.CommentService commentService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private com.wzj.soopin.content.mapper.VlogMapperCustom vlogMapperCustom;

//    @Override
//    public PullUploadResponse pullUpload(PullUploadRequest req) throws Exception {
//        // 获取VOD客户端实例
//        VodClient client = tencentCloudUtil.getVodClient();
//        // 返回的resp是一个PullUploadResponse的实例，与请求对象对应
//        return client.PullUpload(req);
//    }




    // 视频审核
    @Override
    public void auditVlog(String vlogId, Integer status, String reason) {
        try {
            // 参数验证
            if (vlogId == null || vlogId.trim().isEmpty()) {
                throw new IllegalArgumentException("视频ID不能为空");
            }
            if (status == null || (status != 1 && status != 2)) {
                throw new IllegalArgumentException("审核状态无效，只能是1(通过)或2(不通过)");
            }
            // 只有当状态为不通过(2)时才需要原因说明
            if (status == 2 && (reason == null || reason.trim().isEmpty())) {
                throw new IllegalArgumentException("审核不通过时，必须提供原因说明");
            }

            // 获取VOD客户端实例
            VodClient client = tencentCloudUtil.getVodClient();

            // 创建审核请求
            com.tencentcloudapi.vod.v20180717.models.ReviewAudioVideoRequest req = new com.tencentcloudapi.vod.v20180717.models.ReviewAudioVideoRequest();
            req.setFileId(vlogId);

            // 设置审核内容，包括视频和封面
            req.setReviewContents(new String[]{"Media", "Cover"});

            // 设置审核模板ID，10为预置模板
            req.setDefinition(10L);

            // 设置任务优先级
            req.setTasksPriority(0L);

            // 设置来源上下文，用于透传用户请求信息
            req.setSessionContext(String.format("status=%d&reason=%s", status, reason != null ? reason : ""));

            // 调用审核API
            com.tencentcloudapi.vod.v20180717.models.ReviewAudioVideoResponse resp = client.ReviewAudioVideo(req);

            // 记录审核结果
            log.info("视频审核任务已提交 - vlogId: {}, status: {}, reason: {}, taskId: {}",
                    vlogId, status, reason, resp.getTaskId());

            // TODO: 暂时注释掉数据库操作，等待数据库表创建完成后再启用
            /*
            // 更新本地数据库状态
            Map<String, Object> updateMap = new HashMap<>();
            updateMap.put("vlogId", vlogId);
            updateMap.put("status", status);
            updateMap.put("reason", reason);
            updateMap.put("auditTime", new Date());
            vlogMapper.updateVlogStatus(updateMap);

            // 记录审核日志
            log.info("视频状态已更新 - vlogId: {}, status: {}, reason: {}", vlogId, status, reason);
            */

        } catch (TencentCloudSDKException e) {
            log.error("视频审核失败 - vlogId: {}, error: {}", vlogId, e.getMessage(), e);
            throw new RuntimeException("视频审核失败: " + e.getMessage());
        } catch (Exception e) {
            log.error("更新视频状态失败 - vlogId: {}, error: {}", vlogId, e.getMessage(), e);
            throw new RuntimeException("更新视频状态失败: " + e.getMessage());
        }
    }

    /**
     * 禁播/解禁媒体
     * @param fileIds 媒体文件ID列表
     * @param operation 操作类型：forbid-禁播，recover-解禁
     */
    @Override
    public void forbidMediaDistribution(List<String> fileIds, String operation) {
        try {
            // 参数验证
            if (fileIds == null || fileIds.isEmpty()) {
                throw new IllegalArgumentException("媒体文件ID列表不能为空");
            }
            if (fileIds.size() > 20) {
                throw new IllegalArgumentException("每次最多可提交20个媒体文件");
            }
            if (!"forbid".equals(operation) && !"recover".equals(operation)) {
                throw new IllegalArgumentException("操作类型无效，只能是forbid(禁播)或recover(解禁)");
            }

            // 获取VOD客户端实例
            VodClient client = tencentCloudUtil.getVodClient();

            // 创建禁播/解禁请求
            com.tencentcloudapi.vod.v20180717.models.ForbidMediaDistributionRequest req = new com.tencentcloudapi.vod.v20180717.models.ForbidMediaDistributionRequest();
            req.setFileIds(fileIds.toArray(new String[0]));
            req.setOperation(operation);

            // 调用禁播/解禁API
            com.tencentcloudapi.vod.v20180717.models.ForbidMediaDistributionResponse resp = client.ForbidMediaDistribution(req);

            // 记录操作结果
            log.info("媒体{}操作已提交 - fileIds: {}, notExistFileIds: {}",
                    operation.equals("forbid") ? "禁播" : "解禁",
                    fileIds,
                    resp.getNotExistFileIdSet());

            // 如果有不存在的文件ID，记录警告日志
            if (resp.getNotExistFileIdSet() != null && resp.getNotExistFileIdSet().length > 0) {
                log.warn("部分文件不存在 - fileIds: {}", Arrays.toString(resp.getNotExistFileIdSet()));
            }

        } catch (TencentCloudSDKException e) {
            log.error("媒体{}操作失败 - fileIds: {}, error: {}",
                    operation.equals("forbid") ? "禁播" : "解禁",
                    fileIds,
                    e.getMessage(),
                    e);
            throw new RuntimeException("媒体" + (operation.equals("forbid") ? "禁播" : "解禁") + "失败: " + e.getMessage());
        }
    }

    // 视频删除
    @Override
    public void deleteVlog(String vlogId) {
        // 逻辑删除或物理删除
        // vlogMapper.deleteById(vlogId);
        log.info("删除视频 vlogId={}", vlogId);
    }

    // 视频详情
    @Override
    public Object getVlogDetail(String vlogId) {
        try {
            // 1. 优先从 MySQL 获取视频基础信息
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("vlogId", vlogId);
            List<com.wzj.soopin.content.domain.vo.IndexVlogVO> vlogList = vlogMapperCustom.getVlogDetailById(paramMap);
            com.wzj.soopin.content.domain.vo.IndexVlogVO vlog = vlogList != null && !vlogList.isEmpty() ? vlogList.get(0) : null;

            com.tencentcloudapi.vod.v20180717.models.MediaInfo mediaInfo = null;
            if (vlog == null) {
                // 若本地无，尝试从云点播获取
                com.tencentcloudapi.vod.v20180717.models.DescribeMediaInfosRequest req = new com.tencentcloudapi.vod.v20180717.models.DescribeMediaInfosRequest();
                String fileId = vlogId;  // 这里假设传入的 vlogId 就是 fileId
                req.setFileIds(new String[]{fileId});
                VodClient client = tencentCloudUtil.getVodClient();
                com.tencentcloudapi.vod.v20180717.models.DescribeMediaInfosResponse resp = client.DescribeMediaInfos(req);
                if (resp.getMediaInfoSet() != null && resp.getMediaInfoSet().length > 0) {
                    mediaInfo = resp.getMediaInfoSet()[0];
                }
            }

            // 2. 点赞数量：优先 Redis，无则 MySQL
            int likeCounts=redisCache.zSetScore(com.wzj.soopin.content.domain.base.BaseInfoProperties.REDIS_VLOG_BE_LIKED_COUNTS ,  vlogId).intValue();

            // 3. 评论数量：优先 Redis，无则 MySQL
            int commentCounts=redisCache.zSetScore(com.wzj.soopin.content.domain.base.BaseInfoProperties.REDIS_VLOG_COMMENT_COUNTS ,  vlogId).intValue();


            // 4. 评论内容：只查 MySQL
            List<com.wzj.soopin.content.domain.vo.CommentVO> commentList = new ArrayList<>();
            try {
                PageQuery pageQuery = new PageQuery(1, 10);
                TableDataInfo<CommentVO> tableDataInfo = commentService.queryVlogComments(vlogId, null, pageQuery);
                if (tableDataInfo != null && tableDataInfo.getRows() != null) {
                    commentList = tableDataInfo.getRows();
                }
            } catch (Exception e) {
                log.warn("获取评论列表失败: {}", e.getMessage());
            }

            // 5. 统一返回
            java.util.Map<String, Object> detail = new java.util.HashMap<>();
            detail.put("videoInfo", vlog != null ? vlog : mediaInfo);
            detail.put("likeCounts", likeCounts);
            detail.put("commentCounts", commentCounts);
            detail.put("commentList", commentList);
            return detail;
        } catch (Exception e) {
            log.error("获取视频详情失败", e);
            return null;
        }
    }

}
