package com.ruoyi.database.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.client.j2se.MatrixToImageWriter;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

public class QRCodeGenerator {

    /**
     * 生成二维码并保存到本地
     * @param content 二维码内容
     * @param width 宽度
     * @param height 高度
     * @param filePath 保存路径
     */
    public static void generateQRCode(String content, int width, int height, String filePath) {
        try {
            // 设置二维码参数
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            hints.put(EncodeHintType.MARGIN, 1); // 设置白边

            // 生成二维码矩阵
            BitMatrix bitMatrix = new MultiFormatWriter().encode(
                    content,
                    BarcodeFormat.QR_CODE,
                    width,
                    height,
                    hints
            );

            // 方法1：使用MatrixToImageWriter直接保存（最简单）
            String format = filePath.substring(filePath.lastIndexOf(".") + 1);
            MatrixToImageWriter.writeToPath(bitMatrix, format, Paths.get(filePath));

            System.out.println("二维码已保存到: " + new File(filePath).getAbsolutePath());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成带logo的二维码
     */
    public static void generateQRCodeWithLogo(String content, int width, int height,
                                              String filePath, String logoPath) {
        try {
            // 1. 生成基础二维码
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            hints.put(EncodeHintType.MARGIN, 1);

            BitMatrix bitMatrix = new MultiFormatWriter().encode(
                    content, BarcodeFormat.QR_CODE, width, height, hints);

            // 2. 转换为BufferedImage
            BufferedImage qrImage = MatrixToImageWriter.toBufferedImage(bitMatrix);

            // 3. 添加logo
            if (logoPath != null && new File(logoPath).exists()) {
                BufferedImage logoImage = ImageIO.read(new File(logoPath));
                qrImage = addLogo(qrImage, logoImage);
            }

            // 4. 保存图片
            String format = filePath.substring(filePath.lastIndexOf(".") + 1);
            ImageIO.write(qrImage, format, new File(filePath));

            System.out.println("带Logo的二维码已保存到: " + new File(filePath).getAbsolutePath());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 添加Logo到二维码中心
     */
    private static BufferedImage addLogo(BufferedImage qrImage, BufferedImage logoImage) {
        // 计算logo尺寸（二维码的1/5）
        int logoWidth = logoImage.getWidth() > qrImage.getWidth() * 2 / 10 ?
                qrImage.getWidth() * 2 / 10 : logoImage.getWidth();
        int logoHeight = logoImage.getHeight() > qrImage.getHeight() * 2 / 10 ?
                qrImage.getHeight() * 2 / 10 : logoImage.getHeight();

        // 缩放logo
        BufferedImage scaledLogo = new BufferedImage(logoWidth, logoHeight, BufferedImage.TYPE_INT_ARGB);
        scaledLogo.getGraphics().drawImage(logoImage.getScaledInstance(logoWidth, logoHeight,
                java.awt.Image.SCALE_SMOOTH), 0, 0, null);

        // 计算logo位置（居中）
        int x = (qrImage.getWidth() - logoWidth) / 2;
        int y = (qrImage.getHeight() - logoHeight) / 2;

        // 将logo绘制到二维码上
        qrImage.getGraphics().drawImage(scaledLogo, x, y, null);

        return qrImage;
    }

    /**
     * 根据您提供的坐标数据生成二维码
     */
    public static void generateFromCoordinates(String filePath) {
        try {
            // 假设这是您的坐标数据
            String[] coordinates = {
                    "10:1",
                    "11:1",
                    "12:1"
                    // 这里应该包含完整的坐标数据
            };

            // 解析坐标数据
            int size = 1080; // 二维码尺寸
            BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);

            // 白色背景
            for (int x = 0; x < size; x++) {
                for (int y = 0; y < size; y++) {
                    image.setRGB(x, y, 0xFFFFFF); // 白色
                }
            }

            // 根据坐标绘制黑色模块
            for (String coord : coordinates) {
                String[] parts = coord.split(":");
                if (parts.length == 2) {
                    int row = Integer.parseInt(parts[0].trim());
                    int col = Integer.parseInt(parts[1].trim());
                    if (row < size && col < size) {
                        image.setRGB(col, row, 0x000000); // 黑色
                    }
                }
            }

            // 保存图片
            ImageIO.write(image, "PNG", new File(filePath));
            System.out.println("根据坐标生成的二维码已保存到: " + new File(filePath).getAbsolutePath());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        // 示例1：生成普通二维码
        String content = "C:\\Users\\28758\\Desktop\\222.png";
        String filePath = "C:\\Users\\28758\\Desktop\\666.png";

        // 生成二维码
        generateQRCode(content, 1080, 640, filePath);

        // 示例2：生成带logo的二维码
        String logoPath = "C:\\Users\\28758\\Desktop\\222.png";
        String qrWithLogoPath = "C:\\Users\\28758\\Desktop\\777.png";
        generateQRCodeWithLogo(content, 1080, 640, qrWithLogoPath, logoPath);

    }
}
