张世豪
昨天 ef78717c5b956a26b360de44f774fc2b804296c2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
package home;
 
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import chushihua.Chushihua;
import chushihua.SlotManager;
import chushihua.lunxun;
import publicway.OpenDoor;
import publicway.SerialProtocolParser;
import xitongshezhi.AdminLoginDialog;
import xitongshezhi.CardPickupDialog;
import xitongshezhi.ConfigSet;
import xitongshezhi.Fkj;
import chuankou.SerialPortService;
import chuankou.Sendmsg;
 
@SuppressWarnings("serial")
public class CardMachineUI extends JFrame {
    // 配置常量
    private static final int SCREEN_WIDTH = 600;
    private static final int SCREEN_HEIGHT = 1024;
    private static final int TOTAL_SLOTS = 60;
    // 定时器
    private Timer serialStatusTimer;
    private Timer uiUpdateTimer; // 新增:UI刷新定时器
 
    // 从配置系统获取密码
    private String ADMIN_PASSWORD;
    private String PICKUP_PASSWORD;
 
    // 卡槽管理实例
    private SlotManager slotManager;
    
    // 串口服务和协议解析器实例(新增)
    private SerialPortService serialPortService;
    private SerialProtocolParser serialProtocolParser;
 
    // 卡槽状态定义
    public enum SlotStatus {
        UNUSED("未使用", new Color(93, 109, 126)),        // 深灰色
        CHARGING("充电中", new Color(231, 76, 60)),       // 红色
        FULL("已充满", new Color(46, 204, 113)),          // 绿色
        CHARGE_FAULT("充电故障", new Color(243, 156, 18)), // 黄色
        COMM_FAULT("通信故障", new Color(155, 89, 182));  // 紫色
 
        private final String displayName;
        private final Color color;
 
        SlotStatus(String displayName, Color color) {
            this.displayName = displayName;
            this.color = color;
        }
 
        public String getDisplayName() {
            return displayName;
        }
 
        public Color getColor() {
            return color;
        }
    }
 
    // UI组件
    private JPanel mainPanel;
    private JPanel adminPanel;
    private JPanel cardSlotsPanel;
    private List<JButton> slotButtons;
 
    // 统计面板
    private JPanel currentCardsPanel;
    private JPanel chargingCardsPanel;
    private JPanel fullCardsPanel;
    private JPanel chargeFaultPanel;
    private JPanel commFaultPanel;
 
    public CardMachineUI() {
        try {
            // 先初始化系统配置和组件
            initializeSystem();
            
            // 然后初始化UI
            initializeUI();
            initializeSlots();
            startUIUpdates(); // UI刷新定时器
            startSerialStatusMonitoring(); // 串口状态监控        
            
            //System.out.println("主界面初始化完成");
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, 
                "主界面初始化失败: " + e.getMessage(), 
                "错误", 
                JOptionPane.ERROR_MESSAGE);
            throw new RuntimeException("主界面初始化失败", e);
        }
    }
 
    /**
     * 启动串口状态监控
     */
    private void startSerialStatusMonitoring() {
        serialStatusTimer = new Timer(10000, e -> { // 每10秒检查一次串口状态
            boolean serialConnected = lunxun.checkSerialConnection();
            lunxun.setSerialConnected(serialConnected);
 
            // 如果串口重新连接且轮询处于暂停状态,尝试自动恢复
            if (serialConnected && lunxun.isPolling() && lunxun.isPaused()) {
                // 只有在不在设置页面时才自动恢复
                if (!isInConfigPage()) {
                    lunxun.resumePolling();
                }
            }
        });
        serialStatusTimer.start();
    }
    
    /**
     * 检查是否在设置页面
     */
    private boolean isInConfigPage() {
        // 这里需要根据实际实现来判断是否在设置页面
        // 假设有一个方法来检查当前是否在设置对话框
        return false; // 需要根据实际情况实现
    }
 
    /**
     * 初始化系统配置和组件 - 简化版本
     */
    private void initializeSystem() {
        try {
            // 初始化卡槽管理器 - 必须首先执行
            slotManager = new SlotManager();
            //System.out.println("卡槽管理器初始化完成");
 
            // 直接使用已经初始化的配置系统
            Chushihua configSystem = Chushihua.getInstance();
            if (!configSystem.isInitialized()) {
                // 如果配置系统未初始化,尝试初始化
                if (!configSystem.initialize()) {
                    JOptionPane.showMessageDialog(this, 
                            "系统配置初始化失败,使用默认配置", "警告", JOptionPane.WARNING_MESSAGE);
                    // 设置默认密码
                    ADMIN_PASSWORD = "123456";
                    PICKUP_PASSWORD = "000000";
                } else {
                    // 从配置系统获取密码
                    ADMIN_PASSWORD = configSystem.getMachineConfig().getAdminPassword();
                    PICKUP_PASSWORD = configSystem.getMachineConfig().getFetchCardPassword();
                }
            } else {
                // 配置系统已经初始化,直接获取密码
                ADMIN_PASSWORD = configSystem.getMachineConfig().getAdminPassword();
                PICKUP_PASSWORD = configSystem.getMachineConfig().getFetchCardPassword();
            }
 
            //System.out.println("系统配置初始化完成");
            //System.out.println("管理员密码长度: " + (ADMIN_PASSWORD != null ? ADMIN_PASSWORD.length() : "null"));
            //System.out.println("取卡密码长度: " + (PICKUP_PASSWORD != null ? PICKUP_PASSWORD.length() : "null"));
 
        } catch (Exception e) {
            System.err.println("系统初始化异常: " + e.getMessage());
            e.printStackTrace();
            // 设置默认值
            ADMIN_PASSWORD = "123456";
            PICKUP_PASSWORD = "000000";
            slotManager = new SlotManager(); // 确保即使异常也有默认的slotManager
        }
    }
 
    private void initializeUI() {
        setTitle("UWB人员定位卡发卡机管理系统");
        setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setResizable(false);
 
        // 设置深色主题
        try {
            UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        // 创建主面板
        mainPanel = createMainPanel();
        adminPanel = createAdminPanel();
 
        // 初始显示主面板
        getContentPane().setLayout(new CardLayout());
        getContentPane().add(mainPanel, "MAIN");
        getContentPane().add(adminPanel, "ADMIN");
    }
 
    private JPanel createMainPanel() {
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        panel.setBackground(new Color(15, 28, 48));
        panel.setBorder(new EmptyBorder(8, 8, 8, 8));
 
        // 顶部区域
        panel.add(createTopPanel(), BorderLayout.NORTH);
 
        // 卡槽区域
        panel.add(createCardSlotsPanel(), BorderLayout.CENTER);
 
        return panel;
    }
 
    private JPanel createTopPanel() {
        JPanel topPanel = new JPanel();
        topPanel.setLayout(new BorderLayout());
        topPanel.setPreferredSize(new Dimension(SCREEN_WIDTH - 16, 180));
        topPanel.setOpaque(false);
 
        // 人脸识别区域
        topPanel.add(createFacePanel(), BorderLayout.WEST);
 
        // 状态面板
        topPanel.add(createStatusPanel(), BorderLayout.CENTER);
 
        return topPanel;
    }
 
    private JPanel createFacePanel() {
        JPanel facePanel = new JPanel();
        facePanel.setLayout(new BorderLayout());
        facePanel.setPreferredSize(new Dimension(230, 180));
        facePanel.setBackground(new Color(30, 60, 114));
        facePanel.setBorder(BorderFactory.createLineBorder(new Color(42, 82, 152), 2));
 
        JLabel faceIcon = new JLabel("👤", SwingConstants.CENTER);
        faceIcon.setFont(new Font("Microsoft YaHei", Font.PLAIN, 32));
        faceIcon.setForeground(Color.WHITE);
 
        JLabel faceTitle = new JLabel("人脸识别", SwingConstants.CENTER);
        faceTitle.setFont(new Font("Microsoft YaHei", Font.PLAIN, 16));
        faceTitle.setForeground(Color.WHITE);
 
        JLabel faceStatus = new JLabel("等待识别中...", SwingConstants.CENTER);
        faceStatus.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
        faceStatus.setForeground(new Color(160, 200, 255));
 
        JPanel contentPanel = new JPanel();
        contentPanel.setLayout(new GridLayout(3, 1));
        contentPanel.setOpaque(false);
        contentPanel.add(faceIcon);
        contentPanel.add(faceTitle);
        contentPanel.add(faceStatus);
 
        facePanel.add(contentPanel, BorderLayout.CENTER);
 
        return facePanel;
    }
 
    private JPanel createStatusPanel() {
        // 创建主面板,使用 BorderLayout
        JPanel statusPanel = new JPanel(new BorderLayout(10, 0));
        statusPanel.setBackground(new Color(26, 43, 68));
        statusPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
 
        // 设置按钮
        JButton settingsBtn = new JButton("⚙️");
        settingsBtn.setFont(new Font("Segoe UI Emoji", Font.PLAIN, 16));
        settingsBtn.setBackground(new Color(52, 152, 219));
        settingsBtn.setForeground(Color.WHITE);
        settingsBtn.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        settingsBtn.setFocusPainted(false);
        settingsBtn.addActionListener(e -> {
            // 使用新的管理员登录对话框
            if (AdminLoginDialog.showAdminLogin(CardMachineUI.this)) {
                // 密码正确,打开系统设置对话框
                ConfigSet.showConfigDialog(CardMachineUI.this);
            } else {
                // 对话框已处理错误提示,这里不需要额外处理
            }
        });
 
        // 手动刷新按钮(新增)
        JButton refreshBtn = new JButton("🔄");
        refreshBtn.setFont(new Font("Segoe UI Emoji", Font.PLAIN, 16));
        refreshBtn.setBackground(new Color(46, 204, 113));
        refreshBtn.setForeground(Color.WHITE);
        refreshBtn.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        refreshBtn.setFocusPainted(false);
        refreshBtn.addActionListener(e -> {
            updateCardSlotsDisplay();
            updateStatistics();
            JOptionPane.showMessageDialog(CardMachineUI.this, 
                    "手动刷新完成,共刷新 " + TOTAL_SLOTS + " 个卡槽", 
                    "刷新完成", JOptionPane.INFORMATION_MESSAGE);
        });
 
        // 创建两列状态面板
        JPanel statusColumnsPanel = new JPanel(new GridLayout(1, 2, 15, 0));
        statusColumnsPanel.setOpaque(false);
 
        // 第一列:当前、充电、充满
        JPanel leftColumn = new JPanel(new GridLayout(3, 1, 5, 5));
        leftColumn.setOpaque(false);
        
        // 第二列:故障、通信、串口
        JPanel rightColumn = new JPanel(new GridLayout(3, 1, 5, 5));
        rightColumn.setOpaque(false);
 
        // 创建状态项
        currentCardsPanel = createStatusItem("当前", "48/60", new Color(93, 109, 126));
        chargingCardsPanel = createStatusItem("充电", "8", new Color(231, 76, 60));
        fullCardsPanel = createStatusItem("充满", "35", new Color(46, 204, 113));
        chargeFaultPanel = createStatusItem("故障", "3", new Color(243, 156, 18));
        commFaultPanel = createStatusItem("通信", "2", new Color(155, 89, 182));
        
        // 新增:串口状态显示
        JPanel serialStatusPanel = createStatusItem("串口","0", new Color(52, 152, 219));
 
        // 添加到对应的列
        leftColumn.add(currentCardsPanel);
        leftColumn.add(chargingCardsPanel);
        leftColumn.add(fullCardsPanel);
        
        rightColumn.add(chargeFaultPanel);
        rightColumn.add(commFaultPanel);
        rightColumn.add(serialStatusPanel);
 
        // 将两列添加到列面板
        statusColumnsPanel.add(leftColumn);
        statusColumnsPanel.add(rightColumn);
 
        // 创建包装面板,包含状态面板和设置按钮
        JPanel wrapper = new JPanel(new BorderLayout());
        wrapper.setOpaque(false);
        wrapper.add(statusColumnsPanel, BorderLayout.CENTER);
 
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        buttonPanel.setOpaque(false);
        buttonPanel.add(settingsBtn);
        buttonPanel.add(refreshBtn); // 添加刷新按钮
 
        wrapper.add(buttonPanel, BorderLayout.NORTH);
 
        return wrapper;
    }
 
    private JPanel createStatusItem(String title, String value, Color color) {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 0));
        panel.setOpaque(false);
 
        // 创建圆圈标签
        JLabel circleLabel = new JLabel("●");
        circleLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 20));
        circleLabel.setForeground(color);
 
        // 创建文字标签
        JLabel textLabel = new JLabel(title + ": " + value);
        textLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        textLabel.setForeground(Color.WHITE);
 
        panel.add(circleLabel);
        panel.add(textLabel);
 
        return panel;
    }
 
    private JPanel createCardSlotsPanel() {
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        panel.setBackground(new Color(26, 43, 68));
        panel.setBorder(new EmptyBorder(10, 10, 10, 10));
 
        cardSlotsPanel = new JPanel();
        cardSlotsPanel.setLayout(new GridLayout(12, 5, 4, 4));
        cardSlotsPanel.setOpaque(false);
 
        // 创建滚动面板
        JScrollPane scrollPane = new JScrollPane(cardSlotsPanel);
        scrollPane.setBorder(BorderFactory.createEmptyBorder());
        scrollPane.getVerticalScrollBar().setUnitIncrement(16);
        scrollPane.setOpaque(false);
        scrollPane.getViewport().setOpaque(false);
 
        panel.add(scrollPane, BorderLayout.CENTER);
 
        return panel;
    }
 
    private void initializeSlots() {
        // 确保slotManager已初始化
        if (slotManager == null) {
            System.err.println("错误: slotManager 为 null,无法初始化卡槽");
            slotManager = new SlotManager(); // 紧急初始化
        }
        
        slotButtons = new ArrayList<>();
        updateCardSlotsDisplay();
        updateStatistics();
    }
 
    /**
     * 根据SlotManager中的状态获取对应的UI状态
     */
    private SlotStatus getSlotStatusFromManager(int slotId) {
        // 检查slotManager是否已初始化
        if (slotManager == null) {
            System.err.println("警告: slotManager 未初始化,使用默认状态");
            return SlotStatus.UNUSED;
        }
        
        // 从SlotManager获取卡槽信息
        Fkj slotInfo = slotManager.getSlotInfo(slotId);
        if (slotInfo == null) {
            System.err.println("警告: 卡槽 " + slotId + " 信息为空");
            return SlotStatus.UNUSED;
        }
        
        String hasCardStatus = slotInfo.getHasCard();
        String workStatus = slotInfo.getWorkStatus();
 
        // 如果无卡,显示深灰色
        if ("0".equals(hasCardStatus) || "-1".equals(hasCardStatus)) {
            return SlotStatus.UNUSED;
        } 
        // 如果有卡,根据工作状态显示不同颜色
        else if ("1".equals(hasCardStatus)) {
            try {
                int statusCode = Integer.parseInt(workStatus);
                switch (statusCode) {
                    case 2: // 充电中
                        return SlotStatus.CHARGING;
                    case 3: // 已充满
                        return SlotStatus.FULL;
                    case 4: // 故障
                    case 5: // 授权到期
                        return SlotStatus.CHARGE_FAULT;
                    case 6: // 通信超时
                        return SlotStatus.COMM_FAULT;
                    case 0: // 无效
                    case 1: // 待机
                    default:
                        return SlotStatus.UNUSED; // 默认显示深灰色
                }
            } catch (NumberFormatException e) {
                // 如果workStatus不是数字,默认显示深灰色
                return SlotStatus.UNUSED;
            }
        } 
        // 未知状态也显示深灰色
        else {
            return SlotStatus.UNUSED;
        }
    }
 
    public void updateCardSlotsDisplay() {
        // 检查必要的组件是否已初始化
        if (cardSlotsPanel == null) {
            System.err.println("错误: cardSlotsPanel 为 null");
            return;
        }
        
        if (slotManager == null) {
            System.err.println("错误: slotManager 为 null,无法更新卡槽显示");
            return;
        }
        
        cardSlotsPanel.removeAll();
        slotButtons.clear();
 
        for (int i = 1; i <= TOTAL_SLOTS; i++) {
            final int slotId = i;
            SlotStatus status = getSlotStatusFromManager(slotId);
            
            // 添加调试信息
            Fkj slotInfo = slotManager.getSlotInfo(slotId);
            if (slotInfo != null) {
            } else {
                System.err.println("卡槽 " + slotId + " - 获取信息失败");
            }
 
            JButton slotButton = new JButton(String.valueOf(slotId));
            slotButton.setBackground(status.getColor());
            slotButton.setForeground(Color.WHITE);
            slotButton.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
            slotButton.setFocusPainted(false);
            slotButton.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
 
            // 添加鼠标悬停效果
            slotButton.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseEntered(java.awt.event.MouseEvent evt) {
                    slotButton.setBackground(brighterColor(status.getColor()));
                }
 
                public void mouseExited(java.awt.event.MouseEvent evt) {
                    slotButton.setBackground(status.getColor());
                }
            });
 
            slotButton.addActionListener(e -> showPickupDialog(slotId, status));
 
            slotButtons.add(slotButton);
            cardSlotsPanel.add(slotButton);
        }
 
        cardSlotsPanel.revalidate();
        cardSlotsPanel.repaint();
        
//        //System.out.println("卡槽显示更新完成: " + updatedSlots + " 个成功, " + errorSlots + " 个失败");
    }
 
    private Color brighterColor(Color color) {
        int r = Math.min(255, color.getRed() + 30);
        int g = Math.min(255, color.getGreen() + 30);
        int b = Math.min(255, color.getBlue() + 30);
        return new Color(r, g, b);
    }
 
    public void updateStatistics() {
        // 使用SlotManager的静态方法获取统计数量
        String chargingCount = SlotManager.getChargingCount();
        String fullCount = SlotManager.getFullyChargedCount();
        String faultCount = SlotManager.getFaultCount();
        String commTimeoutCount = SlotManager.getCommTimeoutCount();
        
        // 计算当前有卡数量
        int currentCardCount = 0;
        for (int i = 1; i <= TOTAL_SLOTS; i++) {
            Fkj slotInfo = slotManager.getSlotInfo(i);
            if (slotInfo != null && "1".equals(slotInfo.getHasCard())) {
                currentCardCount++;
            }
        }
        String currentCount = currentCardCount + "/" + TOTAL_SLOTS;
 
        // 更新状态项的文本内容
        updateStatusItemText(currentCardsPanel, "当前", currentCount, new Color(93, 109, 126));
        updateStatusItemText(chargingCardsPanel, "充电", chargingCount, new Color(231, 76, 60));
        updateStatusItemText(fullCardsPanel, "充满", fullCount, new Color(46, 204, 113));
        updateStatusItemText(chargeFaultPanel, "故障", faultCount, new Color(243, 156, 18));
        updateStatusItemText(commFaultPanel, "通信", commTimeoutCount, new Color(155, 89, 182));
        
        // 更新串口状态
        updateSerialStatusDisplay();
    }
 
    // 辅助方法:更新状态项的文本
    private void updateStatusItemText(JPanel statusItem, String title, String value, Color color) {
        // 获取面板中的组件并更新
        if (statusItem.getComponentCount() >= 2) {
            JLabel circleLabel = (JLabel) statusItem.getComponent(0);
            JLabel textLabel = (JLabel) statusItem.getComponent(1);
 
            circleLabel.setForeground(color);
            textLabel.setText(title + ": " + value);
        }
    }
 
    /**
     * 更新串口状态显示
     */
    private void updateSerialStatusDisplay() {
        // 找到串口状态面板并更新
        Component[] components = commFaultPanel.getParent().getComponents();
        for (Component comp : components) {
            if (comp instanceof JPanel) {
                JPanel panel = (JPanel) comp;
                // 检查这个面板是否包含串口状态
                if (panel.getComponentCount() >= 2) {
                    JLabel textLabel = (JLabel) panel.getComponent(1);
                    if (textLabel.getText().startsWith("串口:")) {
                        Color statusColor = lunxun.isSerialConnected() ? 
                            new Color(52, 152, 219) : new Color(231, 76, 60);
                        
                        JLabel circleLabel = (JLabel) panel.getComponent(0);
                        circleLabel.setForeground(statusColor);
                        textLabel.setText("串口: " + SerialPortService.receivedDataCount);
                        break;
                    }
                }
            }
        }
    }
 
    private void showPickupDialog(int slotId, SlotStatus status) {
        // 使用新的取卡操作对话框
        boolean pickupSuccess = CardPickupDialog.showCardPickup(this, slotId, status);
        
        if (pickupSuccess) {
            // 取卡成功,调用changgehaska方法改变卡槽属性
            SlotManager.changgehaska(slotId, "1"); // "1"表示管理员操作
            //System.out.println("卡槽 " + slotId + " 取卡成功,已更新卡槽状态");
        }
    }
    
    public void dispose() {
        // 停止UI刷新定时器
        if (uiUpdateTimer != null) {
            uiUpdateTimer.stop();
        }
        
        // 停止串口状态监控
        if (serialStatusTimer != null) {
            serialStatusTimer.stop();
        }
        
        // 停止轮询查询
        if (lunxun.isPolling()) {
            lunxun.stopPolling();
            //System.out.println("应用程序关闭,轮询查询已停止");
        }
        
        // 停止串口协议解析器(新增)
        if (serialProtocolParser != null) {
            serialProtocolParser.stop();
        }
        
        // 停止串口服务
        if (serialPortService != null) {
            serialPortService.stopCapture();
            serialPortService.close();
        }
        
        super.dispose();
    }
    
    /**
     * 新增:获取串口解析器状态信息
     */
    public String getSerialParserStatus() {
        if (serialProtocolParser != null) {
            return serialProtocolParser.getStatusInfo();
        }
        return "串口解析器未初始化";
    }
    
    /**
     * 验证取卡密码
     */
    public boolean validatePickupPassword(String inputPassword) {
        try {
            // 使用Chushihua配置系统验证密码
            Chushihua configSystem = Chushihua.getInstance();
            if (configSystem.isInitialized()) {
                String correctPassword = configSystem.getMachineConfig().getFetchCardPassword();
                return inputPassword.equals(correctPassword);
            }
        } catch (Exception e) {
            System.err.println("密码验证异常: " + e.getMessage());
        }
 
        // 如果配置系统不可用,使用默认密码
        return inputPassword.equals(PICKUP_PASSWORD);
    }
 
    /**
     * 执行取卡操作
     */
    public boolean performCardPickup(int slotId) {
        try {
            // 调用OpenDoor生成开门指令
            String command = OpenDoor.openOneDoor(slotId, OpenDoor.TYPE_ISSUE_CARD);
 
            // 使用Sendmsg发送指令到串口
            boolean sendResult = Sendmsg.sendMessage(command);
 
            if (sendResult) {                
                return true;
            } else {
                System.err.println("发送开门指令失败");
                return false;
            }
 
        } catch (Exception e) {
            System.err.println("取卡操作异常: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
 
    
 
    private JPanel createAdminPanel() {
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        panel.setBackground(new Color(26, 43, 68));
        panel.setBorder(new EmptyBorder(10, 10, 10, 10));
 
        // 标题栏
        JPanel headerPanel = new JPanel(new BorderLayout());
        headerPanel.setOpaque(false);
 
        JLabel titleLabel = new JLabel("系统管理后台");
        titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 20));
        titleLabel.setForeground(new Color(52, 152, 219));
 
        JButton backButton = new JButton("返回");
        backButton.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        backButton.setBackground(new Color(231, 76, 60));
        backButton.setForeground(Color.WHITE);
        backButton.setFocusPainted(false);
        backButton.addActionListener(e -> showMainPanel());
 
        headerPanel.add(titleLabel, BorderLayout.WEST);
        headerPanel.add(backButton, BorderLayout.EAST);
 
        // 内容区域
        JPanel contentPanel = new JPanel();
        contentPanel.setLayout(new GridLayout(4, 1, 10, 10));
        contentPanel.setOpaque(false);
 
        contentPanel.add(createAdminSection("设备状态", 
                "设备: UWB发卡机-01",
                "序列号: UWB-2023-001", 
                "运行: 245天12小时",
                "版本: V2.3.5",
                "维护: 2023-10-15"));
 
        contentPanel.add(createAdminSection("网络设置",
                "IP: 192.168.1.105",
                "掩码: 255.255.255.0",
                "网关: 192.168.1.1",
                "DNS: 8.8.8.8",
                "状态: 已连接"));
 
        contentPanel.add(createAdminSection("用户管理",
                "管理员: admin",
                "操作员: 3人",
                "登录: 2023-11-05",
                "IP: 192.168.1.25",
                "权限: 超级管理员"));
 
        contentPanel.add(createAdminSection("系统日志",
                "操作: 128次",
                "发卡: 45张",
                "故障: 2次",
                "备份: 2023-11-04",
                "存储: 78%"));
 
        JScrollPane scrollPane = new JScrollPane(contentPanel);
        scrollPane.setBorder(BorderFactory.createEmptyBorder());
        scrollPane.getVerticalScrollBar().setUnitIncrement(16);
        scrollPane.setOpaque(false);
        scrollPane.getViewport().setOpaque(false);
 
        panel.add(headerPanel, BorderLayout.NORTH);
        panel.add(scrollPane, BorderLayout.CENTER);
 
        return panel;
    }
 
    private JPanel createAdminSection(String title, String... items) {
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        panel.setBackground(new Color(15, 28, 48));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
 
        JLabel titleLabel = new JLabel(title);
        titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 16));
        titleLabel.setForeground(new Color(52, 152, 219));
        titleLabel.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(44, 62, 80)));
 
        JPanel contentPanel = new JPanel();
        contentPanel.setLayout(new GridLayout(items.length, 1));
        contentPanel.setOpaque(false);
 
        for (String item : items) {
            JLabel itemLabel = new JLabel(item);
            itemLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
            itemLabel.setForeground(Color.WHITE);
            contentPanel.add(itemLabel);
        }
 
        panel.add(titleLabel, BorderLayout.NORTH);
        panel.add(contentPanel, BorderLayout.CENTER);
 
        return panel;
    }
 
    private void showMainPanel() {
        CardLayout layout = (CardLayout) getContentPane().getLayout();
        layout.show(getContentPane(), "MAIN");
        
        // 切换到主页面时,如果轮询处于暂停状态且串口已连接,则恢复轮询
        if (lunxun.isPolling() && lunxun.isPaused()) {
            // 恢复前检查串口连接
            if (lunxun.checkSerialConnection()) {
                boolean resumed = lunxun.setPollingPaused(false);
                if (resumed) {
                    //System.out.println("切换到主页面,轮询查询已恢复");
                }
            } else {
                System.err.println("切换到主页面,串口未连接,保持轮询暂停");
            }
        }
    }
 
    /**
     * 启动UI刷新定时器 - 每3秒刷新一次
     */
    private void startUIUpdates() {
        uiUpdateTimer = new Timer(3000, e -> {            
            updateCardSlotsDisplay();
            updateStatistics();
        });
        uiUpdateTimer.start();
    }
    
    /**
     * 验证管理员密码
     */
    public boolean validateAdminPassword(String inputPassword) {
        try {
            // 使用Chushihua配置系统验证密码
            Chushihua configSystem = Chushihua.getInstance();
            if (configSystem.isInitialized()) {
                String correctPassword = configSystem.getMachineConfig().getAdminPassword();
                return inputPassword.equals(correctPassword);
            }
        } catch (Exception e) {
            System.err.println("管理员密码验证异常: " + e.getMessage());
        }
 
        // 如果配置系统不可用,使用默认密码
        return inputPassword.equals(ADMIN_PASSWORD);
    }
    
    /**
     * 获取卡槽管理器实例(供对话框使用)
     */
    public SlotManager getSlotManager() {
        return slotManager;
    }
        
}