alielie
2026-04-23 ef52fd6fd07508883dce4eb002acda59f0169e59
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
using HMI.Base;
using HMI.Core.Entity;
using HMI.Core.Manager;
using HMI.Core.Setting;
using HMI.Core.Util;
using HMI.UI.Util;
using HMI.Util;
using Microsoft.Web.WebView2.Core;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
 
namespace Plugin.DataBoard
{
    /// <summary>
    /// UserControl1.xaml 的交互逻辑
    /// </summary>
    public partial class DataBoard : PluginControl
    {
        public DataBoard()
        {
            DataContext = this;
            InitializeComponent();
            webview2.DefaultBackgroundColor = Color.Transparent;//Color.FromArgb(243, 249, 255);
        }
 
        private ObservableCollection<OptionData> _options = new ObservableCollection<OptionData> {
            new OptionData { Name = LangUtil.Get("bd.today"), Value = "today" },
            //new OptionData { Name = LangUtil.Get("bd.today"), Value = "today" },
            new OptionData { Name = LangUtil.Get("bd.week"), Value = "week" },
            new OptionData { Name = LangUtil.Get("bd.month"), Value = "month" }
        };
 
        public ObservableCollection<OptionData> Options
        {
            get { return _options; }
            set { Set(ref _options, value); }
        }
 
 
        private string iniFile;
        private string DataFolder;
        public override void InitFinish()
        {
            iniFile = Path.Combine(BaseFolder, "Config.ini");
            if (!File.Exists(iniFile))
            {
                File.Create(iniFile);
            }
            DataFolder = ParamSetting.DataLogFolder;
            LoadProduct();
        }
 
        private void PluginControl_Loaded(object sender, RoutedEventArgs e)
        {
 
        }
 
        private void LoadProduct()
        {
            List<ProductData> products = ProductManager.GetProducts<List<ProductData>>()
               ?? new List<ProductData>();
            this.modelSelect.Items.Clear();
            List<string> productSource = new List<string>();
            foreach (var prd in products)
            {
                this.modelSelect.Items.Add(prd.Name);
                productSource.Add(prd.Name);
            }
 
            string model = IniFileHelper.ReadIniData("Config", "Model", "", iniFile);
            if (!string.IsNullOrEmpty(model))
            {
                this.modelSelect.SelectedItem = model;
            }
            else if (products.Count > 0)
            {
                this.modelSelect.SelectedIndex = 0;
            }
        }
 
        private void RefreshAll()
        {
            try
            {
                var start0 = dtp00.SelectedDateTime ?? DateTime.Now;
                var end0 = dtp01.SelectedDateTime ?? DateTime.Now;
                RefreshChart0(start0, end0);
            }
            catch { }
 
            try
            {
                var start1 = dtp10.SelectedDateTime ?? DateTime.Now;
                var end1 = dtp11.SelectedDateTime ?? DateTime.Now;
                RefreshChart1(start1, end1);
            }
            catch { }
 
            try
            {
                var start2 = dtp20.SelectedDateTime ?? DateTime.Now;
                var end2 = dtp21.SelectedDateTime ?? DateTime.Now;
                RefreshChart2(start2, end2);
            }
            catch { }
 
            try
            {
                var start3 = dtp30.SelectedDateTime ?? DateTime.Now;
                var end3 = dtp31.SelectedDateTime ?? DateTime.Now;
                RefreshChart3(start3, end3);
            }
            catch { }
        }
 
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var btn = sender as Button;
            DateTime start, end;
            switch (btn.Name)
            {
                case "btnAll":
                    RefreshAll();
                    break;
                case "btn0":
                    start = dtp00.SelectedDateTime ?? DateTime.Now;
                    end = dtp01.SelectedDateTime ?? DateTime.Now;
                    RefreshChart0(start, end);
                    break;
                case "btn1":
                    start = dtp10.SelectedDateTime ?? DateTime.Now;
                    end = dtp11.SelectedDateTime ?? DateTime.Now;
                    RefreshChart1(start, end);
                    break;
                case "btn2":
                    start = dtp20.SelectedDateTime ?? DateTime.Now;
                    end = dtp21.SelectedDateTime ?? DateTime.Now;
                    RefreshChart2(start, end);
                    break;
                case "btn3":
                    start = dtp30.SelectedDateTime ?? DateTime.Now;
                    end = dtp31.SelectedDateTime ?? DateTime.Now;
                    RefreshChart3(start, end);
                    break;
                default:
                    break;
            }
        }
 
        public string[] GetDbFiles(DateTime startTime, DateTime endTime)
        {
            if (!Directory.Exists(DataFolder))
            {
                return new string[0];
            }
            string startName = $"Data_{startTime.ToString("yyyyMMdd")}";
            string endName = $"Data_{endTime.ToString("yyyyMMdd")}";
            var oldFiles = Directory.GetFiles(DataFolder, "Data_*.db");
            oldFiles = oldFiles.Where(file =>
            {
                var fileName = Path.GetFileNameWithoutExtension(file);
                bool flag = true;
                if (startTime != null) flag &= (string.Compare(fileName, startName) == 1 || fileName == startName);
                if (endTime != null) flag &= (string.Compare(endName, fileName) == 1 || fileName == endName);
                return flag;
            }).ToArray();
 
            return oldFiles;
        }
 
 
        private List<SerialData> SelectSerialDataByTime(string model, DateTime start, DateTime end)
        {
            var s1 = DateTime.Now;
            string[] files = GetDbFiles(start, end);
            if (files == null || files.Length <= 0)
            {
                return new List<SerialData>();
            }
            string segment = string.Empty;
            if (!string.IsNullOrEmpty(model))
            {
                segment = $"AND model = '{model}'";
            }
 
            string sql = $@"SELECT * FROM serialData WHERE time BETWEEN '{start:yyyy-MM-dd HH:mm:ss}' AND '{end:yyyy-MM-dd HH:mm:ss}' 
{segment} ORDER BY time DESC;";
 
            DataTable dt = new DataTable();
            foreach (string file in files)
            {
                using (SqliteHelper helper = new SqliteHelper(file))
                {
                    dt.Merge(helper.GetDataTable(sql));
                }
            }
            var s2 = DateTime.Now;
            log.Info($"SelectSerialDataByTime Cast: {(s2 - s1).TotalMilliseconds}");
            var data = BeanUtil.ReadBeanFromDataTable<SerialData>(dt);
            log.Info($"Bean Cast: {(DateTime.Now - s2).TotalMilliseconds}");
            return data;
        }
 
        private List<SerialData> SelectResultDataByTime(string model, DateTime start, DateTime end)
        {
            string[] files = GetDbFiles(start, end);
            if (files == null || files.Length <= 0)
            {
                return new List<SerialData>();
            }
 
            string segment = string.Empty;
            if (!string.IsNullOrEmpty(model))
            {
                segment = $"AND model = '{model}'";
            }
 
            string sql = $@"SELECT * FROM testResult WHERE time BETWEEN '{start:yyyy-MM-dd HH:mm:ss}' AND '{end:yyyy-MM-dd HH:mm:ss}' {segment};";
 
            DataTable dt = new DataTable();
            foreach (string file in files)
            {
                using (SqliteHelper helper = new SqliteHelper(file))
                {
                    var temp = helper.GetDataTable(sql);
                    dt.Merge(temp);
                }
            }
            return BeanUtil.ReadBeanFromDataTable<SerialData>(dt);
        }
 
        private void webview2_Loaded(object sender, RoutedEventArgs e)
        {
            string path = Path.Combine(PathHelper.AppFolder, "Libs", "Static", "test.html");
            webview2.Source = new Uri(path);
        }
 
        private void Webview2_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e)
        {
            cb0.SelectedIndex = 0;
            cb1.SelectedIndex = 0;
            cb2.SelectedIndex = 0;
            cb3.SelectedIndex = 0;
        }
 
        private void webview2_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            var width = this.webview2.ActualWidth - 100;
            var height = this.webview2.ActualHeight;
            webview2.CoreWebView2?.ExecuteScriptAsync($"resize({width},{height})");
        }
 
        //private void RefreshChart0(DateTime start, DateTime end)
        //{
        //    dtp00.SelectedDateTime = start;
        //    dtp01.SelectedDateTime = end;
        //    Task.Run(() =>
        //    {
        //        try
        //        {
        //            var st = DateTime.Now;
        //            List<SerialData> datas = SelectSerialDataByTime(start, end);
        //            log.Info($"0 Select Data cast: {(DateTime.Now-st).TotalMilliseconds}");
 
        //            datas.OrderByDescending(e => e.time);
        //            int all = 0, output = 0;
        //            HashSet<string> snCache = new HashSet<string>();
        //            foreach (var data in datas)
        //            {
        //                if (snCache.Contains(data.sn)) continue;
        //                snCache.Add(data.sn);
        //                all++;
        //                if (data.status == "Passed") output++;
        //            }
        //            var fields = $"['{this.lang("bd.input")}','{this.lang("bd.output")}']";
        //            Dispatcher.BeginInvoke(new Action(() =>
        //            {
        //                webview2.CoreWebView2?.ExecuteScriptAsync($"drawChart0({fields}, [{all},{output}])");
        //            }));
        //        }
        //        catch (Exception ex)
        //        {
        //            log.Error("RefreshChart0 Error.", ex);
        //            ToastHelper.Error("表1刷新失败!");
        //        }
        //    });
        //}
 
        private void RefreshChart0(DateTime start, DateTime end)
        {
            dtp00.SelectedDateTime = start;
            dtp01.SelectedDateTime = end;
            string model = modelSelect.SelectedItem?.ToString();
            Task.Run(() =>
            {
                try
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        webview2.CoreWebView2?.ExecuteScriptAsync($"loading0('加载中,请稍后...')");
                    }));
                    List<SerialData> datas = SelectResultDataByTime(model, start, end);
                    datas.OrderByDescending(e => e.time);
                    int all = 0, output = 0;
                    HashSet<string> snCache = new HashSet<string>();
                    foreach (var data in datas)
                    {
                        if (snCache.Contains(data.sn)) continue;
                        snCache.Add(data.sn);
                        all++;
                        if (data.result == "Passed") output++;
                    }
                    var fields = $"['{this.lang("bd.input")}','{this.lang("bd.output")}']";
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        webview2.CoreWebView2?.ExecuteScriptAsync($"drawChart0({fields}, [{all},{output}])");
                    }));
                }
                catch (Exception ex)
                {
                    log.Error("RefreshChart0 Error.", ex);
                    ToastHelper.Error("表1刷新失败!");
                }
            });
        }
 
        private void RefreshChart1(DateTime start, DateTime end)
        {
            dtp10.SelectedDateTime = start;
            dtp11.SelectedDateTime = end;
            string model = modelSelect.SelectedItem?.ToString();
            Task.Run(() =>
            {
                try
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        webview2.CoreWebView2?.ExecuteScriptAsync($"loading1('加载中,请稍后...')");
                    }));
                    List<SerialData> datas = SelectResultDataByTime(model, start, end);
 
                    datas = datas.OrderByDescending(e => e.time).ToList();
                    Dictionary<string, int?> pieData = new Dictionary<string, int?> {
                { "Passed",0},
                { "Failed",0},
                //{ "Action",0},
                //{ "Wait",0},
            };
                    //if (datas == null || datas.Count <= 0)
                    //{
                    //    pieData = new Dictionary<string, int?> {
                    //    { "Passed",null},
                    //    { "Failed",null},
                    //};
                    //}
 
                    HashSet<string> snCache = new HashSet<string>();
                    foreach (var data in datas)
                    {
                        if (snCache.Contains(data.sn)) continue;
                        snCache.Add(data.sn);
                        if (pieData.ContainsKey(data.result))
                        {
                            pieData[data.result]++;
                        }
                    }
                    string res = "[";
                    foreach (var key in pieData.Keys)
                    {
                        res += $"{{name:'{key}',value:{pieData[key]}}},";
                    }
                    res += "]";
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        webview2.CoreWebView2?.ExecuteScriptAsync($"drawChart1({res})");
                    }));
                }
                catch (Exception ex)
                {
                    log.Error("RefreshChart1 Error.", ex);
                    ToastHelper.Error("表2刷新失败!");
                }
            });
        }
 
        //private void RefreshChart2(DateTime start, DateTime end)
        //{
        //    dtp20.SelectedDateTime = start;
        //    dtp21.SelectedDateTime = end;
        //    List<SerialData> datas = SelectSerialDataByTime(start, end);
 
        //    var groups =
        //        datas.Where(e => e.status == "Passed" || e.status == "Failed").GroupBy(d => d.time.ToString("yyyy-MM-dd"));
 
        //    Dictionary<string, PassRateData> res = new Dictionary<string, PassRateData>();
 
        //    foreach (var group in groups)
        //    {
        //        Dictionary<string, string> snStatusCache = new Dictionary<string, string>();
        //        double all = 0, oneTimePass = 0, passed = 0;
        //        var groupDatas = group.ToList();
        //        groupDatas = groupDatas.OrderBy(e => e.time).ToList();
 
        //        foreach (var data in groupDatas)
        //        {
        //            if (snStatusCache.ContainsKey(data.sn))
        //            {
        //                if (snStatusCache[data.sn] != "Passed" && data.status == "Passed")
        //                {
        //                    passed++;
        //                }
        //                else if (snStatusCache[data.sn] == "Passed" && data.status == "Passed")
        //                {
        //                    if (oneTimePass > 0) oneTimePass--;
        //                }
        //            }
        //            else
        //            {
        //                all++;
        //                if (data.status == "Passed")
        //                {
        //                    passed++;
        //                    oneTimePass++;
        //                }
        //                snStatusCache.Add(data.sn, data.status);
        //            }
        //        }
        //        res.Add(group.Key, new PassRateData
        //        {
        //            time = group.Key,
        //            onePassRate = oneTimePass / all * 100,
        //            passRate = passed / all * 100,
        //        });
        //    }
 
 
 
        //    string fields = "[", vals0 = "[", vals1 = "[";
        //    foreach (var key in res.Keys)
        //    {
        //        fields += $"'{key}',";
        //        vals0 += $"{res[key].onePassRate},";
        //        vals1 += $"{res[key].passRate},";
        //    }
        //    fields += "]";
        //    vals0 += "]";
        //    vals1 += "]";
        //    var names = $"['{this.lang("bd.onePassRate")}','{this.lang("bd.passRate")}']";
        //    webview2.CoreWebView2?.ExecuteScriptAsync($"drawChart2({fields},{names},{vals0},{vals1})");
        //}
 
        private void RefreshChart2(DateTime start, DateTime end)
        {
            dtp20.SelectedDateTime = start;
            dtp21.SelectedDateTime = end;
            string model = modelSelect.SelectedItem?.ToString();
            Task.Run(() =>
            {
                try
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        webview2.CoreWebView2?.ExecuteScriptAsync($"loading2('加载中,请稍后...')");
                    }));
                    List<SerialData> datas = SelectResultDataByTime(model, start, end);
 
                    var groups =
                        datas.GroupBy(d => d.time.ToString("yyyy-MM-dd"));
 
                    Dictionary<string, PassRateData> res = new Dictionary<string, PassRateData>();
 
                    foreach (var group in groups)
                    {
                        Dictionary<string, string> snStatusCache = new Dictionary<string, string>();
                        double all = 0, oneTimePass = 0, passed = 0;
                        var groupDatas = group.ToList();
                        groupDatas = groupDatas.OrderByDescending(e => e.time).ToList();
 
                        foreach (var data in groupDatas)
                        {
                            if (!snStatusCache.ContainsKey(data.sn))
                            {
                                snStatusCache.Add(data.sn, data.result);
                                all++;
                                if (data.result == "Passed")
                                {
                                    passed++;
                                    oneTimePass++;
                                }
                            }
                            else
                            {
                                if (snStatusCache[data.sn] == "Passed")
                                {
                                    if (oneTimePass > 0) oneTimePass--;
                                    snStatusCache[data.sn] = "NoOnePass";
                                }
                            }
                        }
                        res.Add(group.Key, new PassRateData
                        {
                            time = group.Key,
                            onePassRate = oneTimePass / all * 100,
                            passRate = passed / all * 100,
                        });
                    }
 
                    string fields = "[", vals0 = "[", vals1 = "[";
                    foreach (var key in res.Keys)
                    {
                        fields += $"'{key}',";
                        vals0 += $"{res[key].onePassRate},";
                        vals1 += $"{res[key].passRate},";
                    }
                    fields += "]";
                    vals0 += "]";
                    vals1 += "]";
                    var names = $"['{this.lang("bd.onePassRate")}','{this.lang("bd.passRate")}']";
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        webview2.CoreWebView2?.ExecuteScriptAsync($"drawChart2({fields},{names},{vals0},{vals1})");
                    }));
                }
                catch (Exception ex)
                {
                    log.Error("RefreshChart2 Error.", ex);
                    ToastHelper.Error("表3刷新失败!");
                }
            });
        }
 
        private void RefreshChart3(DateTime start, DateTime end)
        {
            dtp30.SelectedDateTime = start;
            dtp31.SelectedDateTime = end;
            string model = modelSelect.SelectedItem?.ToString();
            Task.Run(() =>
            {
                try
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        webview2.CoreWebView2?.ExecuteScriptAsync($"loading3('加载中,请稍后...')");
                    }));
                    var st = DateTime.Now;
                    List<SerialData> datas = SelectSerialDataByTime(model, start, end);
                    var s2 = DateTime.Now;
                    log.Info($"RefreshChart3 Data Cast {(s2 - st).TotalMilliseconds}");
 
                    Dictionary<string, SimpleData> pieData = new Dictionary<string, SimpleData>();
                    List<SimpleData> datasource = new List<SimpleData>();
                    //HashSet<string> snCache = new HashSet<string>();
 
                    foreach (var data in datas)
                    {
                        //if (snCache.Contains(data.sn)) continue;
                        if (data.status != "Failed") continue;
                        if (pieData.ContainsKey(data.step))
                        {
                            pieData[data.step].Value++;
                        }
                        else
                        {
                            pieData[data.step] = new SimpleData
                            {
                                Name = data.step,
                                Value = 1
                            };
                            datasource.Add(pieData[data.step]);
                        }
                    }
                    datasource = datasource.OrderByDescending(e => e.Value).ToList();
                    if (datasource.Count > 10)
                    {
                        datasource = datasource.Take(10).ToList();
                    }
                    var s3 = DateTime.Now;
                    log.Info($"RefreshChart3 Build {(s3 - s2).TotalMilliseconds}");
 
                    string names = string.Empty, vals = string.Empty;
                    foreach (var data in datasource)
                    {
                        names += $"'{data.Name}',";
                        vals += $"{data.Value},";
                    }
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        webview2.CoreWebView2?.ExecuteScriptAsync($"drawChart3([{names}],[{vals}])");
                    }));
                }
                catch (Exception ex)
                {
                    log.Error("RefreshChart3 Error.", ex);
                    ToastHelper.Error("表4刷新失败!");
                }
            });
        }
 
        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox cb = sender as ComboBox;
            string val = (e.AddedItems[0] as OptionData)?.Value?.ToString();
            DateTime start, end;
            if (val == "today")
            {
                DateUtil.GetDayTime(out start, out end);
            }
            else if (val == "week")
            {
                DateUtil.GetWeekTime(out start, out end);
            }
            else
            {
                DateUtil.GetMonthTime(out start, out end);
            }
 
            switch (cb.Name)
            {
                case "cb0":
                    RefreshChart0(start, end);
                    break;
                case "cb1":
                    RefreshChart1(start, end);
                    break;
                case "cb2":
                    RefreshChart2(start, end);
                    break;
                case "cb3":
                    RefreshChart3(start, end);
                    break;
                default:
                    break;
            }
        }
 
        private void modelSelect_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                IniFileHelper.WriteIniData("Config", "Model", e.AddedItems[0].ToString(), iniFile);
            }
        }
    }
}