package com.gic.haoban.manage.service.context.combined;

import com.gic.haoban.manage.api.qdto.combined.CombinedQDTO;
import com.gic.haoban.manage.service.context.chat.BusinessManager;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.net.URL;
import java.util.concurrent.TimeUnit;

/**
 * Created by wangzubo on 2024/10/27.
 */
public class ImageCombined {

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

    private static final Cache<String, BufferedImage> imageCache = Caffeine.newBuilder()
            .maximumWeight(100 * 1024 * 1024) // 100MB
            .weigher((String key, BufferedImage image) -> image.getWidth() * image.getHeight() / 4)
            .expireAfterAccess(30, TimeUnit.MINUTES) // 可设置失效时间
            .build();

    public static final String IMAGE_REDIS_KEY = "haoban-manage3-service:combined_image:";

    private static final int MAX_HEIGHT_NO_WHITE_SPACE = 1500;
    private static final int MAX_HEIGHT_WITH_WHITE_SPACE = 1340;
    private static final int MIN_WIDTH = 500;
    private static final int WHITE_SPACE_HEIGHT = 160;
    private static final int QR_WIDTH_REFERENCE = 136;


    private static final String LARGE_IMAGE_URL = "https://jhdmyx-1251519181.cos.ap-shanghai.myqcloud.com/image/material_content-2e81265ed1bf4c4d8a623d6b04942767.jpeg?imageView2/2/w/1080/h/10800/format/jpg";
    private static final String QR_CODE_URL = "https://gicinner-1251519181.cos.ap-shanghai.myqcloud.com/image/material_content-4ffc77073ca1476fb264bf1be9f11383.png";
    private static final String STORE_NAME = "门店CCA";
    private static final String GUIDE_NAME = "宇智222为您推荐";
    private static final String OUTPUT_PATH = "/Users/wang/Downloads/output_image3.jpg";
    public static void main(String[] args) throws Exception{
        BufferedImage largeImage = loadImageWithCache(LARGE_IMAGE_URL);
        BufferedImage qrCodeImage = ImageIO.read(new URL(QR_CODE_URL));

        int showStyle = 0;

        BufferedImage combinedImage = generateImage(largeImage, qrCodeImage, showStyle,STORE_NAME, GUIDE_NAME);
        ImageIO.write(combinedImage, "jpg", new File(OUTPUT_PATH));
    }

    public static byte[] getCombinedImage(CombinedQDTO combinedQDTO) throws Exception{
        String imageUrl = combinedQDTO.getImageUrl();
        String qrCodeUrl = combinedQDTO.getQrCodeUrl();
        Integer showStyle = combinedQDTO.getShowStyle();
        String lineOne = combinedQDTO.getLineOne();
        String lineTwo = combinedQDTO.getLineTwo();
        if(imageUrl.contains("?")) {
            logger.info("url有参数={}",imageUrl);
            imageUrl = imageUrl.split("\\?")[0] ;
        }
        //压缩图片的参数
        imageUrl = imageUrl + "?imageView2/2/w/1080/h/10800/format/jpg";
        BufferedImage largeImage = loadImageWithCache(imageUrl);
        BufferedImage qrCodeImage = ImageIO.read(new URL(qrCodeUrl));
        if (largeImage == null || qrCodeImage == null) {
            return null;
        }
        BufferedImage combinedImage = generateImage(largeImage, qrCodeImage, showStyle, lineOne, lineTwo);

        ImageIO.write(combinedImage, "jpg", new File(OUTPUT_PATH));
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            ImageIO.write(combinedImage, "jpg", baos);
            // 返回字节数组
            return baos.toByteArray();
        }
    }

    /**
     * 从缓存中加载图像
     */
    private static BufferedImage loadImageWithCache(String url) {
        return imageCache.get(url, key -> {
            try {
                logger.info("加载图片buffered");
                return ImageIO.read(new URL(key));
            } catch (Exception e) {
                logger.info("获取图片异常",e);
                return null;
            }
        });
    }

    private static BufferedImage generateImage(BufferedImage image, BufferedImage qrCode, int showStyle,String lineOne,String lineTwo) throws Exception {
        int width = image.getWidth();
        int height = image.getHeight();

        if (showStyle == 1) {
            if (height > MAX_HEIGHT_NO_WHITE_SPACE) {
                width = width * MAX_HEIGHT_NO_WHITE_SPACE / height;
                height = MAX_HEIGHT_NO_WHITE_SPACE;
            }
        } else {
            if (height > MAX_HEIGHT_WITH_WHITE_SPACE) {
                width = width * MAX_HEIGHT_WITH_WHITE_SPACE / height;
                height = MAX_HEIGHT_WITH_WHITE_SPACE;
            }
            width = Math.max(width, MIN_WIDTH);
        }

        BufferedImage resizedImage = Thumbnails.of(image).size(width, height).asBufferedImage();
        int finalHeight = height + (showStyle == 1 ? 0 : WHITE_SPACE_HEIGHT);
        BufferedImage combinedImage = new BufferedImage(width, finalHeight, BufferedImage.TYPE_INT_RGB);

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

        int qrWidth = width * QR_WIDTH_REFERENCE / 750;
        if (width <= MIN_WIDTH) {
            qrWidth = 136;
        }
        BufferedImage resizedQRCode = Thumbnails.of(qrCode).size(qrWidth, qrWidth).asBufferedImage();

        if (showStyle == 1) {
            // 不需要留白时，QR码距离底部20px
            g.drawImage(resizedQRCode, width - qrWidth - 20, finalHeight - qrWidth - 20, null);
        } else {
            // 需要留白时
            addWhiteSpace(g, width, finalHeight, resizedQRCode, qrWidth, lineOne, lineTwo);
        }

        g.dispose();
        return combinedImage;
    }

    private static void addWhiteSpace(Graphics2D g, int width, int finalHeight, BufferedImage qrCode, int qrWidth,String lineOne,String lineTwo) {
        // 添加白色背景
        g.setColor(Color.WHITE);
        g.fillRect(0, finalHeight - WHITE_SPACE_HEIGHT, width, WHITE_SPACE_HEIGHT);

        // 添加门店名称，距底部88px
        g.setColor(new Color(36, 40, 53));
        g.setFont(new Font("Arial", Font.PLAIN, 30));
        g.drawString(lineOne, 30, finalHeight - WHITE_SPACE_HEIGHT + 72);

        // 添加推荐人信息，距底部40px
        g.setColor(new Color(151, 155, 165));
        g.setFont(new Font("Arial", Font.PLAIN, 26));
        g.drawString(lineTwo, 30, finalHeight - WHITE_SPACE_HEIGHT + 120);

        // 添加二维码，距底部12px
        int qrBottomPadding = 12;
        g.drawImage(qrCode, width - qrWidth - qrBottomPadding, finalHeight - qrWidth - qrBottomPadding, null);
    }

}
