package com.rj.controller;

import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rj.entity.VideoImageAnalysis;
import com.rj.service.IVideoImageAnalysisService;
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.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.rj.service.MinIOService;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * AI视频图像分析记录 前端控制器
 * Qwen3-VL-Plus模型的视觉理解能力最强，Qwen-VL-Max（基于Qwen2.5-VL）次之；Qwen-VL-Plus（基于Qwen2.5-VL）模型在效果、成本上比较均衡，
 * 如果您暂时不确定使用某种模型，可以优先尝试使用通义千问Qwen3-VL-Plus模型。
 * @author 系统生成
 * @date 2025/1/30
 */
@Slf4j
@RestController
@RequestMapping("/api/video-image-analysis")
@Tag(name = "AI视频图像分析记录", description = "AI视频图像分析记录相关接口")
public class VideoImageAnalysisController {

    @Autowired
    private IVideoImageAnalysisService videoImageAnalysisService;

    @Autowired
    private MinIOService minIOService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Value("${dashscope.api.key}")
    private String dashscopeApiKey;

    /**
     * 分页查询AI视频图像分析记录列表
     */
    @GetMapping("/list")
    @Operation(summary = "分页查询AI视频图像分析记录列表", description = "根据条件分页查询AI视频图像分析记录信息列表")
    public ResponseEntity<Map<String, Object>> getAnalysisList(
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小", example = "10") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "AI模型") @RequestParam(required = false) String model,
            @Parameter(description = "用户姓名（模糊查询）") @RequestParam(required = false) String userName,
            @Parameter(description = "用户电话") @RequestParam(required = false) String userPhone,
            @Parameter(description = "会话名称（模糊查询）") @RequestParam(required = false) String sessionName,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status,
            @Parameter(description = "开始日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @Parameter(description = "结束日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {
        
        log.info("分页查询AI视频图像分析记录列表，模型={}, 用户姓名={}, 用户电话={}, 会话名称={}, 状态={}, 开始日期={}, 结束日期={}", 
                model, userName, userPhone, sessionName, status, startDate, endDate);

        Map<String, Object> result = new HashMap<>();
        try {
            Page<VideoImageAnalysis> page = new Page<>(current, size);
            LambdaQueryWrapper<VideoImageAnalysis> queryWrapper = new LambdaQueryWrapper<>();
            
            // 添加查询条件
            if (model != null && !model.trim().isEmpty()) {
                queryWrapper.like(VideoImageAnalysis::getModel, model);
            }
            if (userName != null && !userName.trim().isEmpty()) {
                queryWrapper.like(VideoImageAnalysis::getUserName, userName);
            }
            if (userPhone != null && !userPhone.trim().isEmpty()) {
                queryWrapper.like(VideoImageAnalysis::getUserPhone, userPhone);
            }
            if (sessionName != null && !sessionName.trim().isEmpty()) {
                queryWrapper.like(VideoImageAnalysis::getSessionName, sessionName);
            }
            if (status != null) {
                queryWrapper.eq(VideoImageAnalysis::getStatus, status);
            }
            if (startDate != null) {
                queryWrapper.ge(VideoImageAnalysis::getCreatedAt, startDate.atStartOfDay());
            }
            if (endDate != null) {
                queryWrapper.le(VideoImageAnalysis::getCreatedAt, endDate.atTime(23, 59, 59));
            }
            
            // 按创建时间倒序排列
            queryWrapper.orderByDesc(VideoImageAnalysis::getCreatedAt);
            
            Page<VideoImageAnalysis> analysisPage = videoImageAnalysisService.page(page, queryWrapper);
            
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", analysisPage.getRecords());
            result.put("total", analysisPage.getTotal());
            result.put("current", analysisPage.getCurrent());
            result.put("size", analysisPage.getSize());
            result.put("pages", analysisPage.getPages());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("分页查询AI视频图像分析记录列表失败", e);
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据条件查询AI视频图像分析记录（不分页）
     */
    @GetMapping("/query")
    @Operation(summary = "根据条件查询AI视频图像分析记录", description = "根据条件查询AI视频图像分析记录信息（不分页）")
    public ResponseEntity<Map<String, Object>> getAnalysisList(
            @Parameter(description = "AI模型") @RequestParam(required = false) String model,
            @Parameter(description = "用户姓名") @RequestParam(required = false) String userName,
            @Parameter(description = "用户电话") @RequestParam(required = false) String userPhone,
            @Parameter(description = "会话名称") @RequestParam(required = false) String sessionName,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status,
            @Parameter(description = "开始日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @Parameter(description = "结束日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            LambdaQueryWrapper<VideoImageAnalysis> queryWrapper = new LambdaQueryWrapper<>();
            
            // 添加查询条件
            if (model != null && !model.trim().isEmpty()) {
                queryWrapper.like(VideoImageAnalysis::getModel, model);
            }
            if (userName != null && !userName.trim().isEmpty()) {
                queryWrapper.like(VideoImageAnalysis::getUserName, userName);
            }
            if (userPhone != null && !userPhone.trim().isEmpty()) {
                queryWrapper.like(VideoImageAnalysis::getUserPhone, userPhone);
            }
            if (sessionName != null && !sessionName.trim().isEmpty()) {
                queryWrapper.like(VideoImageAnalysis::getSessionName, sessionName);
            }
            if (status != null) {
                queryWrapper.eq(VideoImageAnalysis::getStatus, status);
            }
            if (startDate != null) {
                queryWrapper.ge(VideoImageAnalysis::getCreatedAt, startDate.atStartOfDay());
            }
            if (endDate != null) {
                queryWrapper.le(VideoImageAnalysis::getCreatedAt, endDate.atTime(23, 59, 59));
            }
            
            // 按创建时间倒序排列
            queryWrapper.orderByDesc(VideoImageAnalysis::getCreatedAt);
            
            List<VideoImageAnalysis> analysisList = videoImageAnalysisService.list(queryWrapper);
            
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", analysisList);
            result.put("total", analysisList.size());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("根据条件查询AI视频图像分析记录失败", e);
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据ID查询AI视频图像分析记录
     */
    @GetMapping("/{id}")
    @Operation(summary = "根据ID查询AI视频图像分析记录", description = "根据主键ID查询单条AI视频图像分析记录信息")
    public ResponseEntity<Map<String, Object>> getAnalysisById(
            @Parameter(description = "AI视频图像分析记录ID", required = true)
            @PathVariable String id) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            VideoImageAnalysis analysis = videoImageAnalysisService.getById(id);
            if (analysis != null) {
                result.put("success", true);
                result.put("message", "查询成功");
                result.put("data", analysis);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "AI视频图像分析记录不存在");
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            log.error("根据ID查询AI视频图像分析记录失败", e);
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据用户姓名查询AI视频图像分析记录
     */
    @GetMapping("/by-user-name/{userName}")
    @Operation(summary = "根据用户姓名查询AI视频图像分析记录", description = "根据用户姓名查询AI视频图像分析记录信息")
    public ResponseEntity<Map<String, Object>> getAnalysisByUserName(
            @Parameter(description = "用户姓名", required = true)
            @PathVariable String userName) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            VideoImageAnalysis analysis = videoImageAnalysisService.getByUserName(userName);
            if (analysis != null) {
                result.put("success", true);
                result.put("message", "查询成功");
                result.put("data", analysis);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "未找到对应的AI视频图像分析记录");
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            log.error("根据用户姓名查询AI视频图像分析记录失败", e);
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据用户电话查询AI视频图像分析记录
     */
    @GetMapping("/by-user-phone/{userPhone}")
    @Operation(summary = "根据用户电话查询AI视频图像分析记录", description = "根据用户电话查询AI视频图像分析记录信息")
    public ResponseEntity<Map<String, Object>> getAnalysisByUserPhone(
            @Parameter(description = "用户电话", required = true)
            @PathVariable String userPhone) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            VideoImageAnalysis analysis = videoImageAnalysisService.getByUserPhone(userPhone);
            if (analysis != null) {
                result.put("success", true);
                result.put("message", "查询成功");
                result.put("data", analysis);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "未找到对应的AI视频图像分析记录");
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            log.error("根据用户电话查询AI视频图像分析记录失败", e);
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据会话名称查询AI视频图像分析记录
     */
    @GetMapping("/by-session-name/{sessionName}")
    @Operation(summary = "根据会话名称查询AI视频图像分析记录", description = "根据会话名称查询AI视频图像分析记录信息")
    public ResponseEntity<Map<String, Object>> getAnalysisBySessionName(
            @Parameter(description = "会话名称", required = true)
            @PathVariable String sessionName) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            VideoImageAnalysis analysis = videoImageAnalysisService.getBySessionName(sessionName);
            if (analysis != null) {
                result.put("success", true);
                result.put("message", "查询成功");
                result.put("data", analysis);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "未找到对应的AI视频图像分析记录");
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            log.error("根据会话名称查询AI视频图像分析记录失败", e);
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据模型查询AI视频图像分析记录
     */
    @GetMapping("/by-model/{model}")
    @Operation(summary = "根据模型查询AI视频图像分析记录", description = "根据模型查询AI视频图像分析记录信息")
    public ResponseEntity<Map<String, Object>> getAnalysisByModel(
            @Parameter(description = "AI模型", required = true)
            @PathVariable String model) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            VideoImageAnalysis analysis = videoImageAnalysisService.getByModel(model);
            if (analysis != null) {
                result.put("success", true);
                result.put("message", "查询成功");
                result.put("data", analysis);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "未找到对应的AI视频图像分析记录");
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            log.error("根据模型查询AI视频图像分析记录失败", e);
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 新增AI视频图像分析记录
     */
    @PostMapping("/add")
    @Operation(summary = "新增AI视频图像分析记录", description = "新增一条AI视频图像分析记录")
    public ResponseEntity<Map<String, Object>> addAnalysis(
            @Parameter(description = "AI视频图像分析记录信息", required = true)
            @Valid @RequestBody VideoImageAnalysis analysis) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            // 设置系统字段
            LocalDateTime now = LocalDateTime.now();
            analysis.setCreatedAt(now);
            analysis.setUpdatedAt(now);
            
            // 设置默认值
            if (analysis.getRole() == null || analysis.getRole().trim().isEmpty()) {
                analysis.setRole("assistant");
            }
            if (analysis.getChoiceIndex() == null) {
                analysis.setChoiceIndex(0);
            }
            if (analysis.getStatus() == null) {
                analysis.setStatus(1);
            }
            
            boolean success = videoImageAnalysisService.saveVideoImageAnalysis(analysis);
            if (success) {
                result.put("success", true);
                result.put("message", "AI视频图像分析记录添加成功");
                result.put("data", analysis);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "AI视频图像分析记录添加失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            log.error("新增AI视频图像分析记录失败", e);
            result.put("success", false);
            result.put("message", "添加异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 修改AI视频图像分析记录
     */
    @PutMapping("/update")
    @Operation(summary = "修改AI视频图像分析记录", description = "修改AI视频图像分析记录信息")
    public ResponseEntity<Map<String, Object>> updateAnalysis(
            @Parameter(description = "AI视频图像分析记录信息", required = true)
            @Valid @RequestBody VideoImageAnalysis analysis) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            if (analysis.getId() == null || analysis.getId().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            // 检查记录是否存在
            VideoImageAnalysis existingAnalysis = videoImageAnalysisService.getById(analysis.getId());
            if (existingAnalysis == null) {
                result.put("success", false);
                result.put("message", "AI视频图像分析记录不存在");
                return ResponseEntity.notFound().build();
            }
            
            // 设置更新时间
            analysis.setUpdatedAt(LocalDateTime.now());
            
            boolean success = videoImageAnalysisService.updateById(analysis);
            if (success) {
                result.put("success", true);
                result.put("message", "AI视频图像分析记录修改成功");
                result.put("data", analysis);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "AI视频图像分析记录修改失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            log.error("修改AI视频图像分析记录失败", e);
            result.put("success", false);
            result.put("message", "修改异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 删除AI视频图像分析记录
     */
    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除AI视频图像分析记录", description = "根据ID删除AI视频图像分析记录")
    public ResponseEntity<Map<String, Object>> deleteAnalysis(
            @Parameter(description = "AI视频图像分析记录ID", required = true)
            @PathVariable String id) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            // 检查记录是否存在
            VideoImageAnalysis existingAnalysis = videoImageAnalysisService.getById(id);
            if (existingAnalysis == null) {
                result.put("success", false);
                result.put("message", "AI视频图像分析记录不存在");
                return ResponseEntity.notFound().build();
            }
            
            boolean success = videoImageAnalysisService.removeById(id);
            if (success) {
                result.put("success", true);
                result.put("message", "AI视频图像分析记录删除成功");
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "AI视频图像分析记录删除失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            log.error("删除AI视频图像分析记录失败", e);
            result.put("success", false);
            result.put("message", "删除异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 批量删除AI视频图像分析记录
     */
    @DeleteMapping("/batch-delete")
    @Operation(summary = "批量删除AI视频图像分析记录", description = "根据ID列表批量删除AI视频图像分析记录")
    public ResponseEntity<Map<String, Object>> batchDeleteAnalysis(
            @Parameter(description = "AI视频图像分析记录ID列表", required = true)
            @RequestBody List<String> ids) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            if (ids == null || ids.isEmpty()) {
                result.put("success", false);
                result.put("message", "ID列表不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            
            boolean success = videoImageAnalysisService.removeByIds(ids);
            if (success) {
                result.put("success", true);
                result.put("message", "AI视频图像分析记录批量删除成功");
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "AI视频图像分析记录批量删除失败");
                return ResponseEntity.badRequest().body(result);
            }
        } catch (Exception e) {
            log.error("批量删除AI视频图像分析记录失败", e);
            result.put("success", false);
            result.put("message", "批量删除异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 获取AI视频图像分析记录统计信息
     */
    @GetMapping("/statistics")
    @Operation(summary = "获取AI视频图像分析记录统计信息", description = "获取AI视频图像分析记录的统计信息")
    public ResponseEntity<Map<String, Object>> getAnalysisStatistics(
            @Parameter(description = "开始日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @Parameter(description = "结束日期") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate,
            @Parameter(description = "AI模型") @RequestParam(required = false) String model) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            LambdaQueryWrapper<VideoImageAnalysis> queryWrapper = new LambdaQueryWrapper<>();
            
            // 添加查询条件
            if (startDate != null) {
                queryWrapper.ge(VideoImageAnalysis::getCreatedAt, startDate.atStartOfDay());
            }
            if (endDate != null) {
                queryWrapper.le(VideoImageAnalysis::getCreatedAt, endDate.atTime(23, 59, 59));
            }
            if (model != null && !model.trim().isEmpty()) {
                queryWrapper.eq(VideoImageAnalysis::getModel, model);
            }
            
            List<VideoImageAnalysis> analysisList = videoImageAnalysisService.list(queryWrapper);
            
            // 计算统计信息
            Map<String, Object> statistics = new HashMap<>();
            statistics.put("totalCount", analysisList.size());
            statistics.put("successCount", analysisList.stream().filter(a -> a.getStatus() == 1).count());
            statistics.put("failCount", analysisList.stream().filter(a -> a.getStatus() == 0).count());
            statistics.put("uniqueUsers", analysisList.stream().map(VideoImageAnalysis::getUserName).distinct().count());
            statistics.put("uniqueSessions", analysisList.stream().map(VideoImageAnalysis::getSessionName).distinct().count());
            
            // 按模型统计
            Map<String, Long> modelStats = analysisList.stream()
                    .collect(java.util.stream.Collectors.groupingBy(
                            VideoImageAnalysis::getModel,
                            java.util.stream.Collectors.counting()));
            statistics.put("modelStatistics", modelStats);
            
            // 按状态统计
            Map<Integer, Long> statusStats = analysisList.stream()
                    .collect(java.util.stream.Collectors.groupingBy(
                            VideoImageAnalysis::getStatus,
                            java.util.stream.Collectors.counting()));
            statistics.put("statusStatistics", statusStats);
            
            result.put("success", true);
            result.put("message", "统计信息获取成功");
            result.put("data", statistics);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("获取AI视频图像分析记录统计信息失败", e);
            result.put("success", false);
            result.put("message", "统计信息获取异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * AI分析接口 - 处理图片/视频分析请求
     */
    @PostMapping("/ai-analysis")
    @Operation(summary = "AI分析接口", description = "处理图片/视频的AI分析请求")
    public ResponseEntity<Map<String, Object>> aiAnalysis(
            @Parameter(description = "分析名称", required = true) @RequestParam String analysisName,
            @Parameter(description = "所属人姓名", required = true) @RequestParam String ownerName,
            @Parameter(description = "所属人电话", required = true) @RequestParam String ownerPhone,
            @Parameter(description = "AI模型", required = true) @RequestParam String model,
            @Parameter(description = "分析类型", required = true) @RequestParam String type,
            @Parameter(description = "用户问题", required = true) @RequestParam String userQuestion,
            @Parameter(description = "上传的文件") @RequestParam(required = false) MultipartFile file) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            log.info("AI分析请求开始，分析名称={}, 所属人={}, 电话={}, 模型={}, 分析类型={}, 问题={}", 
                    analysisName, ownerName, ownerPhone, model, type, userQuestion);

            // 创建分析记录
            VideoImageAnalysis analysis = new VideoImageAnalysis();
            analysis.setModel(model);
            analysis.setType(type);
            analysis.setUserQuestion(userQuestion);
            analysis.setUserName(ownerName);
            analysis.setUserPhone(ownerPhone);
            analysis.setSessionName(analysisName);
            analysis.setRole("assistant");
            analysis.setChoiceIndex(0);
            analysis.setStatus(1); // 默认成功状态
            
            // 处理文件上传
            if (file != null && !file.isEmpty()) {
                // 上传文件到MinIO并获取原始链接和临时访问链接
                Map<String, String> uploadResult = handleFileUploadWithBothUrls(file);
                analysis.setVideoImageUrl(uploadResult.get("originalUrl"));
                analysis.setVideoImageTempUrl(uploadResult.get("tempUrl"));
            }
            
            // 设置系统字段
            LocalDateTime now = LocalDateTime.now();
            analysis.setCreatedAt(now);
            analysis.setUpdatedAt(now);
            
            // 调用阿里云AI服务进行实际分析
            Map<String, Object> aiResult=null;
            if ("video".equals(type) ){
                aiResult = performAiAnalysisWithDetailsForVideo(model, type, userQuestion, analysis.getVideoImageTempUrl());
            }else {
                aiResult = performAiAnalysisWithDetails(model, type, userQuestion, analysis.getVideoImageTempUrl());
            }

            String aiResponse = (String) aiResult.get("content");
            analysis.setResponseContent(aiResponse);
            
            // 保存请求和响应数据到数据库
            String requestData = (String) aiResult.getOrDefault("requestData", "{}");
            String responseData = (String) aiResult.getOrDefault("responseData", "{}");
            analysis.setRequestData(requestData);
            analysis.setResponseData(responseData);
            
            // 记录AI分析结果和token使用情况
            analysis.setFinishReason("stop");
             try {
                 analysis.setUsagePromptTokens((Integer) aiResult.getOrDefault("promptTokens", Integer.valueOf(0)));
                 analysis.setUsageCompletionTokens((Integer) aiResult.getOrDefault("completionTokens", Integer.valueOf(0)));
                 analysis.setUsageTotalTokens((Integer) aiResult.getOrDefault("totalTokens", Integer.valueOf(0)));

             }   catch (Exception e) {
               log.error("获取token使用情况失败:{}" ,e );
             }

            // 保存分析记录
            boolean success = videoImageAnalysisService.saveVideoImageAnalysis(analysis);
            
            if (success) {
                result.put("success", true);
                result.put("message", "AI分析完成");
                result.put("data", analysis);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "AI分析失败");
                return ResponseEntity.badRequest().body(result);
            }
            
        } catch (Exception e) {
            log.error("AI分析请求失败", e);
            result.put("success", false);
            result.put("message", "AI分析异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 处理文件上传到MinIO并生成原始链接和7天临时访问链接
     * @param file 上传的文件
     * @return 包含原始URL和临时URL的Map
     */
    private Map<String, String> handleFileUploadWithBothUrls(MultipartFile file) {
        try {
            log.info("开始上传文件到MinIO，文件名：{}, 大小：{}", file.getOriginalFilename(), file.getSize());
            
            // 上传文件到MinIO并获取原始链接
            String originalUrl = minIOService.uploadFile(file);
            log.info("文件上传成功，原始URL：{}", originalUrl);
            
            // 从原始URL中提取对象名，用于生成临时链接
            String objectName = extractObjectNameFromUrl(originalUrl);
            String tempUrl = minIOService.generateTempUrl(objectName);
            log.info("生成7天临时访问URL：{}", tempUrl);
            
            Map<String, String> result = new HashMap<>();
            result.put("originalUrl", originalUrl);
            result.put("tempUrl", tempUrl);
            
            return result;
        } catch (Exception e) {
            log.error("文件上传失败", e);
            throw new RuntimeException("文件上传失败：" + e.getMessage());
        }
    }

    /**
     * 从MinIO URL中提取对象名
     * @param url MinIO文件URL
     * @return 对象名
     */
    private String extractObjectNameFromUrl(String url) {
        try {
            // MinIO URL格式通常是: http://endpoint/bucket/objectName
            // 或者: http://endpoint/bucket/objectName?参数
            log.info("从URL提取对象名: {}", url);
            
            // 去掉查询参数
            String urlWithoutParams = url;
            if (url.contains("?")) {
                urlWithoutParams = url.substring(0, url.indexOf("?"));
            }
            
            // 按"/"分割URL
            String[] parts = urlWithoutParams.split("/");
            if (parts.length >= 2) {
                // 获取最后一个部分作为对象名
                String objectName = parts[parts.length - 1];
                log.info("提取到的对象名: {}", objectName);
                return objectName;
            }
            
            throw new RuntimeException("无法从URL中提取对象名: " + url);
        } catch (Exception e) {
            log.error("提取对象名失败", e);
            throw new RuntimeException("提取对象名失败: " + e.getMessage());
        }
    }
    private Map<String, Object> performAiAnalysisWithDetailsForVideo(String model, String type, String userQuestion, String fileUrl) {
        MultiModalConversation conv = new MultiModalConversation();
        Map<String, Object> result = new HashMap<>();


        // fps 可参数控制视频抽帧频率，表示每隔 1/fps 秒抽取一帧，完整用法请参见：https://help.aliyun.com/zh/model-studio/use-qwen-by-calling-api?#2ed5ee7377fum
        Map<String, Object> params = new HashMap<>();
//        params.put("video", "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241115/cqqkru/1.mp4");
        params.put("video",fileUrl);

        params.put("fps", 2);
        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                .content(Arrays.asList(
                        params,
                        Collections.singletonMap("text", userQuestion))).build();


        MultiModalConversationParam param = MultiModalConversationParam.builder()
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model(model)
                .messages(Arrays.asList(userMessage))
                .build();
        result.put("requestData", userMessage.toString());
        MultiModalConversationResult callResult = null;
        try {
            callResult = conv.call(param);
        } catch (NoApiKeyException e) {
            throw new RuntimeException(e);
        } catch (UploadFileException e) {
            throw new RuntimeException(e);
        }
        result.put("responseData", callResult.toString());
        System.out.println(callResult.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));

        result.put("content",callResult.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text") );
        result.put("promptTokens",callResult.getUsage().getInputTokens() );
        result.put("completionTokens",callResult.getUsage().getOutputTokensDetails() );
        result.put("totalTokens",callResult.getUsage().getTotalTokens() );
        return result;
    }
    /**
     * 执行AI分析 - 调用阿里云通义千问API（返回详细信息）
     */
    private Map<String, Object> performAiAnalysisWithDetails(String model, String type, String userQuestion, String fileUrl) {
        try {
            log.info("执行AI分析，模型：{}, 分析类型：{}, 问题：{}, 文件：{}", model, type, userQuestion, fileUrl);
            
            // 构建请求URL
            String apiUrl = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";
            
            // 构建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + dashscopeApiKey);
            
            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", model);
            
            // 构建消息内容
            List<Map<String, Object>> messages = new ArrayList<>();
            Map<String, Object> message = new HashMap<>();
            message.put("role", "user");
            
            List<Map<String, Object>> content = new ArrayList<>();

            Map<String, Object> imageContent = new HashMap<>();
            imageContent.put("type", type);

            if (type.equals("video")) {
                // 检查是否提供了图片序列
                if (fileUrl == null || fileUrl.trim().isEmpty()) {
                    throw new RuntimeException("视频分析需要提供图片序列，当前未提供任何文件");
                }
                
                // 检查是否为图片序列（通过URL数量判断）
                // 这里假设如果fileUrl包含多个URL（用逗号分隔），则为图片序列
                    // 满足要求的图片序列
                    Map<String, Object> videoContent = new HashMap<>();
                    videoContent.put("video", Arrays.asList(fileUrl));
                    content.add(videoContent);

            } else if (type.equals("image_url")) {
                /**
                 * [{"role": "user","content": [
                 *             {"type": "image_url",
                 *              "image_url": {"url": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"}},
                 *             {"type": "text", "text": "这是什么"},
                 *             ]}]
                 */
                // 如果有文件URL，添加图片内容
                if (fileUrl != null && !fileUrl.trim().isEmpty()) {

                    Map<String, Object> imageUrl = new HashMap<>();
                    imageUrl.put("url", fileUrl);
                    imageContent.put("image_url", imageUrl);
                    content.add(imageContent);
                }
            }

            
            // 添加文本内容，包含分析类型信息
            Map<String, Object> textContent = new HashMap<>();
            textContent.put("type", "text");
            String enhancedQuestion = String.format("分析类型：%s\n用户问题：%s", type, userQuestion);
            textContent.put("text", enhancedQuestion);
            content.add(textContent);
            
            message.put("content", content);
            messages.add(message);
            requestBody.put("messages", messages);
            
            // 创建HTTP实体
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

            // 保存请求数据到结果中
            String requestDataJson = objectMapper.writeValueAsString(requestBody);
            log.info("调用阿里云AI分析API， 请求体：{}", requestDataJson);
            Map<String, Object> result = new HashMap<>();
            result.put("requestData", requestDataJson);
            // 发送请求
            ResponseEntity<String> response = restTemplate.exchange(
                apiUrl,
                HttpMethod.POST,
                entity,
                String.class
            );

            log.info("阿里云AI分析API响应内容：{}", response.getBody());
            // 保存响应数据
            String responseDataJson = response.getBody();
            result.put("responseData", responseDataJson);

            if (response.getStatusCode().is2xxSuccessful()) {
                // 解析响应
                JsonNode responseJson = objectMapper.readTree(response.getBody());
                JsonNode choices = responseJson.path("choices");
                if (choices.isArray() && choices.size() > 0) {
                    JsonNode firstChoice = choices.get(0);
                    JsonNode messageNode = firstChoice.path("message");
                    String contentText = messageNode.path("content").asText();
                    
                    // 记录token使用情况
                    JsonNode usage = responseJson.path("usage");

                    result.put("content", contentText);
                    
                    if (!usage.isMissingNode()) {
                        int promptTokens = usage.path("prompt_tokens").asInt();
                        int completionTokens = usage.path("completion_tokens").asInt();
                        int totalTokens = usage.path("total_tokens").asInt();
                        
                    result.put("promptTokens", promptTokens);
                    result.put("completionTokens", completionTokens);
                    result.put("totalTokens", totalTokens);
                    
                    log.info("Token使用情况 - 提示词：{}, 完成：{}, 总计：{}", 
                        promptTokens, completionTokens, totalTokens);
                } else {
                    result.put("promptTokens", 0);
                    result.put("completionTokens", 0);
                    result.put("totalTokens", 0);
                }
                

                
                return result;
                } else {
                    log.error("AI分析响应格式异常，未找到choices");
                    Map<String, Object> errorResult = new HashMap<>();
                    errorResult.put("content", "AI分析响应格式异常");
                    errorResult.put("promptTokens", 0);
                    errorResult.put("completionTokens", 0);
                    errorResult.put("totalTokens", 0);
                    errorResult.put("requestData", requestDataJson);
                    errorResult.put("responseData", responseDataJson);
                    return errorResult;
                }
            } else {
                log.error("AI分析API调用失败，状态码：{}", response.getStatusCode());
                Map<String, Object> errorResult = new HashMap<>();
                errorResult.put("content", "AI分析API调用失败：" + response.getStatusCode());
                errorResult.put("promptTokens", 0);
                errorResult.put("completionTokens", 0);
                errorResult.put("totalTokens", 0);
                errorResult.put("requestData", requestDataJson);
                errorResult.put("responseData", responseDataJson);
                return errorResult;
            }
            
        } catch (Exception e) {
            log.error("AI分析执行失败", e);
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("content", "AI分析执行失败：" + e.getMessage());
            errorResult.put("promptTokens", 0);
            errorResult.put("completionTokens", 0);
            errorResult.put("totalTokens", 0);
            // 异常情况下可能没有完整的请求数据
            errorResult.put("requestData", "{}");
            errorResult.put("responseData", "{}");
            return errorResult;
        }
    }
}
