      package com.example.demo.controller;

import com.example.demo.service.ImageGridService;
import com.example.demo.service.CosService;
import com.example.demo.util.JwtUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.*;

/**
 * 图片拼接API控制器
 * 用于将多张图片拼接成网格图
 */
@RestController
@RequestMapping("/api/image-grid")
@CrossOrigin(origins = "*", maxAge = 3600)
public class ImageGridApiController {

    private static final Logger logger = LoggerFactory.getLogger(ImageGridApiController.class);

    @Autowired
    private ImageGridService imageGridService;

    @Autowired
    private CosService cosService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 拼接多张图片为六宫格（2×3）
     * 接收多张图片文件或Base64字符串，返回拼接后的Base64图片
     */
    @PostMapping("/merge")
    public ResponseEntity<Map<String, Object>> mergeImages(
            @RequestParam(value = "images", required = false) MultipartFile[] imageFiles,
            @RequestBody(required = false) Map<String, Object> requestBody,
            @RequestHeader(value = "Authorization", required = false) String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 验证用户身份
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录或token无效");
                logger.warn("图片拼接API调用失败: token无效");
                return ResponseEntity.status(401).body(response);
            }
            
            logger.info("图片拼接API调用: username={}", username);
            List<String> imageBase64List = new ArrayList<>();
            
            // 处理文件上传形式
            if (imageFiles != null && imageFiles.length > 0) {
                logger.info("收到 {} 张图片文件进行拼接", imageFiles.length);
                
                for (MultipartFile file : imageFiles) {
                    if (file.isEmpty()) {
                        continue;
                    }
                    
                    // 转换为Base64
                    byte[] bytes = file.getBytes();
                    String base64 = Base64.getEncoder().encodeToString(bytes);
                    String contentType = file.getContentType();
                    if (contentType == null) {
                        contentType = "image/jpeg";
                    }
                    imageBase64List.add("data:" + contentType + ";base64," + base64);
                }
            }
            // 处理JSON Body形式（Base64数组）
            else if (requestBody != null && requestBody.containsKey("images")) {
                @SuppressWarnings("unchecked")
                List<String> images = (List<String>) requestBody.get("images");
                logger.info("收到 {} 张Base64图片进行拼接", images.size());
                imageBase64List.addAll(images);
            }
            
            // 验证图片数量
            if (imageBase64List.isEmpty()) {
                response.put("success", false);
                response.put("message", "未提供图片");
                return ResponseEntity.badRequest().body(response);
            }
            
            if (imageBase64List.size() > 6) {
                logger.warn("图片数量超过6张，只取前6张: {}", imageBase64List.size());
                imageBase64List = imageBase64List.subList(0, 6);
            }
            
            // 确定网格列数
            int cols = 3; // 默认3列（2×3六宫格）
            if (requestBody != null && requestBody.containsKey("cols")) {
                cols = (int) requestBody.get("cols");
            }
            
            logger.info("开始拼接图片: 数量={}, 列数={}", imageBase64List.size(), cols);
            
            // 调用拼接服务
            String mergedImage = imageGridService.mergeImagesToGrid(imageBase64List, cols);
            
            logger.info("图片拼接成功，返回Base64长度: {}", mergedImage.length());
            
            // 上传到COS对象存储
            String cosUrl = null;
            if (cosService.isEnabled()) {
                logger.debug("======== 开始上传图片到COS ========");
                logger.debug("COS服务已启用，准备上传压缩后的图片");
                try {
                    long startTime = System.currentTimeMillis();
                    cosUrl = cosService.uploadBase64Image(mergedImage, null);
                    long endTime = System.currentTimeMillis();
                    
                    if (cosUrl != null) {
                        logger.info("======== COS上传成功 ========");
                        logger.info("公网访问链接: {}", cosUrl);
                        logger.info("上传耗时: {} ms", (endTime - startTime));
                        logger.info("================================");
                    } else {
                        logger.warn("COS上传返回空URL");
                    }
                } catch (Exception e) {
                    logger.error("上传图片到COS失败: {}", e.getMessage(), e);
                    logger.warn("继续返回Base64数据");
                }
            } else {
                logger.debug("COS服务未启用，跳过上传");
            }
            
            response.put("success", true);
            response.put("message", "图片拼接成功");
            
            // 构建返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("mergedImage", mergedImage);
            data.put("imageCount", imageBase64List.size());
            data.put("cols", cols);
            if (cosUrl != null) {
                data.put("cosUrl", cosUrl);  // 返回COS链接
            }
            response.put("data", data);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("图片拼接失败", e);
            response.put("success", false);
            response.put("message", "图片拼接失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 从Token中提取用户名
     */
    private String extractUsernameFromToken(String token) {
        try {
            if (token == null || !token.startsWith("Bearer ")) {
                return null;
            }
            
            // 提取实际的token
            String actualToken = jwtUtils.extractTokenFromHeader(token);
            if (actualToken == null) {
                return null;
            }
            
            // 验证token并获取用户名
            String username = jwtUtils.getUsernameFromToken(actualToken);
            if (username != null && !jwtUtils.isTokenExpired(actualToken)) {
                return username;
            }
            
            return null;
        } catch (Exception e) {
            logger.error("解析token失败", e);
            return null;
        }
    }
}
