package com.fuyuanshen.equipment.utils.c;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class TextToDotMatrix {

    public static void main(String[] args) {
        String text = "现场危险，停止救援，\n紧急撤离至安全区域！";
        int width = 160;    // 点阵宽度
        int height = 80;    // 点阵高度

        try {
            // 1. 创建点阵图片
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY);
            Graphics2D g = image.createGraphics();

            // 设置背景为白色
            g.setColor(Color.WHITE);
            g.fillRect(0, 0, width, height);

            // 设置字体并居中显示文本
            g.setColor(Color.BLACK);
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

            // 自动调整字体大小以适应区域
            Font font = findBestFitFont(text, width, height, g);
            g.setFont(font);

            // 计算文本位置并绘制
            drawCenteredText(g, text, width, height);
            g.dispose();

            // 2. 生成二进制数组
            List<Byte> byteList = new ArrayList<>();
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x += 8) {
                    byte b = 0;
                    for (int bit = 0; bit < 8; bit++) {
                        int xPos = x + bit;
                        if (xPos < width) {
                            int rgb = image.getRGB(xPos, y) & 0xFFFFFF;
                            if (rgb != 0xFFFFFF) { // 黑色像素
                                b |= (1 << (7 - bit));
                            }
                        }
                    }
                    byteList.add(b);
                }
            }

            // 转换为字节数组
            byte[] dotMatrixData = new byte[byteList.size()];
            for (int i = 0; i < byteList.size(); i++) {
                dotMatrixData[i] = byteList.get(i);
            }

            // 3. 保存预览图片
            ImageIO.write(image, "png", new File("warning_display.png"));
            System.out.println("预览图片已生成: warning_display.png");

            // 4. 打印点阵数据信息
            System.out.println("\n点阵数据信息:");
            System.out.println("尺寸: " + width + "x" + height + " 像素");
            System.out.println("数据大小: " + dotMatrixData.length + " 字节");
            System.out.println("每行字节数: " + (width / 8));
            System.out.println("总行数: " + height);

            // 5. 打印二进制数组（十六进制格式）
            System.out.println("\n点阵数据字节数组 (HEX):");
            System.out.print("byte[] dotMatrixData = {");
            for (int i = 0; i < dotMatrixData.length; i++) {
                System.out.printf("0x%02X", dotMatrixData[i] & 0xFF);
                if (i < dotMatrixData.length - 1) System.out.print(", ");
                if (i % 16 == 15) System.out.println();
            }
            System.out.println("};\n");

            // 6. 打印点阵图预览
            System.out.println("点阵图预览 (缩小版):");
            printTextPreview(image);

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

    // 自动寻找最佳字体大小
    private static Font findBestFitFont(String text, int width, int height, Graphics2D g) {
        int fontSize = 20; // 初始字体大小
        Font bestFont = null;
        int bestHeight = 0;

        while (fontSize > 8) {
            Font font = new Font("黑体", Font.BOLD, fontSize);
            g.setFont(font);
            FontMetrics metrics = g.getFontMetrics();

            // 计算文本所需高度
            String[] lines = text.split("\n");
            int textHeight = metrics.getHeight() * lines.length;

            // 检查是否超出高度
            if (textHeight < height * 0.8) {
                bestFont = font;
                bestHeight = textHeight;
                break;
            }
            fontSize--;
        }

        // 如果没有找到合适字体，使用最小字体
        if (bestFont == null) {
            bestFont = new Font("黑体", Font.BOLD, 8);
        }

        System.out.println("使用字体: " + bestFont.getSize() + "pt");
        return bestFont;
    }

    // 居中绘制文本
    private static void drawCenteredText(Graphics g, String text, int width, int height) {
        FontMetrics metrics = g.getFontMetrics();
        String[] lines = text.split("\n");

        // 计算总文本高度
        int totalHeight = metrics.getHeight() * lines.length;

        // 计算起始Y位置
        int y = (height - totalHeight) / 2 + metrics.getAscent();

        for (String line : lines) {
            // 计算X位置使文本居中
            int x = (width - metrics.stringWidth(line)) / 2;
            g.drawString(line, x, y);
            y += metrics.getHeight();
        }
    }

    // 打印文本预览
    private static void printTextPreview(BufferedImage image) {
        int width = image.getWidth();
        int height = image.getHeight();

        // 缩小预览比例
        int scale = 4;
        int previewWidth = width / scale;
        int previewHeight = height / scale;

        for (int y = 0; y < previewHeight; y++) {
            for (int x = 0; x < previewWidth; x++) {
                int pixelCount = 0;
                for (int dy = 0; dy < scale; dy++) {
                    for (int dx = 0; dx < scale; dx++) {
                        int origX = x * scale + dx;
                        int origY = y * scale + dy;
                        if (origX < width && origY < height) {
                            int rgb = image.getRGB(origX, origY) & 0xFFFFFF;
                            if (rgb != 0xFFFFFF) { // 黑色像素
                                pixelCount++;
                            }
                        }
                    }
                }

                // 根据黑色像素密度选择字符
                if (pixelCount > scale * scale * 0.7) {
                    System.out.print("██");
                } else if (pixelCount > scale * scale * 0.4) {
                    System.out.print("▓▓");
                } else if (pixelCount > scale * scale * 0.1) {
                    System.out.print("░░");
                } else {
                    System.out.print("  ");
                }
            }
            System.out.println();
        }
    }
}