package com.ruoyi.web.controller.common;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.ThumbnailUtils;
import com.ruoyi.common.utils.VideoUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.base.domain.RobotOpsMediaAsset;
import com.ruoyi.base.service.IRobotOpsMediaAssetService;

// ... existing code ...

@RestController
@RequestMapping("/common")
public class CommonController
{
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private IRobotOpsMediaAssetService robotOpsMediaAssetService;

    private static final String FILE_DELIMITER = ",";

    // ... existing code ...

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 上传素材文件（单个）- 只上传文件，返回文件信息，不保存到数据库
     */
    @PostMapping("/uploadMediaFile")
    public AjaxResult uploadMediaFile(MultipartFile file) throws Exception
    {
        try
        {
            // 1. 上传文件
            String filePath = RuoYiConfig.getUploadPath();
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;

            // 2. 构建返回数据
            AjaxResult ajax = AjaxResult.success("上传成功");
            ajax.put("fileUrl", url);
            ajax.put("fileName", fileName);
            ajax.put("originalFilename", file.getOriginalFilename());
            ajax.put("fileSize", file.getSize());
            ajax.put("mimeType", file.getContentType());
            ajax.put("fileFormat", FileUtils.getExtension(file));

            // 3. 根据文件类型处理
            String contentType = file.getContentType();

            if (contentType != null && contentType.startsWith("image/"))
            {
                // 图片：生成缩略图和获取分辨率
                String thumbnailUrl = ThumbnailUtils.generateThumbnail(file);
                ajax.put("thumbnailUrl", thumbnailUrl);

                try
                {
                    java.awt.image.BufferedImage image = javax.imageio.ImageIO.read(file.getInputStream());
                    if (image != null)
                    {
                        String resolution = image.getWidth() + "x" + image.getHeight();
                        ajax.put("resolution", resolution);
                    }
                }
                catch (Exception e)
                {
                    log.warn("获取图片分辨率失败", e);
                }
            }
            else if (contentType != null && contentType.startsWith("video/"))
            {
                // 视频：生成缩略图、获取时长和分辨率
                try
                {
                    // 获取实际文件路径
                    String realFilePath = RuoYiConfig.getProfile() + FileUtils.stripPrefix(url);

                    // 生成视频缩略图（截取第1秒的画面）
                    String thumbnailUrl = VideoUtils.generateVideoThumbnail(realFilePath, 1);
                    ajax.put("thumbnailUrl", thumbnailUrl);

                    // 获取视频信息（时长和分辨率）
                    Map<String, Object> videoInfo = VideoUtils.getVideoInfo(realFilePath);
                    if (videoInfo.containsKey("durationSeconds"))
                    {
                        ajax.put("durationSeconds", videoInfo.get("durationSeconds"));
                    }
                    if (videoInfo.containsKey("resolution"))
                    {
                        ajax.put("resolution", videoInfo.get("resolution"));
                    }
                }
                catch (Exception e)
                {
                    log.warn("处理视频文件失败", e);
                }
            }

            return ajax;
        }
        catch (Exception e)
        {
            log.error("上传素材文件失败", e);
            return AjaxResult.error("上传失败: " + e.getMessage());
        }
    }

    // ... existing code ...

    /**
     * 通用上传请求（多个）
     */
    @PostMapping("/uploads")
    public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files)
            {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMITER));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMITER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMITER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMITER));
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 批量上传素材文件 - 只上传文件，返回文件信息列表，不保存到数据库
     */
    @PostMapping("/uploadMediaFiles")
    public AjaxResult uploadMediaFiles(List<MultipartFile> files) throws Exception
    {
        List<AjaxResult> fileInfoList = new ArrayList<>();
        int successCount = 0;
        int failedCount = 0;

        try
        {
            String filePath = RuoYiConfig.getUploadPath();

            for (MultipartFile file : files)
            {
                try
                {
                    // 1. 上传文件
                    String fileName = FileUploadUtils.upload(filePath, file);
                    String url = serverConfig.getUrl() + fileName;

                    // 2. 构建文件信息
                    AjaxResult fileInfo = AjaxResult.success();
                    fileInfo.put("fileUrl", url);
                    fileInfo.put("fileName", fileName);
                    fileInfo.put("originalFilename", file.getOriginalFilename());
                    fileInfo.put("fileSize", file.getSize());
                    fileInfo.put("mimeType", file.getContentType());
                    fileInfo.put("fileFormat", FileUtils.getExtension(file));

                    // 3. 根据文件类型处理
                    String contentType = file.getContentType();

                    if (contentType != null && contentType.startsWith("image/"))
                    {
                        // 图片处理
                        String thumbnailUrl = ThumbnailUtils.generateThumbnail(file);
                        fileInfo.put("thumbnailUrl", thumbnailUrl);

                        try
                        {
                            java.awt.image.BufferedImage image = javax.imageio.ImageIO.read(file.getInputStream());
                            if (image != null)
                            {
                                String resolution = image.getWidth() + "x" + image.getHeight();
                                fileInfo.put("resolution", resolution);
                            }
                        }
                        catch (Exception e)
                        {
                            log.warn("获取图片分辨率失败", e);
                        }
                    }
                    else if (contentType != null && contentType.startsWith("video/"))
                    {
                        // 视频处理
                        try
                        {
                            String realFilePath = RuoYiConfig.getProfile() + FileUtils.stripPrefix(url);

                            // 生成视频缩略图
                            String thumbnailUrl = VideoUtils.generateVideoThumbnail(realFilePath, 1);
                            fileInfo.put("thumbnailUrl", thumbnailUrl);

                            // 获取视频信息
                            Map<String, Object> videoInfo = VideoUtils.getVideoInfo(realFilePath);
                            if (videoInfo.containsKey("durationSeconds"))
                            {
                                fileInfo.put("durationSeconds", videoInfo.get("durationSeconds"));
                            }
                            if (videoInfo.containsKey("resolution"))
                            {
                                fileInfo.put("resolution", videoInfo.get("resolution"));
                            }
                        }
                        catch (Exception e)
                        {
                            log.warn("处理视频文件失败", e);
                        }
                    }

                    fileInfoList.add(fileInfo);
                    successCount++;
                }
                catch (Exception e)
                {
                    log.error("上传文件失败: {}", file.getOriginalFilename(), e);
                    failedCount++;
                }
            }

            AjaxResult ajax = AjaxResult.success();
            ajax.put("files", fileInfoList);
            ajax.put("successCount", successCount);
            ajax.put("failedCount", failedCount);
            return ajax;
        }
        catch (Exception e)
        {
            log.error("批量上传素材文件失败", e);
            return AjaxResult.error("批量上传失败: " + e.getMessage());
        }
    }

    // ... existing code ...
}
