package com.wzj.soopin.content.controller.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tencentcloudapi.vod.v20180717.models.*;
import com.wzj.soopin.content.domain.base.BaseInfoProperties;
import com.wzj.soopin.content.domain.bo.VlogBO;

import com.wzj.soopin.content.service.VlogService;
import com.wzj.soopin.content.service.VlogUploadService;
import com.wzj.soopin.content.utils.RedisOperator;
import org.dromara.common.redis.utils.RedisUtils;
import com.wzj.soopin.content.utils.TencentCloudUtil;
import com.wzj.soopin.member.service.IFansService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

@Slf4j
@Api(tags = "管理端-视频")
@RequestMapping("/cms/video")
@RestController
public class VlogUploadController extends BaseInfoProperties {

    @Autowired
    private VlogUploadService vlogUploadService;

    @Autowired
    private VlogService vlogService;

    @Autowired
    private TencentCloudUtil tencentCloudUtil;

    @Autowired
    private RedisOperator redis;

    @Autowired
    private IFansService fansService;

    /**
     * 视频审核接口
     */
    @PostMapping("/audit")
    public R<Void> auditVlog(@RequestParam String vlogId,
                             @RequestParam Integer status,
                             @RequestParam(required = false) String reason) {
        try {
            vlogUploadService.auditVlog(vlogId, status, reason);
            return R.ok();
        } catch (Exception e) {
            log.error("视频审核失败", e);
            return R.fail("视频审核失败: " + e.getMessage());
        }
    }

    /**
     * 视频删除接口
     */
    @PostMapping("/delete")
    public R<Void> deleteVlog(@RequestParam String vlogId) {
        try {
            vlogUploadService.deleteVlog(vlogId);
            return R.ok();
        } catch (Exception e) {
            log.error("视频删除失败", e);
            return R.fail("视频删除失败: " + e.getMessage());
        }
    }

    /**
     * 视频详情接口
     */
    @GetMapping("/detail")
    public R<Map<String, Object>> vlogDetail(@RequestParam String fileId) {
        try {
            // 获取视频基本信息
            Map<String, Object> result = vlogService.getVlogDetailInfo(fileId);

            // 获取视频上传者信息
            Map<String, String> uploaderInfo = vlogService.getVlogUploaderInfo(fileId);
            if (uploaderInfo != null) {
                result.put("uploaderName", uploaderInfo.get("name"));
                result.put("uploaderPhone", uploaderInfo.get("phone"));
            }

            return R.ok(result);
        } catch (Exception e) {
            log.error("获取视频详情失败", e);
            return R.fail("获取视频详情失败: " + e.getMessage());
        }
    }

    @ApiOperation(value = "禁播/解禁视频", notes = "禁播/解禁视频接口")
    @PostMapping("/forbid")
    public R<Void> forbidMediaDistribution(@RequestBody Map<String, Object> params) {
        try {
            // 参数验证
            if (params == null) {
                return R.fail("参数不能为空");
            }

            Object fileIdsObj = params.get("fileIds");
            String operation = (String) params.get("operation");

            List<String> fileIds;
            if (fileIdsObj instanceof String) {
                // 如果是单个字符串，转换为列表
                fileIds = Collections.singletonList((String) fileIdsObj);
            } else if (fileIdsObj instanceof List) {
                // 如果已经是列表，直接使用
                fileIds = (List<String>) fileIdsObj;
            } else {
                return R.fail("媒体文件ID格式不正确");
            }

            if (fileIds.isEmpty()) {
                return R.fail("媒体文件ID列表不能为空");
            }
            if (fileIds.size() > 20) {
                return R.fail("每次最多可提交20个媒体文件");
            }
            if (!"forbid".equals(operation) && !"recover".equals(operation)) {
                return R.fail("操作类型无效，只能是forbid(禁播)或recover(解禁)");
            }

            // 调用服务层方法
            vlogUploadService.forbidMediaDistribution(fileIds, operation);
            // 如果是禁播操作，将数据库中的状态改为4（删除）
            if ("forbid".equals(operation)) {
                for (String fileId : fileIds) {
                    vlogService.updateVlogStatus(fileId, 4, "视频已被禁播");
                }
            }
            // 返回成功结果
            return R.ok("操作成功");
        } catch (IllegalArgumentException e) {
            log.error("参数错误: {}", e.getMessage());
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("操作失败: {}", e.getMessage(), e);
            return R.fail("操作失败: " + e.getMessage());
        }
    }

    @ApiOperation(value = "根据vlogerId查询用户信息", notes = "查询视频上传者的姓名和电话")
    @GetMapping("/user-info")
    public R<Map<String, String>> getUserInfoByVlogerId(@RequestParam String vlogerId) {
        try {
            if (StringUtils.isBlank(vlogerId)) {
                return R.fail("vlogerId不能为空");
            }

            // 获取视频上传者信息
            Map<String, String> uploaderInfo = vlogService.getVlogUploaderInfo(vlogerId);
            if (uploaderInfo == null || uploaderInfo.isEmpty()) {
                return R.fail("未找到对应的用户信息");
            }

            return R.ok(uploaderInfo);
        } catch (Exception e) {
            log.error("获取用户信息失败", e);
            return R.fail("获取用户信息失败: " + e.getMessage());
        }
    }
}
