package com.tourism.common.huaweicloud.obs.util;

import com.obs.services.ObsClient;
import com.obs.services.model.PutObjectResult;
import com.tourism.common.huaweicloud.obs.config.HuaweicloudObsProperties;
import jakarta.annotation.PostConstruct;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.List;

@Service
public class MergeAvatarsFlexUtils {

    private final HuaweicloudObsProperties huaweicloudObsProperties;
    private final ObsClient client;

    public MergeAvatarsFlexUtils(HuaweicloudObsProperties properties, HuaweicloudObsProperties huaweicloudObsProperties, ObsClient client) {
        super();
        this.huaweicloudObsProperties = huaweicloudObsProperties;
        this.client = client;
    }
    /**
     * 合并用户头像
     *
     * @param avatarUrls 用户头像 URL 列表
     * @return 合成后的 BufferedImage
     * @throws Exception 异常处理
     */
    private BufferedImage mergeAvatars(List<String> avatarUrls) throws Exception {
        int avatarCount = avatarUrls.size();
        int avatarSize = 100; // 单个头像的大小
        int padding = 1;     // 间距

        // 动态计算行列数
        int rows = calculateRows(avatarCount);
        int cols = calculateCols(avatarCount, rows);

        // 画布大小
        int canvasWidth = cols * (avatarSize + padding) - padding;
        int canvasHeight = rows * (avatarSize + padding) - padding;

        // 创建画布
        BufferedImage canvas = new BufferedImage(canvasWidth, canvasHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = canvas.createGraphics();

        // 设置抗锯齿
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // 下载头像并绘制
        for (int i = 0; i < avatarCount; i++) {
            int row = i / cols;
            int col = i % cols;

            // 根据布局进行位置调整
            int x = col * (avatarSize + padding);
            int y = row * (avatarSize + padding);

            // 对于特殊布局（例如3个头像需要调整位置），在此处做调整
            if (avatarCount == 3) {
                if (i == 0) {
                    // 第1个头像居中
                    x = (canvasWidth - avatarSize) / 2;
                    y = 0;
                } else {
                    // 第2个和第3个头像排在第二行
                    x = col * (avatarSize + padding);
                    y = avatarSize + padding;
                }
            }
            // 处理不同数量的头像
            if (avatarCount == 5) {
                if (i == 0 || i == 1) {
                    // 上排2个头像，水平居中
                    x = (canvasWidth / 2 - avatarSize) + (i * (avatarSize + padding)); // x在中心偏移
                    y = 0;
                } else {
                    // 下排3个头像
                    x = col * (avatarSize + padding);
                    y = avatarSize + padding;
                }
            }

            if (avatarCount == 7) {
                if (i == 0) {
                    // 第1个头像居中
                    x = (canvasWidth - avatarSize) / 2;
                    y = 0;
                } else if (i < 4) {
                    // 中间3个头像
                    x = col * (avatarSize + padding);
                    y = avatarSize + padding;
                } else {
                    // 下3个头像
                    x = col * (avatarSize + padding);
                    y = 2 * (avatarSize + padding);
                }
            }

            if (avatarCount == 8) {
                if (i == 0 || i == 1) {
                    // 上排2个头像，居中
                    x = (canvasWidth / 2 - avatarSize) + (i * (avatarSize + padding)); // x在中心偏移
                    y = 0;
                } else if (i < 5) {
                    // 中排3个头像
                    x = col * (avatarSize + padding);
                    y = avatarSize + padding;
                } else {
                    // 下排3个头像
                    x = col * (avatarSize + padding);
                    y = 2 * (avatarSize + padding);
                }
            }
//            if (avatarCount == 7) {
//                if (i == 0) {
//                    x = (canvasWidth - avatarSize) / 2;  // 上面1个头像居中
//                    y = 0;
//                } else if (i < 4) {
//                    x = col * (avatarSize + padding);   // 中间3个头像排
//                    y = avatarSize + padding;
//                } else {
//                    x = col * (avatarSize + padding);   // 下面3个头像排
//                    y = 2 * (avatarSize + padding);
//                }
//            }
            // 下载头像
            BufferedImage avatar = downloadImage(avatarUrls.get(i));

            // 缩放头像到指定大小
            BufferedImage resizedAvatar = resizeImage(avatar, avatarSize, avatarSize);

            // 绘制到画布
            g.drawImage(resizedAvatar, x, y, null);
        }

        g.dispose();
        return canvas;
    }

    /**
     * 计算行数
     */
    private int calculateRows(int avatarCount) {
        if (avatarCount == 1) return 1;  // 1个头像，居中
        if (avatarCount == 2) return 1;  // 2个头像，横向排布
        if (avatarCount == 3 || avatarCount == 4) return 2;  // 3-4个头像，2行布局
        if (avatarCount == 5 || avatarCount == 6) return 2;  // 5-6个头像，2行布局
        if (avatarCount == 7 || avatarCount == 8) return 3;  // 7-8个头像，3行布局
        if (avatarCount == 9) return 3;  // 9个头像，每排3个
        return 3;  // 默认3行
    }

    /**
     * 计算列数
     */
    private int calculateCols(int avatarCount, int rows) {
        if (avatarCount == 1) return 1;  // 1个头像
        if (avatarCount == 2) return 2;  // 2个头像
        if (avatarCount == 3) return 2;  // 3个头像，上排1个，下面2个
        if (avatarCount == 4) return 2;  // 4个头像，2行2列
        if (avatarCount == 5) return 3;  // 5个头像，上2下3
        if (avatarCount == 6) return 3;  // 6个头像，3行2列
        if (avatarCount == 7) return 3;  // 7个头像，上1下3再下3
        if (avatarCount == 8) return 3;  // 8个头像，上2下3再下3
        if (avatarCount == 9) return 3;  // 9个头像，3排3列
        return 3;  // 默认3列
    }

    /**
     * 下载图片
     */
    private BufferedImage downloadImage(String url) throws Exception {
        try (InputStream input = new URL(url).openStream()) {
            return ImageIO.read(input);
        }
    }

    /**
     * 缩放图片
     */
    private BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) {
        Image scaledImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_SMOOTH);
        BufferedImage resizedImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_ARGB);

        Graphics2D g = resizedImage.createGraphics();
        g.drawImage(scaledImage, 0, 0, null);
        g.dispose();

        return resizedImage;
    }

    /**
     * 合并用户头像并上传到华为云
     *
     * @param avatarUrls 用户头像 URL 列表
     * @return 上传后的图片 URL
     * @throws Exception 异常处理
     */
    public String mergeAndUploadAvatars(String hostIpPort,List<String> avatarUrls) throws Exception {
        //设定最多为九张图片的组合
        if(CollectionUtils.isNotEmpty(avatarUrls) && avatarUrls.size() > 9){
            avatarUrls = avatarUrls.subList(0,9);
        }
        // 1. 合成图片
        BufferedImage mergedImage = mergeAvatars(avatarUrls);

        // 2. 将图片上传到华为云
        String fileName = "merged_avatar_" + System.currentTimeMillis() + ".png";
        String uploadedUrl = uploadToHuaweiCloud(mergedImage, fileName);
        String imageUrlAfterConvert =
                hostIpPort + "/" + uploadedUrl;
        return imageUrlAfterConvert;
    }

    /**
     * 上传图片到华为云
     *
     * @param image    BufferedImage 图片
     * @param fileName 上传到华为云的文件名
     * @return 上传后的图片 URL
     * @throws Exception 异常处理
     */
    private String uploadToHuaweiCloud(BufferedImage image, String fileName) throws Exception {
        // 将 BufferedImage 转为 InputStream
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(image, "png", os);
        InputStream inputStream = new ByteArrayInputStream(os.toByteArray());

        // 初始化华为云 OBS 客户端
        ObsClient obsClient = new ObsClient(huaweicloudObsProperties.getAccessKey(), huaweicloudObsProperties.getSecretKey(), huaweicloudObsProperties.getEndpoint());

        // 设置文件上传的路径（包括文件夹和文件名）
        String filePath = "images/avatars/" + fileName;

        // 上传文件
        PutObjectResult result = obsClient.putObject(huaweicloudObsProperties.getBucketName(), filePath, inputStream);

        // 返回文件 URL
//        String fileUrl = String.format("%s/%s/%s", huaweicloudObsProperties.getEndpoint(), huaweicloudObsProperties.getBucketName(), filePath);
        // 关闭客户端
        obsClient.close();

        return filePath;
    }
//    public static void main(String[] args) throws Exception {
//        // 示例用户头像 URL 列表
//        List<String> avatarUrls = List.of(
//                "https://v.xiaoyaotravel.com/image/TourismProjectTravelNotesWrite/tourismTavelNotesUrl/c5e3a8db6aac497bbe27d3e7e694078a.jpg",
//                "https://v.xiaoyaotravel.com/image/TourismProjectTravelNotesWrite/tourismTavelNotesUrl/aa64bf5ac7a84d7eb6492513c752b9c8.jpg",
//                "https://v.xiaoyaotravel.com/image/TourismProjectTravelNotesWrite/tourismTavelNotesUrl/f22b02713d8a4732a20366e8b9368986.jpg"
//        );
//
//        // 调用合成并上传方法
//        String resultUrl = mergeAndUploadAvatars(applicationConfig.getHostIpPort(),avatarUrls);
//        System.out.println("合成图片上传成功，访问链接：" + resultUrl);
//    }
}