C3032
2025-12-20 15492363f898704b51afce5f1c88fa3b754cbabc
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
using SmartScanner.ViewModel;
using OfficeOpenXml;
using OfficeOpenXml.Style;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
 
namespace SmartScanner
{
    public static class ExcelResultRecorder
    {
        private static readonly string reportDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Reports");
        private static readonly string reportFileName = $"DetectionResults_{DateTime.Now:yyyyMMdd}.xlsx";
        private static readonly List<DetectionRecord> _pendingRecords = new List<DetectionRecord>();
        private static readonly object _lock = new object();
        private static Timer _autoFlushTimer;
        static ExcelResultRecorder()
        {
            try
            {
                // 确保报告目录存在
                if (!Directory.Exists(reportDirectory))
                {
                    Directory.CreateDirectory(reportDirectory);
                }
                // 设置EPPlus许可证上下文
                //ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                ExcelPackage.License.SetNonCommercialPersonal("Lanbao");
                InitializeAutoFlush();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"ExcelResultRecorder初始化失败: {ex.Message}");
                throw;
            }
        }
 
        public static void RecordDetectionResult(int sequence, string result, string qrCode = "N/A")
        {
            lock (_lock)
            {
                _pendingRecords.Add(new DetectionRecord
                {
                    QrCode = qrCode,
                    Sequence = sequence,
                    Result = result,
                    Operator = UserManager.CurrentUser?.Username ?? "Unknown"
                });
 
                // 每10条记录或每隔20秒自动保存一次
                if (_pendingRecords.Count >= 10)
                {
                    Task.Run(() => FlushRecords());
                }
            }
        }
 
        public static void FlushRecords()
        {
            lock (_lock)
            {
                if (_pendingRecords.Count == 0) return;
 
                try
                {
                    string filePath = Path.Combine(reportDirectory, reportFileName);
 
                    using (var package = new ExcelPackage(new FileInfo(filePath)))
                    {
                        ExcelWorksheet worksheet = package.Workbook.Worksheets["检测结果"] ??
                                                 package.Workbook.Worksheets.Add("检测结果");
 
                        // 初始化表头(如果文件是新创建的)
                        if (worksheet.Dimension == null)
                        {
                            CreateHeader(worksheet);
                        }
 
                        // 找到第一个空行
                        int startRow = worksheet.Dimension?.End.Row + 1 ?? 2;
                        // 批量写入数据
                        for (int i = 0; i < _pendingRecords.Count; i++)
                        {
                            var record = _pendingRecords[i];
                            int currentRow = startRow + i;
 
                            worksheet.Cells[currentRow, 1].Value = record.QrCode;
                            worksheet.Cells[currentRow, 2].Value = $"点位 {record.Sequence}";
                            worksheet.Cells[currentRow, 3].Value = record.Result;
                            worksheet.Cells[currentRow, 4].Value = record.DetectionTime.ToString("yyyy-MM-dd HH:mm:ss");
                            worksheet.Cells[currentRow, 5].Value = record.Operator;
                            // 根据结果设置单元格背景色
                            var resultCell = worksheet.Cells[currentRow, 3];
                            resultCell.Style.Fill.PatternType = ExcelFillStyle.Solid;
                            resultCell.Style.Fill.BackgroundColor.SetColor(
                                record.Result == "OK" ? Color.LightGreen : Color.Red);
                        }
                        // 自动调整列宽
                        worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();
 
                        // 保存文件
                        package.Save();
                        EnhancedLogViewModel.Instance.AddLog($"{_pendingRecords.Count}条检测结果已保存至{reportFileName}");
                    }
                    _pendingRecords.Clear();
                }
                catch (Exception ex)
                {
                    // 记录错误并保留未写入的记录
                    Console.WriteLine($"记录检测结果到Excel失败: {ex.Message}");
                    EnhancedLogViewModel.Instance.AddLog($"{_pendingRecords.Count}条检测结果保存失败,请关闭{reportFileName}后重试", "ERROR");
                }
            }
        }
 
        private static void CreateHeader(ExcelWorksheet worksheet)
        {
            // 设置表头
            worksheet.Cells["A1"].Value = "二维码";
            worksheet.Cells["B1"].Value = "检测点位";
            worksheet.Cells["C1"].Value = "检测结果";
            worksheet.Cells["D1"].Value = "检测时间";
            worksheet.Cells["E1"].Value = "操作人员";
 
            // 设置表头样式
            using (var range = worksheet.Cells["A1:E1"])
            {
                range.Style.Font.Bold = true;
                range.Style.Border.Top.Style = ExcelBorderStyle.Thin;
                range.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
                range.Style.Border.Left.Style = ExcelBorderStyle.Thin;
                range.Style.Border.Right.Style = ExcelBorderStyle.Thin;
                range.Style.Fill.PatternType = ExcelFillStyle.Solid;
                range.Style.Fill.BackgroundColor.SetColor(Color.LightGray);
                range.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
            }
        }
        public static void OpenReportFolder()
        {
            try
            {
                if (Directory.Exists(reportDirectory))
                {
                    System.Diagnostics.Process.Start("explorer.exe", reportDirectory);
                }
                else
                {
                    Console.WriteLine("报告目录不存在");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"打开报告文件夹失败: {ex.Message}");
            }
        }
 
        // 定时保存任务
        public static void InitializeAutoFlush()
        {
            // 如果定时器已存在,先停止并释放
            if (_autoFlushTimer != null)
            {
                _autoFlushTimer.Stop();
                _autoFlushTimer.Dispose();
            }
 
            // 创建新的定时器
            _autoFlushTimer = new Timer(20000);
            _autoFlushTimer.Elapsed += (s, e) =>
            {
                try
                {
                    Task.Run(() => FlushRecords());
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"定时保存记录失败: {ex.Message}");
                }
            };
            _autoFlushTimer.AutoReset = true;
            _autoFlushTimer.Start();
        }
 
        private class DetectionRecord
        {
            public string QrCode { get; set; }
            public int Sequence { get; set; }
            public string Result { get; set; }
            public DateTime DetectionTime { get; } = DateTime.Now;
            public string Operator { get; set; }
        }
    }
}