package com.example.demo.service;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Base64;
import java.util.List;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * 图片网格拼接服务
 * 用于将多张分镜图片拼接成一个网格布局
 * 参考Comfly项目的图片处理方式
 */
@Service
public class ImageGridService {

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

    /**
     * 将多张图片URL拼接成一个网格图片
     * 
     * @param imageUrls 图片URL列表
     * @param gridCols 网格列数，默认3列（适合6张或9张图）
     * @return Base64编码的拼接后图片
     */
    public String mergeImagesToGrid(List<String> imageUrls, int gridCols) {
        if (imageUrls == null || imageUrls.isEmpty()) {
            throw new IllegalArgumentException("图片URL列表不能为空");
        }

        try {
            int imageCount = imageUrls.size();
            // 自动计算网格布局：如果未指定列数，根据图片数量自动计算
            if (gridCols <= 0) {
                gridCols = calculateOptimalColumns(imageCount);
            }
            int gridRows = (int) Math.ceil((double) imageCount / gridCols);

            logger.info("开始拼接图片网格: 图片数量={}, 列数={}, 行数={}", imageCount, gridCols, gridRows);

            // 读取所有图片
            BufferedImage[] images = new BufferedImage[imageCount];
            int maxWidth = 512;  // 默认最小宽度，避免网格尺寸为0
            int maxHeight = 512; // 默认最小高度，避免网格尺寸为0

            for (int i = 0; i < imageCount; i++) {
                BufferedImage img = loadImageFromUrl(imageUrls.get(i));
                if (img != null) {
                    images[i] = img;
                    maxWidth = Math.max(maxWidth, img.getWidth());
                    maxHeight = Math.max(maxHeight, img.getHeight());
                } else {
                    logger.warn("无法加载图片: {}", imageUrls.get(i));
                    // 创建一个空白图片占位
                    BufferedImage placeholder = new BufferedImage(512, 512, BufferedImage.TYPE_INT_RGB);
                    Graphics2D g = placeholder.createGraphics();
                    g.setColor(java.awt.Color.WHITE);
                    g.fillRect(0, 0, 512, 512);
                    g.dispose();
                    images[i] = placeholder;
                }
            }

            // 创建网格图片，每张图片使用统一尺寸
            int cellWidth = maxWidth;
            int cellHeight = maxHeight;
            BufferedImage gridImage = new BufferedImage(
                gridCols * cellWidth,
                gridRows * cellHeight,
                BufferedImage.TYPE_INT_RGB
            );

            Graphics2D g = gridImage.createGraphics();
            g.setColor(java.awt.Color.WHITE);
            g.fillRect(0, 0, gridImage.getWidth(), gridImage.getHeight());

            // 将图片放置到网格中
            for (int i = 0; i < imageCount; i++) {
                int row = i / gridCols;
                int col = i % gridCols;
                int x = col * cellWidth;
                int y = row * cellHeight;

                BufferedImage img = images[i];
                // 如果图片尺寸不同，居中放置
                int imgX = x + (cellWidth - img.getWidth()) / 2;
                int imgY = y + (cellHeight - img.getHeight()) / 2;
                
                g.drawImage(img, imgX, imgY, null);
            }

            g.dispose();

            // 转换为Base64
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(gridImage, "PNG", baos);
            byte[] imageBytes = baos.toByteArray();
            String base64 = Base64.getEncoder().encodeToString(imageBytes);
            
            logger.info("图片网格拼接完成: 总尺寸={}x{}", gridImage.getWidth(), gridImage.getHeight());
            
            return "data:image/png;base64," + base64;

        } catch (Exception e) {
            logger.error("拼接图片网格失败", e);
            throw new RuntimeException("图片拼接失败: " + e.getMessage(), e);
        }
    }

    /**
     * 计算最优列数
     */
    private int calculateOptimalColumns(int imageCount) {
        // 根据图片数量选择最佳列数
        if (imageCount <= 2) return 2;
        if (imageCount <= 4) return 2;
        if (imageCount <= 6) return 3;
        if (imageCount <= 9) return 3;
        if (imageCount <= 12) return 4;
        return 4; // 默认4列
    }

    /**
     * 从URL加载图片
     */
    private BufferedImage loadImageFromUrl(String imageUrl) {
        try {
            // 处理base64格式的图片
            if (imageUrl.startsWith("data:image")) {
                String base64Data = imageUrl.substring(imageUrl.indexOf(",") + 1);
                byte[] imageBytes = Base64.getDecoder().decode(base64Data);
                return ImageIO.read(new java.io.ByteArrayInputStream(imageBytes));
            }
            
            // 处理普通URL
            URI uri = new URI(imageUrl);
            URL url = uri.toURL();
            return ImageIO.read(url);
        } catch (IOException | URISyntaxException e) {
            logger.error("加载图片失败: {}", imageUrl, e);
            return null;
        }
    }
}

