package com.xy.xyaicpzs.controller;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.xy.xyaicpzs.common.ErrorCode;
import com.xy.xyaicpzs.common.ResultUtils;
import com.xy.xyaicpzs.common.response.ApiResponse;
import com.xy.xyaicpzs.config.CosConfig;
import com.xy.xyaicpzs.exception.BusinessException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上传控制器
 *
 * @author xy
 */
@Tag(name = "文件上传", description = "腾讯云 COS 文件上传相关接口")
@RestController
@RequestMapping("/file")
@Slf4j
public class FileUploadController {

    @Resource
    private COSClient cosClient;

    @Resource
    private CosConfig cosConfig;

    /**
     * 上传图片到腾讯云 COS
     *
     * @param file 上传的图片文件（最大50MB）
     * @return 文件访问 URL
     */
    @Operation(summary = "上传图片", description = "上传图片到腾讯云 COS，文件名使用UUID命名，最大支持50MB")
    @PostMapping("/upload")
    public ApiResponse<Map<String, String>> uploadImage(@RequestParam("file") MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件不能为空");
        }

        try {
            // 获取原始文件名
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件名不能为空");
            }

            // 验证文件类型（仅允许图片）
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "仅支持上传图片文件");
            }

            // 获取文件扩展名
            String extension = "";
            int lastDotIndex = originalFilename.lastIndexOf(".");
            if (lastDotIndex > 0) {
                extension = originalFilename.substring(lastDotIndex);
            }

            // 使用 UUID 生成唯一文件名
            String fileName = UUID.randomUUID().toString() + extension;

            // 设置对象元数据
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(file.getSize());
            objectMetadata.setContentType(file.getContentType());

            // 创建上传请求
            PutObjectRequest putObjectRequest = new PutObjectRequest(
                    cosConfig.getBucketName(),
                    fileName,
                    file.getInputStream(),
                    objectMetadata
            );

            // 执行上传
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            log.info("图片上传成功，文件名: {}, RequestId: {}", fileName, putObjectResult.getRequestId());

            // 生成文件访问 URL
            String fileUrl = cosConfig.getDomain() + "/" + fileName;

            // 返回结果
            Map<String, String> result = new HashMap<>();
            result.put("fileName", fileName);
            result.put("fileUrl", fileUrl);
            result.put("originalFilename", originalFilename);

            return ResultUtils.success(result);

        } catch (IOException e) {
            log.error("图片上传失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "图片上传失败：" + e.getMessage());
        }
    }

    /**
     * 批量上传图片
     *
     * @param files 上传的图片文件列表（单个文件最大50MB，总请求最大100MB）
     * @return 文件访问 URL 列表
     */
    @Operation(summary = "批量上传图片", description = "批量上传多张图片到腾讯云 COS，单个文件最大50MB")
    @PostMapping("/upload/batch")
    public ApiResponse<Map<String, Object>> uploadImages(@RequestParam("files") MultipartFile[] files) {
        if (files == null || files.length == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件列表不能为空");
        }

        try {
            java.util.List<Map<String, String>> fileList = new java.util.ArrayList<>();
            int successCount = 0;
            int failCount = 0;

            for (MultipartFile file : files) {
                if (file.isEmpty()) {
                    failCount++;
                    continue;
                }

                try {
                    // 获取原始文件名
                    String originalFilename = file.getOriginalFilename();
                    if (originalFilename == null) {
                        failCount++;
                        continue;
                    }

                    // 验证文件类型（仅允许图片）
                    String contentType = file.getContentType();
                    if (contentType == null || !contentType.startsWith("image/")) {
                        log.warn("跳过非图片文件: {}", originalFilename);
                        failCount++;
                        continue;
                    }

                    // 获取文件扩展名
                    String extension = "";
                    int lastDotIndex = originalFilename.lastIndexOf(".");
                    if (lastDotIndex > 0) {
                        extension = originalFilename.substring(lastDotIndex);
                    }

                    // 使用 UUID 生成唯一文件名
                    String fileName = UUID.randomUUID().toString() + extension;

                    // 设置对象元数据
                    ObjectMetadata objectMetadata = new ObjectMetadata();
                    objectMetadata.setContentLength(file.getSize());
                    objectMetadata.setContentType(file.getContentType());

                    // 创建上传请求
                    PutObjectRequest putObjectRequest = new PutObjectRequest(
                            cosConfig.getBucketName(),
                            fileName,
                            file.getInputStream(),
                            objectMetadata
                    );

                    // 执行上传
                    PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
                    log.info("图片上传成功，文件名: {}, RequestId: {}", fileName, putObjectResult.getRequestId());

                    // 生成文件访问 URL
                    String fileUrl = cosConfig.getDomain() + "/" + fileName;

                    // 添加到结果列表
                    Map<String, String> fileInfo = new HashMap<>();
                    fileInfo.put("fileName", fileName);
                    fileInfo.put("fileUrl", fileUrl);
                    fileInfo.put("originalFilename", originalFilename);
                    fileList.add(fileInfo);

                    successCount++;

                } catch (Exception e) {
                    log.error("单个图片上传失败：{}", file.getOriginalFilename(), e);
                    failCount++;
                }
            }

            // 返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("fileList", fileList);
            result.put("total", files.length);
            result.put("successCount", successCount);
            result.put("failCount", failCount);

            return ResultUtils.success(result);

        } catch (Exception e) {
            log.error("批量图片上传失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "批量图片上传失败：" + e.getMessage());
        }
    }
}
