package com.wzj.soopin.content.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wzj.soopin.content.domain.base.BaseInfoProperties;
import com.wzj.soopin.content.domain.bo.VlogBO;
import com.wzj.soopin.content.domain.vo.IndexVlogVO;
import com.wzj.soopin.content.enums.YesOrNo;
import com.wzj.soopin.content.service.IVlogPullService;
import com.wzj.soopin.content.service.IVlogPushService;
import com.wzj.soopin.content.service.VlogService;
import com.wzj.soopin.content.utils.RedisOperator;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.R;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Slf4j
@Tag(name = "短视频相关业务功能的接口")
@RequestMapping("/cms/vlog")
@RestController
@AllArgsConstructor
public class VlogController extends BaseInfoProperties {
    private final VlogService vlogService;
    public final RedisOperator redis;
    private final IVlogPushService vlogPushService;
    private final IVlogPullService vlogPullService;

    @Operation(summary = "查询列表")
    @PostMapping("/page")
    public R<IPage<IndexVlogVO>> page(@RequestBody VlogBO bo, @RequestBody Page page) {
        Page<IndexVlogVO> pages = vlogService.getIndexVlogList(bo ,page);
        return R.ok(pages);
    }
    @PostMapping("/vodCallBack")
    public R<Void> vodCallBack(@RequestBody Map<String, Object> callbackData) {
        try {
            // 解析回调事件类型
            String eventType = (String) callbackData.get("EventType");
            log.info("收到腾讯云 VOD 回调, 事件类型: {}", eventType);
            log.info(callbackData.toString());

            if ("ProcedureStateChanged".equals(eventType)) {
                // 获取 ProcedureStateChangeEvent
                Object eventObject = callbackData.get("ProcedureStateChangeEvent");
                if (eventObject instanceof Map) {
                    @SuppressWarnings("unchecked")
                    Map<String, Object> procedureStateChangeEvent = (Map<String, Object>) eventObject;
                    String fileId = (String) procedureStateChangeEvent.get("FileId");
                    String fileUrl = (String) procedureStateChangeEvent.get("FileUrl"); // 原视频地址
                    String status = (String) procedureStateChangeEvent.get("Status"); // FINISH
                    // 只处理完成状态
                    if ("FINISH".equals(status)) {
                        // 获取 MediaProcessResultSet，可能包含任务流信息
                        List<Map<String, Object>> mediaProcessResultSet =
                                (List<Map<String, Object>>) procedureStateChangeEvent.get("MediaProcessResultSet");

                        if (mediaProcessResultSet != null) {
                            String coverUrl=null; // 首帧图
                            String transVdUrl=null; // 转码后的视频地址
                            for (Map<String, Object> processResult : mediaProcessResultSet) {
                                String type = (String) processResult.get("Type");
                                if ("CoverBySnapshot".equals(type)) {
                                    // 任务流：首帧截图
                                    Map<String, Object> coverBySnapshotTask =
                                            (Map<String, Object>) processResult.get("CoverBySnapshotTask");
                                    Map<String, Object> output = (Map<String, Object>) coverBySnapshotTask.get("Output");
                                    coverUrl = (String) output.get("CoverUrl"); // 正确获取 CoverUrl

                                }
                                if("Transcode".equals(type)){
                                    // 拿到output中的url
                                    Map<String, Object> TranscodeTask =
                                            (Map<String, Object>) processResult.get("TranscodeTask");
                                    Map<String, Object> output = (Map<String, Object>) TranscodeTask.get("Output");
                                    transVdUrl = (String) output.get("Url");
                                }
                            }
                            log.info("任务流 [截取首帧，视频转码] 完成, FileId: {}, 封面图 URL: {},视频地址: {}", fileId, coverUrl,transVdUrl);
                            // TODO: 更新数据库，存储首帧图,设置云端地址，删除minio视频文件
                            vlogService.updateVlogFirstImg(fileId,coverUrl,transVdUrl);

                        } else {
                            log.warn("MediaProcessResultSet 为空，回调数据: {}", callbackData);
                        }
                    }
                    log.info("任务流完成, FileId: {}, Status: {}", fileId, status);
                } else {
                    log.warn("ProcedureStateChangeEvent 为空或格式错误，回调数据: {}", callbackData);
                }
            }
            if("ReviewAudioVideoComplete".equals(eventType)){
                //处理审核结果
                Map<String, Object> reviewEvent = (Map<String, Object>) callbackData.get("ReviewAudioVideoCompleteEvent");
                if (reviewEvent != null) {
                    String status = (String) reviewEvent.get("Status"); // FINISH
                    if ("FINISH".equals(status)) {
                        Map<String, Object> input = (Map<String, Object>) reviewEvent.get("Input");
                        String fileId = (String) input.get("FileId"); // 查询的唯一标识
                        // 获取审核结果
                        Map<String, Object> output = (Map<String, Object>) reviewEvent.get("Output");
                        String suggestion = (String) output.get("Suggestion");
                        if ("block".equals(suggestion)) {
                            // 审核不通过，修改视频状态为2，写入reason，发送站内消息，告知审核结果
                            // label
                            //Porn：色情；
                            //Terror：暴力；
                            //Polity：不适宜的信息；
                            //Ad：广告；
                            //Illegal：违法；
                            //Abuse：谩骂；
                            //Moan：娇喘。
                            String label = (String) output.get("Label"); // 违规内容
                            String subLabel = (String) output.get("SubLabel"); // 违规子标签
                            log.info("视频文件 {} 审核驳回, 原因: {} - {}", fileId, label, subLabel);
                            // TODO: 更新数据库,发送站内信
                            vlogService.updateVlogStatus(fileId,2,label);
                        } else if ("pass".equals(suggestion)) {
                            // 审核通过，处理通过逻辑,修改视频状态为1，发送站内消息，告知审核结果
                            log.info("视频文件 {} 审核通过", fileId);
                            // TODO: 更新数据库，发送站内信
                            vlogService.updateVlogStatus(fileId,1,"通过");

                        } else if ("review".equals(suggestion)){
                            // 建议复审，修改状态为3，发送站内消息，告知审核结果
                            String label = (String) output.get("Label"); // 违规内容
                            String subLabel = (String) output.get("SubLabel"); // 违规子标签
                            log.info("视频文件 {} 建议复审, 原因: {} - {}", fileId, label, subLabel);
                            // TODO: 更新数据库，发送站内信
                            vlogService.updateVlogStatus(fileId,3,"等待复审");

                        }
                    }
                }
            }
            // 处理完成，返回成功，防止腾讯云重复发送回调
            return R.ok();
        } catch (Exception e) {
            log.error("处理腾讯云 VOD 回调异常: ", e);
            return R.fail("处理腾讯云 VOD 回调异常: " + e.getMessage());
        }
    }






    @Operation(summary = "修改视频状态")
    @PostMapping("/changeVlogStatus")
    public R<Void> changeVlogStatus(@RequestParam String userId,
                                            @RequestParam String vlogId,
                                            @RequestParam Integer status) {
        vlogService.changeVlogStatus(userId, vlogId,status);
        return R.ok();
    }

    @Operation(summary = "修改视频为私密")
    @PostMapping("/changeToPrivate")
    public R<Void> changeToPrivate(@RequestParam String userId,
                                           @RequestParam String vlogId) {
        vlogService.changeToPrivateOrPublic(userId,
                                            vlogId,
                                            YesOrNo.YES.type);
        return R.ok();
    }

    @Operation(summary = "修改视频为公开")
    @PostMapping("/changeToPublic")
    public R<Void> changeToPublic(@RequestParam String userId,
                                           @RequestParam String vlogId) {
        vlogService.changeToPrivateOrPublic(userId,
                vlogId,
                YesOrNo.NO.type);
        return R.ok();
    }

    @Operation(summary = "查询视频被点赞数量")
    @PostMapping("/totalLikedCounts")
    public R<Integer> totalLikedCounts(@RequestParam String vlogId) {
        return R.ok(vlogService.getVlogBeLikedCounts(vlogId));
    }

    @Operation(summary = "推送视频")
    @GetMapping("/push")
    public R pushMember(@RequestParam int  count,@RequestParam String tag) {
        return R.ok(vlogPushService.pushVlogToMq(count,tag));
    }

    @Operation(summary = "同步视频")
    @GetMapping("/sync")
    public R syncVlog() {
//        vlogPullService.pullFromTencentCloud();
        return R.ok();
    }


}
