WPF_MaterialTemplate.xaml.cs
37.2 KB
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
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
using Acc.ImageBox;
using Asa.FaceControl;
using BLL;
using CameraVisionLib.Model;
using DocumentFormat.OpenXml.EMMA;
using Model;
using SmartScan.SetControl.WPF.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using static SmartScan.SetControl.WPF.Model.NeoAlertBox;
using static System.Windows.Forms.AxHost;
namespace SmartScan.SetControl.WPF
{
/// <summary>
/// WPF_MaterialTemplate.xaml 的交互逻辑
/// </summary>
public partial class WPF_MaterialTemplate : System.Windows.Controls.UserControl
{
private List<MaterialTemplate> mateCopy;
private int mateIndex = -1;
private int codeIndex = -1;
private Bitmap bmp = null;
public bool isvisbles = false;
private ObservableCollection<string> codeItems = new ObservableCollection<string>();
public WPF_MaterialTemplate(bool isvisble = false)
{
InitializeComponent();
bool isvis = Config.Func_EnabledOCR;
if (isvis)
{
UsrMaterialTemplate_BtnOcrCode.Visibility = Visibility.Visible;
}
else
{
UsrMaterialTemplate_BtnOcrCode.Visibility = Visibility.Collapsed;
}
data1.ItemsSource = BLLCommon.mateEdit.Name;
mateCopy = BLLCommon.mateEdit.ToCopy();
UsrMaterialTemplate_BtnCameraImage.IsEnabled = Camera.IsConnected();
// 初始化 WindowsFormsHost 中的图像查看器
InitializeImageViewer();
// 设置条码列表数据源
data3.ItemsSource = codeItems;
}
private void InitializeImageViewer()
{
// 创建一个新的 ImageViewerEx 控件
AccImageBox imgShow = new AccImageBox();
// 配置 imgShow 的属性
imgShow.Dock = System.Windows.Forms.DockStyle.Fill;
imgShow.BackColor = System.Drawing.Color.Black;
// 其他必要的配置...
// 将 imgShow 设置为 WindowsFormsHost 的子控件
imageViewer.Child = imgShow;
}
public void Save()
{
BLLCommon.mateEdit.Save(ref mateCopy);
}
AccImageBox ImgShow = null;
private void data1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (data1.SelectedIndex == -1) return;
mateIndex = data1.SelectedIndex;
BLLCommon.mateMaxCodeID = mateCopy[mateIndex].GetMaxID();
string iamgepath = mateCopy[mateIndex].ImagePath;
ImgShow = imageViewer.Child as AccImageBox;
if (!string.IsNullOrEmpty(iamgepath))
{
if (System.IO.File.Exists(iamgepath))
{ // 加载并显示图像
var bitMap= (Bitmap)ObjConversion.ReadImageFile(iamgepath);
int contenI = 1;
//给条码加上识别数字
//kmon
//2025-6-25
mateCopy[mateIndex].Code.ForEach(codeInfo =>
{
PointF ConterPoint;
using (System.Drawing.Graphics g = Graphics.FromImage(bitMap))
{
ConterPoint = new PointF(codeInfo.CenterX,codeInfo.CenterY);
string str = contenI.ToString();
Font font = new Font("Arial", 20);
SizeF textSize = g.MeasureString(str, font);
g.DrawString(str, font, System.Drawing.Brushes.Red, ConterPoint);
}
contenI++;
});
ImgShow.Image = bitMap;
// 清除并填充条码列表
codeItems.Clear();
foreach (var item in FormatCode())
{
codeItems.Add(item);
}
if (data3.Items.Count > 0)
data3.SelectedIndex = -1;
bmp = (Bitmap)ImgShow.Image;
}
else
{
// 图片路径存在但文件不存在
ImgShow.Image = null;
codeItems.Clear();
}
}
else
{
codeItems.Clear();
ImgShow.Image = null;
}
}
// 获取标签中心点列表
private List<System.Drawing.PointF> LabelCenter()
{
List<System.Drawing.PointF> result = new List<System.Drawing.PointF>();
if (mateIndex >= 0 && mateCopy != null && mateCopy.Count > mateIndex)
{
foreach (var item in mateCopy[mateIndex].Code)
{
result.Add(new System.Drawing.PointF(item.CenterX, item.CenterY));
}
}
return result;
}
// 格式化条码列表
private string[] FormatCode()
{
List<string> result = new List<string>();
for (int i = 0; i < mateCopy[mateIndex].Code.Count; i++)
{
result.Add(FormatCode(i));
}
return result.ToArray();
}
private string FormatCode(int index)
{
MaterialCode code = mateCopy[mateIndex].Code[index];
string text = code.Text.Replace("\r", "");
text = text.Replace("\n", "");
//主键
string s = string.Format("({0}) ", index + 1);
if (code.ID == mateCopy[mateIndex].PrimaryCode)
s += "<P> ";
//条码的关键字
List<string> arr = new();
if (mateCopy[mateIndex].Code[index].CodeType.Equals(Setting_Str.OCR))
{
s += "<OCR> ";
}
s += text;
arr = new();
for (int i = 0; i < mateCopy[mateIndex].Match.Count; i++)
{
if (code.ID == mateCopy[mateIndex].Match[i].CodeID)
arr.Add(mateCopy[mateIndex].Match[i].Keyword);
}
if (arr.Count > 0)
s += " [" + string.Join(",", arr) + "]";
//OCR的关键字
//arr = new();
//List<MaterialCode> codeOcr = mateCopy[mateIndex].Code.FindAll(s => s.CodeType.Equals(Setting_Str.OCR));
//for (int i = 0; i < codeOcr.Count; i++)
//{
// List<MaterialCodeMatch> math = mateCopy[mateIndex].Match.FindAll(s => s.CodeID == codeOcr[i].ID);
// for (int j = 0; j < math.Count; j++)
// arr.Add(math[j].Keyword);
//}
//if (arr.Count > 0)
// s += " [OCR"+ "]";// + string.Join(",", arr) +
//arr = new();
//List<MaterialCodeOCR> codeOcr = mateCopy[mateIndex].Ocr.FindAll(s => s.CodeID == code.ID);
//for (int i = 0; i < codeOcr.Count; i++)
//{
// List<MaterialCodeMatch> math = mateCopy[mateIndex].Match.FindAll(s => s.CodeID == codeOcr[i].ID);
// for (int j = 0; j < math.Count; j++)
// arr.Add(math[j].Keyword);
//}
//if (arr.Count > 0)
// s += " [OCR:" + string.Join(",", arr) + "]";
return s;
}
private void BtnAddMate_Click(object sender, RoutedEventArgs e)
{
string text = LanguageWwitchover.Dialog(LanguageDialogKey.MATERIAL_TEMPLATE_ADD);
FaceInputBox input = new(UsrMaterialTemplate_BtnAddMate.Content.ToString(), text);
DialogResult dr = input.ShowDialog();
if (dr != DialogResult.OK) return;
if (string.IsNullOrWhiteSpace(input.InputValue)) return;
//检查是否有已存在的名称
var find = mateCopy.Find(s => s.Name.Equals(input.InputValue));
if (find != null)
{
string hint = Asa.FaceControl.Language.Dialog("KeyExists");
hint = hint.Replace("[name]", input.InputValue);
hint = hint.Replace("[Name]", input.InputValue);
NeoAlertBox.Show("", hint, AlertType.Warning, "NEO SCAN", true);
//new Asa.FaceControl.FaceMessageBox("", hint, MessageBoxButtons.OK).ShowDialog();
return;
}
mateCopy.Add(new() { Name = input.InputValue, State = TemplateState.Unsaved });
//mateCopy[mateCopy.Count - 1].State = TemplateState.Unsaved;
var nameList = mateCopy.Select(item => item.Name).ToList();
data1.ItemsSource = null;
data1.ItemsSource = nameList;
// 选择最后一项
data1.SelectedItem = mateCopy[mateCopy.Count - 1];
data1.ScrollIntoView(data1.SelectedItem);
}
private void BtnRenameMate_Click(object sender, RoutedEventArgs e)
{
if (mateIndex == -1) return;
// 获取当前选中的项
string selectedItem = data1.SelectedItem.ToString();
string text = LanguageWwitchover.Dialog(LanguageDialogKey.MATERIAL_TEMPLATE_RENAME);
text = text.Replace("[name]", selectedItem);
text = text.Replace("[Name]", selectedItem);
FaceInputBox input = new(UsrMaterialTemplate_BtnRenameMate.Content.ToString(), text);
DialogResult dr = input.ShowDialog();
if (dr != DialogResult.OK) return;
if (string.IsNullOrWhiteSpace(input.InputValue)) return;
//检查是否有已存在的名称
var find = mateCopy.Find(s => s.Name.Equals(input.InputValue));
if (find != null)
{
string hint = Asa.FaceControl.Language.Dialog("KeyExists");
hint = hint.Replace("[Name]", input.InputValue);
NeoAlertBox.Show("", hint, AlertType.Warning, "NEO SCAN", true);
// new Asa.FaceControl.FaceMessageBox("", hint, MessageBoxButtons.OK).ShowDialog();
return;
}
mateCopy[mateIndex].Name = input.InputValue;
mateCopy[mateIndex].State = TemplateState.Unsaved;
// 刷新 ListView
RefreshTemplateList();
// 重新选择该项
data1.SelectedIndex = mateIndex;
}
// 添加一个辅助方法来刷新模板列表
private void RefreshTemplateList()
{
// 方法2:如果绑定的是字符串列表
var nameList = mateCopy.Select(item => item.Name).ToList();
data1.ItemsSource = nameList;
}
private void BtnDelMate_Click(object sender, RoutedEventArgs e)
{
int mateIndex = data1.SelectedIndex;
if (mateIndex == -1) return;
// 获取当前选中的项目名称
string selectedName = data1.SelectedItem.ToString();
// 显示确认删除对话框
string text = LanguageWwitchover.Dialog(LanguageDialogKey.MATERIAL_TEMPLATE_DEL);
text = text.Replace("[name]", selectedName);
FaceMessageBox msg = new(UsrMaterialTemplate_BtnDelMate.Content.ToString(), text, MessageBoxButtons.YesNo);
DialogResult dr = msg.ShowDialog();
if (dr != DialogResult.Yes) return;
// 释放图像资源
if (mateCopy[mateIndex].Image != null)
mateCopy[mateIndex].Image.Dispose();
// 从模板列表中删除
mateCopy.RemoveAt(mateIndex);
// 更新ListView (根据你的数据绑定方式可能有所不同)
RefreshTemplateList();
// 选择第一项或清空选择
if (data1.Items.Count > 0)
data1.SelectedIndex = 0; // 选择第一项
else
mateIndex = -1; // 清空选择
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
string YU = BLLCommon.config.Language;
LanguageWwitchover.LoadPath(FilePath.LANGUAGE_DIR);
LanguageWwitchover.LoadLanguage(YU);
LanguageWwitchover.SetLanguage(this);
}
private void BtnOpenLight_Click(object sender, RoutedEventArgs e)
{
BLLCommon.lightSource.TurnOn();
}
private void BtnCloseLight_Click(object sender, RoutedEventArgs e)
{
BLLCommon.lightSource.TurnOff();
}
public bool iscamp = true;
string nsimagepath = null;
private void UsrMaterialTemplate_BtnLocalImage_Click(object sender, RoutedEventArgs e)
{
if (mateIndex < 0) return;
using OpenFileDialog dlg = new() { Filter = "Image Files|*.jpg;*.jpeg;*.png;*.bmp;*.gif|All Files|*.*" };
if (dlg.ShowDialog() != DialogResult.OK) return;
nsimagepath = dlg.FileName;
bmp = ObjConversion.ReadImageFile(dlg.FileName);
data3.ItemsSource = null ;
ImgShow.Image=null;
mateCopy[mateIndex].State = TemplateState.Unsaved;
mateCopy[mateIndex].ImagePath = "";
mateCopy[mateIndex].Image = bmp;
ImgShow.Image = bmp;
iscamp = false;
}
private void UsrMaterialTemplate_BtnSaveImage_Click(object sender, RoutedEventArgs e)
{
if (bmp == null) return;
SaveFileDialog dlg = new() { Filter = "JPEG图片|*.jpg|BMP图片|*.bmp|PNG图片|*.png" };
if (dlg.ShowDialog() != DialogResult.OK) return;
bmp.Save(dlg.FileName);
//switch (dlg.FilterIndex)
//{
// case 1: bmp.Save(dlg.FileName, System.Drawing.Imaging.ImageFormat.Jpeg); break;
// case 2: bmp.Save(dlg.FileName, System.Drawing.Imaging.ImageFormat.Bmp); break;
// case 3: bmp.Save(dlg.FileName, System.Drawing.Imaging.ImageFormat.Png); break;
//}
string text = Asa.FaceControl.Language.Dialog(LanguageDialogKey.SAVE_SUCCEED);
NeoAlertBox.Show("", text, AlertType.Warning, "NEO SCAN", true);
//new Asa.FaceControl.FaceMessageBox("", text, MessageBoxButtons.OK).ShowDialog();
}
private void UsrMaterialTemplate_BtnCameraImage_Click(object sender, RoutedEventArgs e)
{
if (mateIndex < 0) return;
Bitmap[] result = Camera.Capture();
if (result.Length == 0) return;
bmp = result[0];
data3.ItemsSource = null;
ImgShow.Image = null;
mateCopy[mateIndex].State = TemplateState.Unsaved;
mateCopy[mateIndex].ImagePath = "";
mateCopy[mateIndex].Image = bmp;
ImgShow.Image = bmp;
iscamp = true;
}
private void UsrMaterialTemplate_BtnScanCode_Click(object sender, RoutedEventArgs e)
{
if (mateIndex == -1) return;
if (bmp == null) return;
string text = LanguageWwitchover.Dialog(LanguageDialogKey.REMIND_CLEARTEMPLATE, "Recognizing code will reset the template.Are you sure to perform the action?");
bool dialogResult= NeoAlertBox.Show(mateCopy[mateIndex].Name, text,AlertType.Warning,"NEO SCAN",true);
//DialogResult dialogResult = new FaceMessageBox(mateCopy[mateIndex].Name, text, MessageBoxButtons.YesNo).ShowDialog();
if (!dialogResult)
{
return;
}
List<BarcodeInfo> info = null;
if (iscamp && Camera.useIDCamera)
{
Bitmap[] result = Camera.CaptureAndGetCode(out info);
if (result.Length == 0) return;
bmp = result[0];
mateCopy[mateIndex].ImagePath = "";
mateCopy[mateIndex].Image = bmp;
ImgShow.Image = bmp;
}
else
{
info = Camera.GetBarCode(bmp);
}
//info = Camera.GetBarCode(bmp);
data3.ItemsSource = null;
mateCopy[mateIndex].Match.Clear();
mateCopy[mateIndex].Code.Clear();
mateCopy[mateIndex].Ocr.Clear();
mateCopy[mateIndex].PrimaryCode = -1;
mateCopy[mateIndex].State = TemplateState.Unsaved;
BLLCommon.mateMaxCodeID = info.Count;
PointF[] lst = new PointF[info.Count];
for (int i = 0; i < info.Count; i++)
{
//info[i].Text = info[i].Text.Replace("\r", "");
//info[i].Text = info[i].Text.Replace("\n", "");
MaterialCode code = new()
{
ID = i,
Text = info[i].Text,
CodeType = info[i].CodeType,
CenterX = info[i].Center.X,
CenterY = info[i].Center.Y,
Angle = info[i].Angle,
Width = info[i].Size.Width,
Height = info[i].Size.Height,
Distance = info[i].Distance
};
LogNet.log.Info($"{code.Text}获取到的条码类型={code.CodeType}");
mateCopy[mateIndex].Code.Add(code);
lst[i] = info[i].Center;
}
if (mateCopy[mateIndex].Code.Count == 0)
{
text = LanguageWwitchover.Dialog(LanguageDialogKey.CODE_COUNT);
NeoAlertBox.Show("", text, AlertType.Warning, "NEO SCAN", true);
//new FaceMessageBox("", text, MessageBoxButtons.OK).ShowDialog();
return;
}
data3.ItemsSource=FormatCode();
data3.SelectedIndex = codeIndex = -1;
}
private void UsrMaterialTemplate_BtnOcrCode_Click(object sender, RoutedEventArgs e)
{
if (bmp == null) return;
data3.ItemsSource = null;
//保存需要识别ocr的区域
//bmp?.Save(@"ocrt.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
string currentDirectory = System.Windows.Forms.Application.StartupPath;
string filePath = System.IO.Path.Combine(currentDirectory, "ocrt.jpg");
bmp?.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
string[] regOcrCodes = PaddleOCRHelper.StartTest("..\\ocrt.jpg").Split(';');
var entity = mateCopy[mateIndex].Code.Where(a => a.CodeType.Equals(Setting_Str.OCR)).ToList();
foreach (var item in entity)
{
mateCopy[mateIndex].Code.Remove(item);
}
int startidx = BLLCommon.mateMaxCodeID + 1;
foreach (var ocr in regOcrCodes)
{
if (string.IsNullOrEmpty(ocr)) continue;
MaterialCode code = new()
{
ID = startidx,
Text = ocr,
CodeType = Setting_Str.OCR
};
mateCopy[mateIndex].Code.Add(code);
startidx++;
}
data3.ItemsSource = FormatCode();
data3.SelectedIndex = codeIndex = -1;
}
private void UsrMaterialTemplate_BtnExtractCode_Click(object sender, RoutedEventArgs e)
{
if (codeIndex == -1)
{
string YU = BLLCommon.config.Language;
if (YU=="English")
{
bool result = NeoAlertBox.Show("", "Please select a barcode", AlertType.Warning, "NEO SCAN", true);
}
else if(YU=="日语"){
bool result = NeoAlertBox.Show("", "バーコードを選択してください", AlertType.Warning, "NEO SCAN", true);
}
else
{
bool result = NeoAlertBox.Show("", "请选择一个条码", AlertType.Warning, "NEO SCAN", true);
}
return;
}
MaterialCode code = mateCopy[mateIndex].Code[codeIndex];
AsciiToCharReplacer asciiControl = new AsciiToCharReplacer();
string[] strings = null;
string codestring = asciiControl.StringToAscii(code.Text, out strings);
List<MaterialCodeMatch> match = mateCopy[mateIndex].Match.FindAll(s => s.CodeID == code.ID);
//如果使用新方法识别ocr,去除空格
if (code.CodeType == "OCR" && codestring == "http://localhost:8090/paddle/SelectOcrMethod")
{
codestring = code.Text.Replace(" ", "");
}
WPF_CodeExtract wPF_CodeExtract = new WPF_CodeExtract(codestring, code.ID, code.CodeType, match, strings);
bool dr= (bool)wPF_CodeExtract.ShowDialog();
//FrmCodeExtract frm = new(codestring, code.ID, code.CodeType, match, strings);
//DialogResult dr = frm.ShowDialog();
if (dr)
{
mateCopy[mateIndex].Match.RemoveAll(s => s.CodeID == code.ID);
mateCopy[mateIndex].Match.AddRange(wPF_CodeExtract.CodeMatch);
mateCopy[mateIndex].State = TemplateState.Unsaved;
mateCopy[mateIndex].Match.RemoveAll(x => { return mateCopy[mateIndex].Code.FindIndex(c => c.ID == x.CodeID) == -1 && mateCopy[mateIndex].Ocr.FindIndex(c => c.ID == x.CodeID) == -1; });
// 更新 ObservableCollection
if (codeItems != null && codeIndex >= 0 && codeIndex < codeItems.Count)
{
codeItems[codeIndex] = FormatCode(codeIndex);
}
}
data3.ItemsSource = null;
data3.ItemsSource = FormatCode();
data3.SelectedIndex = codeIndex;
}
private void UsrMaterialTemplate_BtnTemplateValite_Click(object sender, RoutedEventArgs e)
{
LogNet.log.Info($"开始模板验证");
if (ValidateCurTemplate())
{
ValidateAllTemplates();
}
//NeoAlertBox.Show("", "模板验证成功", AlertType.Success, "NEO SCAN", true);
LogNet.log.Info($"结束模板验证");
}
private bool ValidateCurTemplate()
{
bool ismatch = false;
try
{
if (mateIndex == -1) return false;
var curMatch = mateCopy[mateIndex];
List<BarcodeInfo> code = new List<BarcodeInfo>();
curMatch.Code.ForEach(s => { code.Add(new BarcodeInfo() { Text = s.Text, CodeType = s.CodeType }); });
ismatch = TemplateExtract(curMatch, code, out Dictionary<string, string> keyword, out List<string> allkeys);
var codeMatch = curMatch.Match.FindAll(s => !string.IsNullOrEmpty(s.Keyword));
if (codeMatch != null)
{
if (keyword.Count != allkeys.Count)//有重复
{
StringBuilder sb = new StringBuilder();
foreach (var key in keyword.Keys)
{
var dul = allkeys.FindAll(s => s.Equals(key));
if (dul != null && dul.Count > 1)
{
sb.AppendLine(key);
}
}
string text = LanguageWwitchover.Dialog(LanguageDialogKey.TEMPLATE_KEY_MATCHING_DUL, "[name] 以下关键字重复匹配");
text = text.Replace("[name]", curMatch.Name);
NeoAlertBox.Show("", text + ":\r\n" + sb.ToString(), AlertType.Warning,"NEO SCAN",true);
//new FaceMessageBox("", text + ":\r\n" + sb.ToString(), MessageBoxButtons.OK).ShowDialog();
return false;
}
else if (allkeys.Count != codeMatch.Count)//没有重复,但不匹配
{
StringBuilder sb = new StringBuilder();
foreach (var key in codeMatch)
{
if (!keyword.ContainsKey(key.Keyword))
{
sb.AppendLine(key.Keyword);
}
}
string text = LanguageWwitchover.Dialog(LanguageDialogKey.TEMPLATE_KEY_UN_MATCHING, "[name] 以下关键字匹配失败");
text = text.Replace("[name]", curMatch.Name);
NeoAlertBox.Show("", text + ":\r\n" + sb.ToString(), AlertType.Warning, "NEO SCAN", true);
return false;
}
}
if (!ismatch)
{
if (codeMatch.Count == 0)
{
string text = LanguageWwitchover.Dialog(LanguageDialogKey.TEMPLATE_UN_SET_MATCHING, "[name] 模板不匹配,未设置匹配规则");
text = text.Replace("[name]", curMatch.Name);
NeoAlertBox.Show("", text , AlertType.Warning, "NEO SCAN", true);
//new FaceMessageBox("", text, MessageBoxButtons.OK).ShowDialog();
}
}
}
catch (Exception ex)
{
LogNet.log.Error("ValidateCurTemplate", ex);
}
return ismatch;
}
private bool ValidateAllTemplates()
{
try
{
if (mateIndex == -1) return false;
var curMatch = mateCopy[mateIndex];
List<BarcodeInfo> code = new List<BarcodeInfo>();
curMatch.Code.ForEach(s => { code.Add(new BarcodeInfo() { Text = s.Text, CodeType = s.CodeType }); });
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mateCopy.Count; i++)
{
if (mateIndex == i) continue;
var othMatch = mateCopy[i];
bool ismatch = TemplateExtract(othMatch, code, out Dictionary<string, string> keyword, out List<string> allkeys);
if (ismatch)
{
sb.AppendLine(othMatch.Name);
LogNet.log.Info($"【{othMatch.Name}】模板与当前模板【{curMatch.Name}】匹配冲突");
}
}
string templates = sb.ToString();
if (templates.Length > 0)
{
string text = LanguageWwitchover.Dialog(LanguageDialogKey.TEMPLATE_MATCHING_CONFLICT, "[name] 与以下的模板匹配冲突");
text = text.Replace("[name]", curMatch.Name);
NeoAlertBox.Show("", text + ":\r\n" + templates, AlertType.Warning, "NEO SCAN", true);
// new FaceMessageBox("", text + ":\r\n" + templates, MessageBoxButtons.OK).ShowDialog();
}
}
catch (Exception ex)
{
LogNet.log.Error("ValidateAllTemplates", ex);
}
return true;
}
private bool TemplateExtract(MaterialTemplate materialTemplate, List<BarcodeInfo> code, out Dictionary<string, string> keyword, out List<string> allKeywords)
{
keyword = new(StringComparer.OrdinalIgnoreCase);
allKeywords = new List<string>();
int matchCount = 0;
bool isMatch = false;
List<MaterialCode> ocrlist = new List<MaterialCode>();
List<BarcodeInfo> ocrcode = new List<BarcodeInfo>();
//命中规则的条码索引
List<int> MatchCodeIndex = new List<int>();
int[] id = materialTemplate.GetCodeID();
for (int i = 0; i < id.Length; i++)
{
List<MaterialCodeMatch> codeMatch = materialTemplate.Match.FindAll(match => match.CodeID == id[i] && match.Keyword != "");
if (codeMatch.Count == 0) continue;
matchCount += codeMatch.Count;
for (int j = 0; j < code.Count; j++)
{
Dictionary<string, string> matchKey = CodeMatch(code[j], codeMatch);
if (matchKey != null && matchKey.Count > 0)
{
foreach (string key in matchKey.Keys)
{
allKeywords.Add(key);
if (!keyword.ContainsKey(key))
{
MatchCodeIndex.Add(j);
keyword.Add(key, matchKey[key]);
}
LogNet.log.Info($"{materialTemplate.Name}模板验证 【{j + 1}][{code[j].Text}][{code[j].CodeType}]】");
LogNet.log.Info($"{materialTemplate.Name}模板验证 匹配 【{key}={matchKey[key]}】");
}
}
}
}
if (matchCount != 0 && keyword.Count == matchCount)
{
isMatch = true;
}
//if (Config.Func_EnabledOCR)
//{
// List<MaterialCodeMatch> codeMatch = materialTemplate.Match.FindAll(match => match.CodeType.Equals(Setting_Str.OCR));
// int ocrCount = codeMatch.Count;
// if (ocrCount > 0)
// {
// LogNet.log.Info($"{materialTemplate.Name}模板验证 开始OCR匹配 [{ocrCount}]");
// // for (int i = 0; i < ocrlist.Count; i++)
// {
// var ocrcodes = materialTemplate.Code.FindAll(s => s.CodeType.Equals(Setting_Str.OCR));
// List<string> regOcrCodes = new List<string>();
// if (ocrcodes != null)
// {
// ocrcodes.ForEach(s => { regOcrCodes.Add(s.Text); });
// }
// foreach (string regCode in regOcrCodes)
// {
// if (string.IsNullOrEmpty(regCode)) continue;
// var x = new BarcodeInfo() { Text = regCode, CodeType = Setting_Str.OCR };
// Dictionary<string, string> matchKey = CodeMatch(x, codeMatch);
// if (matchKey != null)
// {
// foreach (string key in matchKey.Keys)
// {
// allKeywords.Add(key);
// if (!keyword.ContainsKey(key))
// {
// keyword.Add(key, matchKey[key]);
// ocrCount--;
// }
// LogNet.log.Info($"{materialTemplate.Name}模板验证 OCR匹配 [{key}={matchKey[key]}]");
// }
// }
// }
// }
// if (ocrCount == 0 && !isMatch)
// {
// isMatch = true;
// LogNet.log.Info($"{materialTemplate.Name}模板验证 OCR匹配成功");
// }
// LogNet.log.Info($"{materialTemplate.Name}模板验证 结束OCR匹配 ");
// }
//}
return isMatch;
}
private Dictionary<string, string> CodeMatch(BarcodeInfo codeinfo, List<MaterialCodeMatch> codeMatch)
{
Dictionary<string, string> key = new();
string code, text;
int index, count;
for (int i = 0; i < codeMatch.Count; i++)
{
int matchCount = 0;
var codeText = codeinfo.Text;
codeText = codeText.Replace("\r", "");
codeText = codeText.Replace("\n", "");
code = codeMatch[i].CaseSensitive ? codeText : codeText.ToUpper();
bool ismatch = true;
//匹配CodeType
if (codeMatch[i].CheckCodeType && !string.IsNullOrEmpty(codeMatch[i].CodeType) && !string.IsNullOrEmpty(codeinfo.CodeType))
{
matchCount++;
if (codeinfo.CodeType != codeMatch[i].CodeType)
ismatch = false;
}
//开头
if (codeMatch[i].MatchStart)
{
matchCount++;
text = codeMatch[i].CaseSensitive ? codeMatch[i].StartText : codeMatch[i].StartText.ToUpper();
if (!code.StartsWith(text))
ismatch = false;
}
//结尾
if (codeMatch[i].MatchEnd)
{
matchCount++;
//bool ismatch = true;
text = codeMatch[i].CaseSensitive ? codeMatch[i].EndText : codeMatch[i].EndText.ToUpper();
if (!code.EndsWith(text))
ismatch = false;
}
//中间
if (codeMatch[i].MatchMiddle)
{
matchCount++;
//bool ismatch = true;
text = codeMatch[i].CaseSensitive ? codeMatch[i].MiddleText : codeMatch[i].MiddleText.ToUpper();
if (text == "") return null;
index = count = 0;
while ((index = code.IndexOf(text, index)) != -1)
{
count++;
index += text.Length;
}
if (count == 0)
ismatch = false;
if (codeMatch[i].MatchMiddleType == -1 && count > codeMatch[i].MiddleTextCount)
ismatch = false;
if (codeMatch[i].MatchMiddleType == 0 && count != codeMatch[i].MiddleTextCount)
ismatch = false;
if (codeMatch[i].MatchMiddleType == 1 && count < codeMatch[i].MiddleTextCount)
ismatch = false;
}
//分割
code = codeText;
if (codeMatch[i].MatchSplit)
{
matchCount++;
//bool ismatch = true;
string str = MaterialAsciiCode.GetAsciiCode(codeMatch[i].SplitText);
if (codeText.Contains(str))
{
string[] arr = codeText.Split(new string[] { str }, StringSplitOptions.RemoveEmptyEntries);
index = codeMatch[i].SplitPart - 1;
if (index >= arr.Length)
ismatch = false;
else
code = arr[index];
}
else
{
ismatch = false;
}
}
//截取
if (!ismatch) continue;
int startIndex = codeMatch[i].SubstringStart;
int length = codeMatch[i].SubstringLength;
if (startIndex >= code.Length)
continue;
if (length == -1)
{
length = code.Length - startIndex;
}
else
{
if (startIndex + length > code.Length)
length = code.Length - startIndex;
}
var filtercode = code.Substring(startIndex, length);
if (codeMatch[i].MatchISNumber)
{
string numStr = System.Text.RegularExpressions.Regex.Replace(filtercode, @"[^\d]*", "");
if (!int.TryParse(numStr, out int res))
ismatch = false;
filtercode = res.ToString();
}
//最小
if (codeMatch[i].MatchMinLength)
{
matchCount++;
//bool ismatch = true;
if (code.Length < codeMatch[i].MinLength)
ismatch = false;
}
//最大
if (codeMatch[i].MatchMaxLength)
{
matchCount++;
//bool ismatch = true;
if (code.Length > codeMatch[i].MaxLength)
ismatch = false;
}
if (!ismatch)
continue;
if (key.ContainsKey(codeMatch[i].Keyword))
key[codeMatch[i].Keyword] = filtercode.Trim();
else
key.Add(codeMatch[i].Keyword, filtercode.Trim());
}
return key;
}
private void data3_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
codeIndex = data3.SelectedIndex;
}
}
}