package com.fuyuanshen.equipment.utils.c;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.util.Arrays;

public class DotMatrixDisplaySimulator extends JFrame {

    private static final int WIDTH = 160;
    private static final int HEIGHT = 80;
    private static final int SCALE = 4; // 显示缩放比例

    private JComboBox<Integer> fontSizeCombo;
    private JComboBox<String> exampleCombo;
    private JTextArea textInput;
    private DotMatrixPanel displayPanel;

    private final String[] examples = {
            "紧急通知：现场危险，请立即撤离！",
            "警告：高温区域，禁止入内！",
            "系统故障：请立即联系技术人员处理",
            "安全提示：请佩戴防护装备进入作业区",
            "欢迎使用点阵显示屏模拟系统",
            "现场危险，停止救援，紧急撤离至安全区域！"
    };

    public DotMatrixDisplaySimulator() {
        super("160x80点阵显示屏模拟器");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(800, 600);
        setLayout(new BorderLayout());

        // 创建控制面板
        JPanel controlPanel = new JPanel(new GridLayout(1, 4, 10, 10));
        controlPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 字体大小选择
        controlPanel.add(new JLabel("字体大小:"));
        fontSizeCombo = new JComboBox<>(new Integer[]{8, 10, 12, 14, 16, 18, 20, 24});
        fontSizeCombo.setSelectedItem(14);
        controlPanel.add(fontSizeCombo);

        // 示例选择
        controlPanel.add(new JLabel("示例文本:"));
        exampleCombo = new JComboBox<>(examples);
        exampleCombo.addActionListener(e -> textInput.setText(examples[exampleCombo.getSelectedIndex()]));
        controlPanel.add(exampleCombo);

        // 文本输入
        textInput = new JTextArea(examples[0]);
        textInput.setLineWrap(true);
        textInput.setWrapStyleWord(true);
        JScrollPane textScroll = new JScrollPane(textInput);
        textScroll.setBorder(BorderFactory.createTitledBorder("输入文本"));

        // 点阵显示面板
        displayPanel = new DotMatrixPanel();

        // 添加组件
        add(controlPanel, BorderLayout.NORTH);
        add(textScroll, BorderLayout.CENTER);
        add(displayPanel, BorderLayout.SOUTH);

        // 添加事件监听器
        fontSizeCombo.addActionListener(e -> displayPanel.repaint());
        textInput.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {
            public void changedUpdate(javax.swing.event.DocumentEvent e) { update(); }
            public void removeUpdate(javax.swing.event.DocumentEvent e) { update(); }
            public void insertUpdate(javax.swing.event.DocumentEvent e) { update(); }
            private void update() {
                displayPanel.repaint();
            }
        });

        setLocationRelativeTo(null);
    }

    class DotMatrixPanel extends JPanel {
        private final int panelWidth = WIDTH * SCALE;
        private final int panelHeight = HEIGHT * SCALE;

        public DotMatrixPanel() {
            setPreferredSize(new Dimension(panelWidth, panelHeight + 50));
            setBorder(BorderFactory.createTitledBorder("点阵预览 (160x80)"));
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            // 绘制点阵背景
            g.setColor(Color.WHITE);
            g.fillRect(0, 0, panelWidth, panelHeight);

            // 绘制网格
            g.setColor(new Color(240, 240, 240));
            for (int x = 0; x <= WIDTH; x++) {
                int xPos = x * SCALE;
                g.drawLine(xPos, 0, xPos, panelHeight);
            }
            for (int y = 0; y <= HEIGHT; y++) {
                int yPos = y * SCALE;
                g.drawLine(0, yPos, panelWidth, yPos);
            }

            // 绘制文本
            String text = textInput.getText();
            int fontSize = (Integer) fontSizeCombo.getSelectedItem();
            Font font = new Font("黑体", Font.PLAIN, fontSize);

            // 创建虚拟点阵图像
            BufferedImage img = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_BYTE_BINARY);
            Graphics2D imgG = img.createGraphics();
            imgG.setColor(Color.WHITE);
            imgG.fillRect(0, 0, WIDTH, HEIGHT);
            imgG.setColor(Color.BLACK);
            imgG.setFont(font);
            imgG.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

            // 绘制文本到虚拟点阵
            FontMetrics metrics = imgG.getFontMetrics();
            int lineHeight = metrics.getHeight();
            int yPos = metrics.getAscent();
            String[] lines = text.split("\n");

            int maxLines = HEIGHT / lineHeight;
            int actualLines = Math.min(lines.length, maxLines);
            int totalChars = 0;

            for (int i = 0; i < actualLines; i++) {
                String line = lines[i];
                int lineWidth = metrics.stringWidth(line);
                int maxChars = WIDTH / metrics.stringWidth("字"); // 估算每行字数

                // 截断超过宽度的文本
                if (lineWidth > WIDTH) {
                    while (metrics.stringWidth(line) > WIDTH) {
                        line = line.substring(0, line.length() - 1);
                    }
                    line += "...";
                }

                // 居中显示文本
                int xPos = (WIDTH - metrics.stringWidth(line)) / 2;
                imgG.drawString(line, xPos, yPos);

                totalChars += line.length();
                yPos += lineHeight;

                if (yPos + lineHeight > HEIGHT) break;
            }
            imgG.dispose();

            // 绘制到预览面板
            for (int y = 0; y < HEIGHT; y++) {
                for (int x = 0; x < WIDTH; x++) {
                    int rgb = img.getRGB(x, y) & 0xFFFFFF;
                    if (rgb != 0xFFFFFF) { // 黑色像素
                        g.setColor(Color.BLACK);
                        g.fillRect(x * SCALE, y * SCALE, SCALE, SCALE);
                    }
                }
            }

            // 显示统计信息
            g.setColor(Color.BLACK);
            g.setFont(new Font("宋体", Font.PLAIN, 12));
            String info = String.format("字体大小: %dpt | 显示行数: %d/%d | 显示字数: %d",
                    fontSize, actualLines, maxLines, totalChars);
            g.drawString(info, 10, panelHeight + 20);

            String capacity = String.format("容量分析: %d×80点阵可显示%d-%d个汉字（%dpt字体）",
                    WIDTH,
                    (int)(WIDTH*HEIGHT/(fontSize*fontSize*1.2)),
                    (int)(WIDTH*HEIGHT/(fontSize*fontSize*0.8)),
                    fontSize);
            g.drawString(capacity, 10, panelHeight + 35);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            DotMatrixDisplaySimulator frame = new DotMatrixDisplaySimulator();
            frame.setVisible(true);

            // 显示使用提示
            String message = "<html><div style='text-align:center;'><b>160×80点阵显示屏文字容量分析</b><br><br>"
                    + "• 使用上方下拉菜单选择字体大小和示例文本<br>"
                    + "• 在文本区域输入自定义内容<br>"
                    + "• 点阵预览区域实时显示效果<br><br>"
                    + "<b>容量参考：</b><br>"
                    + "8-9pt：约20字/行 × 10行 = 200字<br>"
                    + "10-11pt：约16字/行 × 8行 = 128字<br>"
                    + "12-13pt：约13字/行 × 6行 = 78字<br>"
                    + "14-15pt：约11字/行 × 5行 = 55字<br>"
                    + "16-18pt：约9字/行 × 4行 = 36字<br>"
                    + "20-24pt：约7字/行 × 3行 = 21字</div></html>";

            JOptionPane.showMessageDialog(frame, message, "使用说明", JOptionPane.INFORMATION_MESSAGE);
        });
    }
}