package com.rj.controller;

import com.rj.service.IDetectVideoTemplateService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * 检测视频模板控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/detect-video-template")
@Tag(name = "检测视频模板", description = "检测视频模板相关接口")
public class DetectVideoTemplateController {
    
    @Autowired
    private IDetectVideoTemplateService detectVideoTemplateService;
    
    /**
     * 视频模板上传和检测接口
     */
    @PostMapping("/uploadAndDetect")
    @Operation(summary = "视频模板上传和检测", description = "上传视频模板文件，生成短链接并进行模板检测")
    public ResponseEntity<Map<String, Object>> uploadAndDetectVideoTemplate(
            @Parameter(description = "视频模板文件", required = true)
            @RequestParam("file") MultipartFile file,
            @Parameter(description = "用户ID", required = false)
            @RequestParam(value = "userId", required = false) String userId,
            @Parameter(description = "所属人姓名", required = false)
            @RequestParam(value = "ownerName", required = false) String ownerName,
            @Parameter(description = "所属人电话", required = false)
            @RequestParam(value = "ownerPhone", required = false) String ownerPhone,
            @Parameter(description = "模板名称", required = false)
            @RequestParam(value = "templateName", required = false) String templateName,
            @Parameter(description = "模型名称", required = false)
            @RequestParam(value = "model", required = false) String model,
            @Parameter(description = "短链接有效期（秒），默认7天", required = false)
            @RequestParam(value = "expiresInSeconds", defaultValue = "604800") int expiresInSeconds) {

        Map<String, Object> result = new HashMap<>();
        
        try {
            log.info("开始处理视频模板上传和检测，文件名: {}, 大小: {} bytes, 用户ID: {}", 
                    file.getOriginalFilename(), file.getSize(), userId);
            
            // 执行视频模板上传和检测
            com.rj.entity.DetectVideoTemplate detectLog = detectVideoTemplateService.uploadAndDetectVideoTemplate(
                file, userId, ownerName, ownerPhone, templateName, model, expiresInSeconds);
            
            // 构建响应结果
            result.put("success", detectLog.getSuccess());
            result.put("message", detectLog.getSuccess() ? "视频模板上传和检测成功" : "视频模板上传和检测失败");
            result.put("originalFileName", file.getOriginalFilename());
            result.put("fileSize", file.getSize());
            result.put("videoUrl", detectLog.getVideoUrl());
            result.put("tempUrl", detectLog.getTempUrl());
            result.put("tempUrlExpiresAt", detectLog.getTempUrlExpiresAt());
            result.put("requestId", detectLog.getRequestId());
            result.put("taskId", detectLog.getTaskId());
            result.put("taskStatus", detectLog.getTaskStatus());
            result.put("templateId", detectLog.getTemplateId());
            result.put("processingTimeMs", detectLog.getProcessingTimeMs());
            result.put("userId", userId);
            result.put("ownerName", detectLog.getOwnerName());
            result.put("ownerPhone", detectLog.getOwnerPhone());
            result.put("templateName", detectLog.getTemplateName());
            result.put("model", detectLog.getModel());
            result.put("expiresInSeconds", expiresInSeconds);
            
            // 视频模板检测结果
            result.put("videoTemplateDetection", detectLog.toString());
            
            if (!detectLog.getSuccess()) {
                result.put("errorMessage", detectLog.getErrorMessage());
                log.warn("视频模板检测失败: {}", detectLog.getErrorMessage());
                return ResponseEntity.badRequest().body(result);
            } else {
                log.info("视频模板检测成功，模板ID: {}", detectLog.getTemplateId());
            }
            
            log.info("视频模板上传和检测处理完成，文件URL: {}", detectLog.getVideoUrl());
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("视频模板上传和检测失败: {}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "视频模板上传和检测失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
    
    /**
     * 视频模板检测接口（JSON格式）
     */
    @PostMapping("/detect-json")
    @Operation(summary = "视频模板检测(JSON)", description = "检测视频模板信息，支持JSON请求体")
    public ResponseEntity<Map<String, Object>> detectVideoTemplateJson(@RequestBody Map<String, String> requestBody) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            String videoUrl = requestBody.get("videoUrl");
            String ownerName = requestBody.get("ownerName");
            String ownerPhone = requestBody.get("ownerPhone");
            String model = requestBody.get("model");
            String templateName = requestBody.get("templateName");
            
            if (videoUrl == null || videoUrl.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "视频URL不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            log.info("开始视频模板检测（JSON），视频URL: {}", videoUrl);
            
            // 执行视频模板检测
            com.rj.entity.DetectVideoTemplate detectLog = detectVideoTemplateService.detectVideoTemplateAndSave(videoUrl, ownerName, ownerPhone, templateName, model);
            
            result.put("success", detectLog.getSuccess());
            result.put("message", detectLog.getSuccess() ? "视频模板检测成功" : "视频模板检测失败");
            result.put("videoUrl", videoUrl);
            result.put("tempUrl", detectLog.getTempUrl());
            result.put("tempUrlExpiresAt", detectLog.getTempUrlExpiresAt());
            result.put("requestId", detectLog.getRequestId());
            result.put("taskId", detectLog.getTaskId());
            result.put("taskStatus", detectLog.getTaskStatus());
            result.put("templateId", detectLog.getTemplateId());
            result.put("processingTimeMs", detectLog.getProcessingTimeMs());
            result.put("ownerName", detectLog.getOwnerName());
            result.put("ownerPhone", detectLog.getOwnerPhone());
            result.put("templateName", detectLog.getTemplateName());
            result.put("model", detectLog.getModel());
            
            if (!detectLog.getSuccess()) {
                result.put("errorMessage", detectLog.getErrorMessage());
                return ResponseEntity.badRequest().body(result);
            }
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("视频模板检测失败: {}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "视频模板检测失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
    
    /**
     * 分页查询检测视频模板日志
     */
    @GetMapping("/logs")
    @Operation(summary = "查询检测日志", description = "分页查询检测视频模板日志")
    public ResponseEntity<Map<String, Object>> getLogs(
            @Parameter(description = "当前页", required = true)
            @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小", required = true)
            @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "是否成功", required = false)
            @RequestParam(required = false) Boolean success,
            @Parameter(description = "开始时间", required = false)
            @RequestParam(required = false) String startTime,
            @Parameter(description = "结束时间", required = false)
            @RequestParam(required = false) String endTime,
            @Parameter(description = "所属人姓名", required = false)
            @RequestParam(required = false) String ownerName,
            @Parameter(description = "所属人电话", required = false)
            @RequestParam(required = false) String ownerPhone,
            @Parameter(description = "模板名称", required = false)
            @RequestParam(required = false) String templateName) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.rj.entity.DetectVideoTemplate> page = 
                detectVideoTemplateService.getPageList(current, size, success, startTime, endTime, ownerName, ownerPhone, templateName);
            
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", page.getRecords());
            result.put("total", page.getTotal());
            result.put("current", page.getCurrent());
            result.put("size", page.getSize());
            result.put("pages", page.getPages());
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("查询检测日志失败: {}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
    
    /**
     * 获取统计信息
     */
    @GetMapping("/statistics")
    @Operation(summary = "获取统计信息", description = "获取检测视频模板的统计信息")
    public ResponseEntity<Map<String, Object>> getStatistics(
            @Parameter(description = "开始时间", required = false)
            @RequestParam(required = false) String startTime,
            @Parameter(description = "结束时间", required = false)
            @RequestParam(required = false) String endTime) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            Map<String, Object> statistics = detectVideoTemplateService.getStatistics(startTime, endTime);
            
            result.put("success", true);
            result.put("message", "统计信息获取成功");
            result.put("data", statistics);
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("获取统计信息失败: {}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "获取统计信息失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
}
