package com.ruoyi.database.util;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class QRCodeGenerator1080x640 {



        public static void generateHighQualityQRCode(String content, String filePath) throws Exception {
            Map<EncodeHintType, Object> hints = new HashMap<>();

            // === 关键参数配置 ===
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            hints.put(EncodeHintType.MARGIN, 4);                    // 边距
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 高容错
            hints.put(EncodeHintType.QR_VERSION, 10);               // 版本

            // 生成大小根据内容动态调整
            int qrSize = 500; // 固定大小，确保清晰度

            QRCodeWriter writer = new QRCodeWriter();
            BitMatrix matrix = writer.encode(content, BarcodeFormat.QR_CODE, qrSize, qrSize, hints);

            // === 提高图像质量 ===
            int scale = 4; // 缩放因子，提高分辨率
            BufferedImage qrImage = new BufferedImage(
                    qrSize * scale,
                    qrSize * scale,
                    BufferedImage.TYPE_INT_RGB
            );

            Graphics2D g = qrImage.createGraphics();
            g.setColor(Color.WHITE);
            g.fillRect(0, 0, qrSize * scale, qrSize * scale);
            g.setColor(Color.BLACK);

            // 绘制高分辨率二维码
            for (int x = 0; x < qrSize; x++) {
                for (int y = 0; y < qrSize; y++) {
                    if (matrix.get(x, y)) {
                        g.fillRect(x * scale, y * scale, scale, scale);
                    }
                }
            }
            g.dispose();

            // === 创建1080x640画布 ===
            BufferedImage finalImage = new BufferedImage(1080, 640, BufferedImage.TYPE_INT_RGB);
            Graphics2D finalG = finalImage.createGraphics();
            finalG.setColor(Color.WHITE);
            finalG.fillRect(0, 0, 1080, 640);

            // 居中放置
            int x = (1080 - qrImage.getWidth()) / 2;
            int y = (640 - qrImage.getHeight()) / 2;
            finalG.drawImage(qrImage, x, y, null);
            finalG.dispose();

            // 保存
            ImageIO.write(finalImage, "PNG", new File(filePath));
        }

        /**
         * 简单的调试工具：检查二维码内容
         */
        public static void testQRCode(String filePath) {
            try {
                System.out.println("=== 二维码生成配置 ===");
                System.out.println("1. 确保二维码核心部分是正方形");
                System.out.println("2. 有足够的边距（margin >= 2）");
                System.out.println("3. 使用高容错等级（ErrorCorrectionLevel.H）");
                System.out.println("4. 像素点清晰，无模糊");
                System.out.println("5. 背景纯白，前景纯黑（对比度高）");

                // 加载并检查图像
                BufferedImage img = ImageIO.read(new File(filePath));
                System.out.println("\n图像信息：");
                System.out.println("尺寸: " + img.getWidth() + "x" + img.getHeight());
                System.out.println("类型: " + img.getType());

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


//    public static void main(String[] args) {
//        String simpleContent = "https://tingche.csckl.com"; // 先用简单内容测试
//
//        // 方法1：直接生成正方形（先确保能扫描）
//        Map<EncodeHintType, Object> hints = new HashMap<>();
//        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
//        hints.put(EncodeHintType.MARGIN, 4);
//
//        QRCodeWriter writer = new QRCodeWriter();
//        BitMatrix matrix = null;
//        try {
//            matrix = writer.encode(simpleContent, BarcodeFormat.QR_CODE, 600, 1024, hints);
//            // 直接保存正方形二维码
//            File squareFile = new File("C:\\Users\\28758\\Desktop\\test_square.jpg");
//            MatrixToImageWriter.writeToPath(matrix, "JPG", squareFile.toPath());
//
//            System.out.println("请先扫描 test_square.png");
//            System.out.println("如果能扫描，再尝试矩形版本");
//        } catch (WriterException e) {
//            throw new RuntimeException(e);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//
//
//    }


//        public static void main(String[] args) {
//            int width = 600;
//            int height = 1024;
//            String outputPath = "hikvision_control.jpg";
//
//            try {
//                createHikvisionImage(width, height, outputPath);
//                System.out.println("图片生成成功: " + outputPath);
//            } catch (IOException e) {
//                System.err.println("图片生成失败: " + e.getMessage());
//            }
//        }

        public static void createHikvisionImage(int width, int height, String outputPath) throws IOException {
            // 创建BufferedImage对象
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

            // 获取Graphics2D对象
            Graphics2D g2d = image.createGraphics();

            // 设置渲染质量
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            // 设置蓝色背景（海康常用蓝色）
            Color hikBlue = new Color(0, 123, 184); // 海康威视标准蓝色
            g2d.setColor(hikBlue);
            g2d.fillRect(0, 0, width, height);

            // 可选：添加文字或logo
            addHikvisionText(g2d, width, height);

            // 释放资源
            g2d.dispose();

            // 保存图片
            ImageIO.write(image, "jpg", new File(outputPath));
        }

        private static void addHikvisionText(Graphics2D g2d, int width, int height) {
            // 设置文字颜色为白色
//            g2d.setColor(Color.WHITE);

            // 设置字体
            Font font = new Font("Microsoft YaHei", Font.BOLD, 48);
            g2d.setFont(font);

            // 计算文字位置使其居中
            String text = "出入口控制";
            FontMetrics fm = g2d.getFontMetrics();
            int textWidth = fm.stringWidth(text);
            int textHeight = fm.getHeight();

            int x = (width - textWidth) / 2;
            int y = (height - textHeight) / 2 + fm.getAscent();

            // 绘制文字
//            g2d.drawString(text, x, y);

            // 添加副标题
            Font subFont = new Font("Microsoft YaHei", Font.PLAIN, 24);
            g2d.setFont(subFont);

            String subText = "海康威视 HIKVISION";
            FontMetrics subFm = g2d.getFontMetrics();
//            int subTextWidth = subFm.stringWidth(subText);

//            int subX = (width - subTextWidth) / 2;
            int subY = y + 80;

//            g2d.drawString(subText, subX, subY);
        }





        public static void main(String[] args) {
            try {
                createSimpleParkingQR(
                        "请扫码缴费",
                        "https://tingche.csckl.com/wisdomPark/doc.html",
                        "simple_qr.jpg"
                );
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public static void createSimpleParkingQR(String text, String qrUrl, String outputPath) throws Exception {
            int width = 600;
            int height = 1024;

            // 创建主图像
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = image.createGraphics();

            // 设置背景色
            g.setColor(new Color(0, 123, 184));
            g.fillRect(0, 0, width, height);

            // 绘制文字
            g.setColor(Color.WHITE);
            g.setFont(new Font("宋体", Font.BOLD, 50));
            FontMetrics fm = g.getFontMetrics();
            int textWidth = fm.stringWidth(text);
            g.drawString(text, (width - textWidth) / 2, 200);

            // 生成二维码
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bitMatrix = qrCodeWriter.encode(qrUrl, BarcodeFormat.QR_CODE, 400, 400);

            BufferedImage qrImage = MatrixToImageWriter.toBufferedImage(bitMatrix);

            // 绘制二维码
            g.drawImage(qrImage, (width - 400) / 2, 300, null);

            // 保存
            ImageIO.write(image, "JPG", new File(outputPath));
            g.dispose();
        }

    }

