package com.moka.gdtauto.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.moka.gdtauto.common.Result;
import com.moka.gdtauto.entity.TencentVideo;
import com.moka.gdtauto.service.TencentVideoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.moka.gdtauto.entity.SysUser;
import com.moka.gdtauto.annotation.AuthUser;

/**
 * 腾讯广告视频上传Controller
 *
 * @author moka
 * @since 2026-02-06
 */
@Slf4j
@RestController
@RequestMapping("/api/tencent-video")
@Api(tags = "腾讯广告视频管理")
public class TencentVideoController {

    @Autowired
    private TencentVideoService videoService;

    /**
     * 上传视频到腾讯广告
     */
    @PostMapping("/upload")
    @ApiOperation("上传视频到腾讯广告")
    public Result<TencentVideo> uploadVideo(
            @ApiParam("视频文件") @RequestParam("file") MultipartFile file,
            @ApiParam("广告账户ID") @RequestParam("accountId") Long accountId,
            @ApiParam("是否添加水印") @RequestParam(value = "hasWatermark", required = false, defaultValue = "false") Boolean hasWatermark,
            @ApiParam("剧ID") @RequestParam(value = "dramaId", required = false) Long dramaId,
            @ApiParam("水印时长(秒)") @RequestParam(value = "watermarkDuration", required = false) Integer watermarkDuration,
            @ApiParam("视频描述") @RequestParam(value = "description", required = false) String description,
            @AuthUser SysUser user) {

        try {
            log.info("开始上传视频: 文件名={}, 账户ID={}, 是否添加水印={}, 剧ID={}, 水印时长={}",
                    file.getOriginalFilename(), accountId, hasWatermark, dramaId, watermarkDuration);

            // 校验文件
            if (file.isEmpty()) {
                return Result.fail("视频文件不能为空");
            }

            // 校验文件格式
            String filename = file.getOriginalFilename();
            if (filename == null || (!filename.toLowerCase().endsWith(".mp4")
                    && !filename.toLowerCase().endsWith(".mov")
                    && !filename.toLowerCase().endsWith(".avi"))) {
                return Result.fail("仅支持MP4、MOV、AVI格式的视频");
            }

            // 校验文件大小（最大100MB）
            if (file.getSize() > 100 * 1024 * 1024) {
                return Result.fail("视频大小不能超过100MB");
            }

            // 如果选择添加水印，必须选择剧
            if (hasWatermark && dramaId == null) {
                return Result.fail("添加水印时必须选择剧");
            }

            // 校验水印时长
            if (watermarkDuration != null && watermarkDuration <= 0) {
                return Result.fail("水印时长必须大于0秒");
            }

            // 上传视频
            TencentVideo result = videoService.uploadVideo(user.getJobNumber(), accountId, file, hasWatermark, dramaId, watermarkDuration, description);

            if ("SUCCESS".equals(result.getUploadStatus())) {
                log.info("视频上传成功，ID: {}", result.getId());
                return Result.success(result, "视频上传成功");
            } else {
                log.error("视频上传失败: {}", result.getErrorMessage());
                return Result.fail("视频上传失败: " + result.getErrorMessage());
            }

        } catch (Exception e) {
            log.error("上传视频异常", e);
            return Result.fail("上传视频异常: " + e.getMessage());
        }
    }

    /**
     * 分页查询视频列表
     */
    @GetMapping("/list")
    @ApiOperation("分页查询视频列表")
    public Result<Page<TencentVideo>> list(
            @ApiParam("页码") @RequestParam(defaultValue = "1") Long page,
            @ApiParam("每页数量") @RequestParam(defaultValue = "10") Long size,
            @ApiParam("账户ID") @RequestParam(required = false) Long accountId,
            @ApiParam("上传状态") @RequestParam(required = false) String uploadStatus) {

        try {
            Page<TencentVideo> pageParam = new Page<>(page, size);
            LambdaQueryWrapper<TencentVideo> wrapper = new LambdaQueryWrapper<>();

            if (accountId != null) {
                wrapper.eq(TencentVideo::getAccountId, accountId);
            }
            if (uploadStatus != null && !uploadStatus.trim().isEmpty()) {
                wrapper.eq(TencentVideo::getUploadStatus, uploadStatus);
            }

            wrapper.orderByDesc(TencentVideo::getCreatedTime);

            Page<TencentVideo> result = videoService.page(pageParam, wrapper);
            return Result.success(result);

        } catch (Exception e) {
            log.error("查询视频列表异常", e);
            return Result.fail("查询视频列表异常: " + e.getMessage());
        }
    }

    /**
     * 根据ID查询视频详情
     */
    @GetMapping("/{id}")
    @ApiOperation("根据ID查询视频详情")
    public Result<TencentVideo> getById(@ApiParam("视频ID") @PathVariable Long id) {
        try {
            TencentVideo video = videoService.getById(id);
            if (video == null) {
                return Result.fail("视频不存在");
            }
            return Result.success(video);
        } catch (Exception e) {
            log.error("查询视频详情异常", e);
            return Result.fail("查询视频详情异常: " + e.getMessage());
        }
    }

    /**
     * 删除视频记录
     */
    @DeleteMapping("/{id}")
    @ApiOperation("删除视频记录")
    public Result<Void> delete(@ApiParam("视频ID") @PathVariable Long id) {
        try {
            boolean success = videoService.removeById(id);
            if (success) {
                log.info("删除视频记录成功，ID: {}", id);
                return Result.success(null, "删除成功");
            } else {
                return Result.fail("删除失败");
            }
        } catch (Exception e) {
            log.error("删除视频记录异常", e);
            return Result.fail("删除视频记录异常: " + e.getMessage());
        }
    }
}
