NS_KetRight.xaml.cs 44.5 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 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
using BLL;
using Model;
using Newtonsoft.Json;
using SmartScan.SetControl.WPF.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using static SmartScan.SetControl.WPF.Model.NeoAlertBox;
using TextBlock = System.Windows.Controls.TextBlock;

namespace SmartScan.SetControl.WPF
{
    /// <summary>
    /// NS_KetRight.xaml 的交互逻辑
    /// </summary>
    public partial class NS_KetRight : UserControl
    {
        /// <summary>
        /// NS_KetRight 的逻辑交互
        /// </summary>

        // 存储字段控件引用
        private Dictionary<string, TextBox> fieldControls = new Dictionary<string, TextBox>();

        // 存储字段有效状态
        private Dictionary<string, bool> fieldValidStatus = new Dictionary<string, bool>();

        // 识别数据
        private Dictionary<string, string> recognizedData = new Dictionary<string, string>();

        public string templateName = "";
        // 事件
        public event EventHandler<string> DataUpdated;
        public event EventHandler PrintLabelRequested;
        public event EventHandler Cherkfun;
        public event EventHandler ISPrint;

        // 添加以下字段
        private List<Model.ExtensionControl> ctlGroup = new List<Model.ExtensionControl>();
        private CurrentExtension currentExtension = new CurrentExtension();
        private ScanWork scanWork;
        public void LoadPanel(List<string> keywords)
        {
            // 清除现有内容和控件组
            FieldsPanel.Children.Clear();
            ctlGroup.Clear();
            fieldControls.Clear();
            fieldValidStatus.Clear();
            recognizedData = new Dictionary<string, string>();

            // 按照原代码逻辑创建控件
            foreach (var key in keywords)
            {
                string[] parts = key.Split('\t');
                string fieldKey = parts.Length > 0 ? parts[0] : string.Empty;
                string fieldName = parts.Length > 1 ? parts[1] : string.Empty;

                // 创建标签控件
                TextBlock label = new TextBlock
                {
                    Text = string.IsNullOrEmpty(fieldName) ? fieldKey : $"{fieldKey}({fieldName})",
                    Margin = new Thickness(0, 0, 0, 5),
                    Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#555555")),
                    FontSize = 14,
                    FontFamily = new System.Windows.Media.FontFamily("微软雅黑"),

                };

                // 创建输入控件
                TextBox textBox = new TextBox
                {
                    Name = "ctxt_" + fieldKey,
                    Padding = new Thickness(5, 3, 5, 3),
                    Foreground = Brushes.Black,
                    Background = Brushes.White,
                    MinHeight = 40
                };

                // 将控件添加到面板
                StackPanel fieldContainer = new StackPanel
                {
                    Margin = new Thickness(0, 0, 0, 10)
                };

                fieldContainer.Children.Add(label);

                Border border = new Border
                {
                    BorderThickness = new Thickness(1),
                    BorderBrush = new SolidColorBrush(Colors.Gray),
                    CornerRadius = new CornerRadius(3),
                    Padding = new Thickness(5),
                    Child = textBox
                };

                fieldContainer.Children.Add(border);
                FieldsPanel.Children.Add(fieldContainer);

                // 创建ExtensionControl并添加到ctlGroup
                Model.ExtensionControl ext = new Model.ExtensionControl
                {
                    Control = textBox,
                    Key = fieldKey,
                    LinkName = fieldKey,
                    CanClear = true
                };

                ctlGroup.Add(ext);

                // 添加到跟踪字典
                fieldControls[fieldKey] = textBox;
                fieldValidStatus[fieldKey] = false;
                recognizedData[fieldKey] = string.Empty;

                // 添加事件处理
                textBox.TextChanged += (sender, e) => TextBox_TextChanged(sender, e, fieldKey);
            }

            // 添加GetReelID和Print按钮
            SetupButtons();

            // 最后加载扩展控件
            currentExtension.Load(ctlGroup);

            // 更新识别结果
            UpdateRecognitionResults(ResultItemsPanel);
        }

        public void ClearFieldContents()
        {
            foreach (var kvp in fieldControls)
            {
                kvp.Value.Text = string.Empty;

                // 同时更新数据字典
                if (recognizedData.ContainsKey(kvp.Key))
                {
                    recognizedData[kvp.Key] = string.Empty;
                    fieldValidStatus[kvp.Key] = false;
                }
            }

            // 更新结果显示
            UpdateRecognitionResults(ResultItemsPanel);

            // 触发数据更新事件
            DataUpdated?.Invoke(this, "clear");

            // 触发ISPrint事件(如果适用)
            ISPrint?.Invoke(this, null);
        }
        private TextBlock txtResults;
        public NS_KetRight()
        {
            InitializeComponent();
            SetupButtons();
            scanWork = new();
            // 添加Loaded事件,确保界面完全加载后再次更新语言
            this.Loaded += NS_KetRight_Loaded;
            //txtResults = FindName("txtResults") as TextBlock;
        }
        private void NS_KetRight_Loaded(object sender, RoutedEventArgs e)
        {
            // 确保UI元素完全加载后更新语言
            UpdateLanguage();
        }
        // 添加公共方法设置结果文本和颜色
        public void SetResultText(string text, string colorValue)
        {
            if (txtResults != null)
            {
                txtResults.Text = text;

                // 设置颜色
                if (colorValue.ToLower() == "green" || colorValue.ToLower() == "ok")
                {
                    txtResults.Foreground = new SolidColorBrush(Colors.Green);
                }
                else if (colorValue.ToLower() == "red" || colorValue.ToLower() == "ng")
                {
                    txtResults.Foreground = new SolidColorBrush(Colors.Red);
                }
                else if (colorValue.ToLower() == "orange" || colorValue.ToLower() == "skip")
                {
                    txtResults.Foreground = new SolidColorBrush(Colors.Orange);
                }
                else
                {
                    try
                    {
                        // 尝试将字符串解析为颜色
                        Color color = (Color)ColorConverter.ConvertFromString(colorValue);
                        txtResults.Foreground = new SolidColorBrush(color);
                    }
                    catch
                    {
                        // 解析失败则使用默认颜色
                        txtResults.Foreground = new SolidColorBrush(Colors.White);
                    }
                }
            }
        }
        // 添加用于简化常见状态设置的方法
        public void SetResultOK()
        {
            SetResultText("OK", "Green");
        }

        public void SetResultNG()
        {
            SetResultText("NG", "Red");
        }

        public void SetResultSkipped()
        {
            SetResultText("已跳过", "Orange");
        }

        public void ClearResult()
        {
            SetResultText("", "White");
        }
        // 显示原始码的辅助方法
        public void UpdateOriginalCodeDisplay(string[] originalCode)
        {
            // 创建显示原始码的逻辑,例如:
            if (originalCode != null && originalCode.Length > 0)
            {
                // 假设你有一个用于显示原始码的TextBlock或ListBox

            }
        }
        // 显示匹配状态的辅助方法
        public void UpdateMatchStatus(bool hasMatch)
        {

        }
        private Button printButton;
        private Button skipButton;

        /// <summary>
        /// 设置按钮
        /// </summary>
        private void SetupButtons()
        {
            //// 检测批次号按钮
            //Button detectLotButton = new Button
            //{
            //    Content = "检测批次号",
            //    Margin = new Thickness(0, 5, 0, 5),
            //    Padding = new Thickness(10, 5, 10, 5),
            //    //Background = new SolidColorBrush(Color.FromRgb(76, 175, 80)),
            //    Foreground = Brushes.White
            //};
            //detectLotButton.Click += async (s, e) =>
            //{
            //    await SimulateLotDetection();
            //};
            //ButtonsPanel.Children.Add(detectLotButton);

            // 打印标签按钮
            printButton = new Button
            {
                Content = LanguageWwitchover.Dialog("NS_KetRight_PrintLabel", "打印标签"),
                Margin = new Thickness(0, 5, 0, 5),
                Padding = new Thickness(10, 5, 10, 5),
                //Background = new SolidColorBrush(Color.FromRgb(0, 120, 215)),
                //Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#555555")),
                Foreground = Brushes.White,
                Height = 35,
                Name = "ns_Pring",
            };
            // 创建用于显示结果的TextBlock
            TextBlock resultTextBlock = new TextBlock
            {
                Name = "txtResults",
                Text = "", // 初始为空,稍后会根据结果设置为"OK"或"NG"
                Margin = new Thickness(8, 0, 0, 0),
                Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#f0f0f0")),
                FontSize = 14,
                FontWeight = FontWeights.Bold,
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment = VerticalAlignment.Center,
                Width = 80,
            };
            txtResults = resultTextBlock;
            // 创建跳过按钮
            skipButton = new Button
            {
                Content = LanguageWwitchover.Dialog("NS_KetRight_Skip", "跳过"),
                Margin = new Thickness(10, 5, 0, 5),
                Padding = new Thickness(10, 5, 10, 5),
                Foreground = Brushes.White,
                Height = 35,
                Width = 150,
                Name = "btnSkip",
            };
            // 为跳过按钮创建样式,和打印按钮类似
            ControlTemplate skipButtonTemplate = new ControlTemplate(typeof(Button));
            FrameworkElementFactory skipBorder = new FrameworkElementFactory(typeof(Border));
            skipBorder.Name = "border";
            skipBorder.SetValue(Border.BackgroundProperty, new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FF5722"))); // 使用不同颜色
            skipBorder.SetValue(Border.BorderBrushProperty, new SolidColorBrush(Colors.Transparent));
            skipBorder.SetValue(Border.BorderThicknessProperty, new Thickness(1));
            skipBorder.SetValue(Border.CornerRadiusProperty, new CornerRadius(2));
            FrameworkElementFactory skipContentPresenter = new FrameworkElementFactory(typeof(ContentPresenter));
            skipContentPresenter.SetValue(ContentPresenter.HorizontalAlignmentProperty, HorizontalAlignment.Center);
            skipContentPresenter.SetValue(ContentPresenter.VerticalAlignmentProperty, VerticalAlignment.Center);
            skipBorder.AppendChild(skipContentPresenter);
            skipButtonTemplate.VisualTree = skipBorder;
            // 添加触发器处理鼠标悬停
            Trigger skipMouseOverTrigger = new Trigger();
            skipMouseOverTrigger.Property = Button.IsMouseOverProperty;
            skipMouseOverTrigger.Value = true;
            skipMouseOverTrigger.Setters.Add(new Setter(
                Border.BackgroundProperty,
                new SolidColorBrush((Color)ColorConverter.ConvertFromString("#E64A19")),
                "border"));
            skipButtonTemplate.Triggers.Add(skipMouseOverTrigger);
            // 应用模板到跳过按钮
            skipButton.Template = skipButtonTemplate;
            // 创建完全自定义的按钮模板,覆盖默认外观
            ControlTemplate template = new ControlTemplate(typeof(Button));
            FrameworkElementFactory border = new FrameworkElementFactory(typeof(Border));
            border.Name = "border";
            border.SetValue(Border.BackgroundProperty, new SolidColorBrush((Color)ColorConverter.ConvertFromString("#555555")));
            border.SetValue(Border.BorderBrushProperty, new SolidColorBrush(Colors.Transparent));
            border.SetValue(Border.BorderThicknessProperty, new Thickness(1));
            border.SetValue(Border.CornerRadiusProperty, new CornerRadius(2));
            FrameworkElementFactory contentPresenter = new FrameworkElementFactory(typeof(ContentPresenter));
            contentPresenter.SetValue(ContentPresenter.HorizontalAlignmentProperty, HorizontalAlignment.Center);
            contentPresenter.SetValue(ContentPresenter.VerticalAlignmentProperty, VerticalAlignment.Center);
            border.AppendChild(contentPresenter);
            template.VisualTree = border;
            // 添加触发器处理鼠标悬停
            Trigger mouseOverTrigger = new Trigger();
            mouseOverTrigger.Property = Button.IsMouseOverProperty;
            mouseOverTrigger.Value = true;
            mouseOverTrigger.Setters.Add(new Setter(Border.BackgroundProperty,
                new SolidColorBrush((Color)ColorConverter.ConvertFromString("#444444")), "border"));
            template.Triggers.Add(mouseOverTrigger);
            // 应用模板
            printButton.Template = template;
            printButton.Click += PrintLabel_Click;
            skipButton.Click += SkipButton_Click; // 添加跳过按钮的事件处理
                                                  // 创建一个容器来存放所有元素
            StackPanel mainContainer = new StackPanel
            {
                Margin = new Thickness(0, 0, 0, 10)
            };
            // 添加结果TextBlock到容器
            mainContainer.Children.Add(printButton);
            // 添加按钮到容器
            StackPanel resultAndSkipPanel = new StackPanel
            {
                Orientation = Orientation.Horizontal,
                HorizontalAlignment = HorizontalAlignment.Center,
                Margin = new Thickness(0, 10, 0, 0)
            };
            resultAndSkipPanel.Children.Add(resultTextBlock);
            resultAndSkipPanel.Children.Add(skipButton);

            mainContainer.Children.Add(resultAndSkipPanel);
            // 添加整个容器到ButtonsPanel

            // 如果需要根据条件显示或隐藏跳过按钮
            if (!BLLCommon.config.CheckFunction)
            {
                resultAndSkipPanel.Visibility = Visibility.Collapsed;
            }
            ButtonsPanel.Children.Add(mainContainer);
            //ButtonsPanel.Children.Add(printButton);

        }

        /// <summary>
        /// 设置跳过按钮的可见性
        /// </summary>
        /// <param name="isVisible">true 显示按钮,false 隐藏按钮</param>
        public void SetSkipButtonVisibility(bool isVisible)
        {
            if (skipButton != null)
            {
                skipButton.Visibility = isVisible ? Visibility.Visible : Visibility.Collapsed;
            }
        }
        /// <summary>
        /// 更新界面语言
        /// </summary>
        public void UpdateLanguage()
        {
            // 更新标题
            if (Wpf_right_name != null)
            {
                Wpf_right_name.Text = LanguageWwitchover.Dialog("NS_KetRight_Title", "元件信息");
            }

            // 更新按钮文本
            if (printButton != null)
            {
                printButton.Content = LanguageWwitchover.Dialog("NS_KetRight_PrintLabel", "打印标签");
            }

            if (skipButton != null)
            {
                skipButton.Content = LanguageWwitchover.Dialog("NS_KetRight_Skip", "跳过");
            }

            // 更新识别结果标签
            UpdateRight();

            // 如果你有其他需要翻译的UI元素,也在这里更新它们
        }


        /// <summary>
        /// 获取字段的显示名称
        /// </summary>
        private string GetDisplayName(string key)
        {
            // 特殊处理包含 "/" 的格式(如 "PC/22")
            if (key.Contains("\t"))
            {
                string[] parts = key.Split('\t');
                if (parts.Length > 2 && !string.IsNullOrWhiteSpace(parts[1]))
                    return $"{parts[0]} ({parts[1]})";
                else return $"{parts[0]}";
            }

            // 对于普通字段,直接返回原始值
            return key;
        }
        private string lagGetDisplayName(string key)
        {
            string YU = BLLCommon.config.Language;
            if (YU == "English")
            {

                YU = "en-US";
            }
            else if (YU == "日语")
            { YU = "ja-JP"; }
            else
            {
                YU = "zh-CN";
            }

            // 特殊处理包含 "/" 的格式(如 "PC/22")
            if (key.Contains("\t"))
            {
                string[] parts = key.Split('\t');

                if (!string.IsNullOrWhiteSpace(parts[1]))
                {
                    return $"{parts[0]}({parts[1]})";
                }
                else
                {
                    return $"{parts[0]}";
                }

            }

            // 对于普通字段,直接返回原始值
            return key;
        }

        /// <summary>
        /// 使用字段列表初始化多个字段控件
        /// </summary>
        public void UpdateMultipleRecognitionData(List<string> keyList)
        {
            // 清除现有控件
            FieldsPanel.Children.Clear();
            fieldControls.Clear();
            fieldValidStatus.Clear();

            // 初始化数据
            if (recognizedData == null)
                recognizedData = new Dictionary<string, string>();

            // 创建字段控件
            foreach (string key in keyList)
            {
                // 检查键是否包含"/"分隔符
                string[] parts = key.Split('\t');

                // 只有当格式为X/Y/True时才添加字段控件
                bool shouldDisplay = true; // 默认显示

                if (parts.Length >= 3)
                {
                    // 如果有第三部分,检查它是否为"True"
                    shouldDisplay = parts[2].Equals("True", StringComparison.OrdinalIgnoreCase);
                }
                else
                {
                    shouldDisplay = false;

                }

                // 只有应该显示的字段才进行处理
                if (shouldDisplay)
                {
                    // 可以选择使用原始key或只使用第一部分作为字段名
                    string fieldKey = parts[0]; // 使用完整key
                                                // 或者: string fieldKey = parts[0]; // 只使用第一部分作为字段名

                    if (!recognizedData.ContainsKey(fieldKey))
                        recognizedData[fieldKey] = string.Empty;
                    // AddFieldControl(fieldKey, recognizedData[fieldKey]);
                    AddFieldControl(key, recognizedData[fieldKey]);
                }
            }

            // 更新结果显示
            UpdateRecognitionResults(ResultItemsPanel);
        }

        /// <summary>
        /// 更新多个字段的识别数据 - 接收字典参数
        /// </summary>
        public void UpdateMultipleRecognitionData(Dictionary<string, string> newData)
        {
            // 创建一个新的字典来存储处理后的数据
            Dictionary<string, string> cleanedData = new Dictionary<string, string>();
            // 创建一个集合记录哪些键来自OCR
            HashSet<string> ocrKeys = new HashSet<string>();

            // 处理每个键值对,移除 <OCR>: 前缀
            foreach (var kvp in newData)
            {
                string value = kvp.Value;

                // 移除 <OCR>: 前缀
                if (value != null && value.StartsWith("<OCR>", StringComparison.OrdinalIgnoreCase))
                {
                    ocrKeys.Add(kvp.Key); // 记录这个键来自OCR
                    value = value.Substring(5); // "<OCR>:" 有 6 个字符
                }

                // 将处理后的值添加到新字典
                cleanedData[kvp.Key] = value ?? string.Empty;
            }
            // 创建一个集合记录在新数据中找到匹配的控件键
            HashSet<string> matchedControlKeys = new HashSet<string>();
            Dictionary<string, bool> controlOcrStatus = new Dictionary<string, bool>();
            foreach (var kvp in cleanedData)
            {
                string key = kvp.Key;
                string value = kvp.Value;

                // 查找匹配的控件键
                var matchingKey = fieldControls.Keys.FirstOrDefault(k =>
                    k.Contains(key) || key.Contains(k));

                if (matchingKey != null && fieldControls.TryGetValue(matchingKey, out TextBox textBox))
                {
                    // 只设置控件文本内容,不更新recognizedData
                    textBox.Text = value;
                    matchedControlKeys.Add(matchingKey);
                    // 如果需要视觉反馈,可以临时更新控件样式,但不影响fieldValidStatus

                    // 记录此控件的OCR状态
                    bool isOcr = ocrKeys.Contains(key);
                    controlOcrStatus[matchingKey] = isOcr;
                    // bool isValid = !string.IsNullOrEmpty(value);
                    // 更新控件样式
                    bool hasContent = !string.IsNullOrEmpty(value);
                    UpdateControlStyle(textBox, matchingKey, hasContent, isOcr);

                }
            }
            // 更新识别数据
            foreach (var controlKeyValuePair in fieldControls)
            {
                string controlKey = controlKeyValuePair.Key;
                TextBox textBox = controlKeyValuePair.Value;

                if (!matchedControlKeys.Contains(controlKey))
                {
                    // 如果不在已匹配集合中,清空控件内容
                    textBox.Text = string.Empty;
                    ISPrint?.Invoke(this, null);
                    // 将未匹配到的控件设置为红色
                    UpdateControlStyle(textBox, controlKey, false, false); // 未找到匹配的设为红色
                }
            }

            // 更新结果
            UpdateRecognitionResults(ResultItemsPanel);

            // 通知
            DataUpdated?.Invoke(this, "multiple");
        }

        /// <summary>
        /// 添加单个字段控件
        /// </summary>
        private void AddFieldControl(string key, string value)
        {
            var innerKey = key;
            if (innerKey.Contains("\t"))
            {
                string[] parts = key.Split('\t');
                innerKey = parts[0];
            }
            // 创建容器
            StackPanel fieldContainer = new StackPanel
            {
                Margin = new Thickness(0, 0, 0, 10)
            };

            // 创建标签
            TextBlock label = new TextBlock
            {
                Text = GetDisplayName(key),
                Margin = new Thickness(0, 0, 0, 8),
                Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#f0f0f0")),
                FontSize = 14
            };
            fieldContainer.Children.Add(label);

            // 创建主容器
            Grid mainContainer = new Grid();

            // 创建左侧绿色指示条
            Border indicatorBorder = new Border
            {
                Width = 2,
                HorizontalAlignment = HorizontalAlignment.Left,
                Background = string.IsNullOrEmpty(value) ? Brushes.Transparent : Brushes.Green
            };

            // 创建文本框容器
            Border textBoxBorder = new Border
            {
                BorderThickness = new Thickness(1),
                BorderBrush = new SolidColorBrush(Colors.Gray),
                CornerRadius = new CornerRadius(3),
                Height = 36,
                Padding = new Thickness(1),
                Margin = new Thickness(0, 0, 0, 0) // 确保没有外边距
            };

            // 创建文本框
            TextBox textBox = new TextBox
            {
                Name = "txt_" + key.Replace("/", "_").Replace("\t", "_").Replace(" ", "_"),
                BorderThickness = new Thickness(0),
                Padding = new Thickness(8, 6, 8, 6),
                FontSize = 14, // 确保字体大小合适
                Text = value,
                Foreground = new SolidColorBrush(Colors.White),
                Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#2a2a2a")),
                Margin = new Thickness(1, 0, 0, 0) // 左侧留出空间,避免文本贴边
            };

            // 添加获取焦点事件 - 当文本框获得焦点时边框变白
            textBox.GotFocus += (sender, e) =>
            {
                if (textBoxBorder != null)
                {
                    textBoxBorder.BorderBrush = Brushes.White;
                }
            };
            // 添加失去焦点事件 - 当文本框失去焦点时边框恢复为灰色
            textBox.LostFocus += (sender, e) =>
            {
                if (textBoxBorder != null)
                {
                    textBoxBorder.BorderBrush = new SolidColorBrush(Colors.Gray);
                }
            };

            // 将文本框加入容器
            textBoxBorder.Child = textBox;

            // 将所有元素添加到主容器
            mainContainer.Children.Add(textBoxBorder);
            mainContainer.Children.Add(indicatorBorder); // 指示条放在上面,确保可见

            // 添加到字段容器
            fieldContainer.Children.Add(mainContainer);

            // 添加到面板
            FieldsPanel.Children.Add(fieldContainer);

            // 保存引用
            fieldControls[innerKey] = textBox;
            fieldValidStatus[innerKey] = !string.IsNullOrEmpty(value);

            // 添加事件
            textBox.TextChanged += (sender, e) => TextBox_TextChanged(sender, e, innerKey);
        }

        //private void AddFieldControl(string key, string value)
        //{
        //    // 创建容器
        //    StackPanel fieldContainer = new StackPanel
        //    {
        //        Margin = new Thickness(0, 0, 0, 10)
        //    };

        //    // 创建标签 - 使用格式化名称
        //    TextBlock label = new TextBlock
        //    {
        //        Text = GetDisplayName(key),
        //        Margin = new Thickness(0, 0, 0, 5),
        //        Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#555555")),
        //        FontSize = 14
        //    };
        //    fieldContainer.Children.Add(label);

        //    // 创建输入容器
        //    Border border = new Border
        //    {
        //        BorderThickness = new Thickness(1),
        //        BorderBrush = new SolidColorBrush(Colors.Gray),
        //        CornerRadius = new CornerRadius(3),
        //        Padding = new Thickness(5)
        //    };

        //    // 创建输入框
        //    string controlName = "txt_" + key.Replace("/", "_").Replace(" ", "_");
        //    TextBox textBox = new TextBox
        //    {
        //        Name = controlName,
        //        BorderThickness = new Thickness(0),
        //        Padding = new Thickness(5, 3, 5, 3),
        //        Text = value,

        //        Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#000000")),
        //        //Background = Brushes.Transparent
        //        Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#ffffff")),

        //    };


        //    // Un marco sin estilo
        //    bool isValid = !string.IsNullOrEmpty(value);
        //    fieldValidStatus[key] = isValid;

        //    if (isValid)
        //    {
        //        // Con Grid
        //        Grid grid = new Grid();

        //        // Un borde verde
        //        Border leftBorder = new Border
        //        {
        //            Background = Brushes.Green,
        //            Width = 4,
        //            HorizontalAlignment = HorizontalAlignment.Left,
        //            Margin = new Thickness(0, 0, 0, 0) // 确保边框完全贴边
        //        };
        //    // 确保文本框有左侧偏移
        //    textBox.Margin = new Thickness(4, 0, 0, 0);
        //    grid.Children.Add(textBox);
        //        grid.Children.Add(leftBorder);

        //        border.Child = grid;
        //    }
        //    else
        //    {
        //        border.Child = textBox;
        //    }

        //    // Añade al contenedor
        //    fieldContainer.Children.Add(border);

        //    // Añade al panel
        //    FieldsPanel.Children.Add(fieldContainer);

        //    // Guarda referencia
        //    fieldControls[key] = textBox;

        //    // Añade evento
        //    textBox.TextChanged += (sender, e) => TextBox_TextChanged(sender, e, key);
        //}

        /// <summary>
        /// 更新样式
        /// </summary>
        private void UpdateControlStyle(TextBox textBox, string key, bool isValid, bool isOcr)
        {
            // 寻找父级 Grid 和指示条
            if (textBox.Parent is Border textBoxBorder && textBoxBorder.Parent is Grid mainGrid)
            {
                // 找到指示条
                Border indicatorBorder = mainGrid.Children.OfType<Border>().FirstOrDefault(b => b != textBoxBorder);
                if (indicatorBorder != null)
                {
                    if (!isValid)
                    {
                        // 没有内容 - 红色
                        indicatorBorder.Background = System.Windows.Media.Brushes.Red;
                    }
                    else if (isOcr)
                    {
                        // OCR识别值 - 黄色
                        indicatorBorder.Background = System.Windows.Media.Brushes.Yellow;
                    }
                    else
                    {
                        // 非OCR值 - 绿色
                        indicatorBorder.Background = System.Windows.Media.Brushes.Green;
                    }
                }
            }
        }

        /// <summary>
        /// 文本改变事件
        /// </summary>
        private void TextBox_TextChanged(object sender, TextChangedEventArgs e, string key)
        {
            TextBox textBox = sender as TextBox;
            if (textBox != null)
            {
                string value = textBox.Text;


                // 更新数据
                recognizedData[key] = value;

                // 更新状态
                bool isValid = !string.IsNullOrEmpty(value);
                fieldValidStatus[key] = isValid;

                // 更新样式
                UpdateControlStyle(textBox, key, isValid, false);

                // 更新结果
                UpdateRecognitionResults(ResultItemsPanel);

                // 通知
                DataUpdated?.Invoke(this, key);
            }
        }
        public void UpdateRight()
        {
            UpdateRecognitionResults(ResultItemsPanel);
        }
        /// <summary>
        /// 更新识别结果
        /// </summary>
        private void UpdateRecognitionResults(Panel resultPanel)
        {

            lbl_Green.Text = LanguageWwitchover.Dialog("NS_KetRight_Green", "绿色 - 完全正确");
            lbl_yellow.Text = LanguageWwitchover.Dialog("NS_KetRight_yllow", "黄色 - OCR识别结果,需要验证");
            lbl_red.Text = LanguageWwitchover.Dialog("NS_KetRight_Red", "红色 - 无法识别或有问题"); 


            //if (YU == "English")
            //{

            //    YU = "en-US";
            //    lbl_Green.Text = "Green - Completely correct";
            //    lbl_yellow.Text = "Yellow - OCR recognition result,\r\n needs verification";
            //    lbl_red.Text = "Red -Unable to recognize or \r\n has issues";
            //}
            //else if (YU == "日语") 
            //{

            //    YU = "ja-JP";

            //    lbl_Green.Text = "緑色 - 完全正確";
            //    lbl_yellow.Text = "黄色 - OCR認識結果、検証が必要";
            //    lbl_red.Text = "赤色 - 識別不能または問題あり";
            //}
            //else
            //{
            //    YU = "zh-CN";
            //    lbl_Green.Text = "绿色 - 完全正确";
            //    lbl_yellow.Text = "黄色 - OCR识别结果,需要验证";
            //    lbl_red.Text = "红色 - 无法识别或有问题";
            //}

            resultPanel.Children.Clear();
            // 计算识别率
            int totalFields = fieldValidStatus.Count;
            int validFields = fieldValidStatus.Values.Count(v => v);

            // 添加标题
            TextBlock titleBlock = new TextBlock
            {
                // Text = YU == "zh-CN" ? "识别结果" : (YU == "ja-JP" ? "認識結果" : "Recognition Result"),
                Text = LanguageWwitchover.Dialog("NS_KetRight_TextBlock", "识别结果") + " : " + templateName,
                FontSize = 16,
                Margin = new Thickness(0, 0, 0, 10),
                Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#f0f0f0"))
            };
            resultPanel.Children.Add(titleBlock);

            // 创建一个带背景色的面板
            Border mainBorder = new Border
            {
                Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#171717")),
                Padding = new Thickness(15),
                Margin = new Thickness(0, 0, 0, 10),
                CornerRadius = new CornerRadius(5)
            };
            StackPanel mainPanel = new StackPanel();
            mainBorder.Child = mainPanel;

            // 添加状态标题
            TextBlock statusLabel = new TextBlock
            {
                //Text = YU == "zh-CN" ? $"已检测字段: {validFields}/{totalFields}" : (YU == "ja-JP" ? $"検出されたフィールド: {validFields}/{totalFields}" : $"Detected Fields: {validFields}/{totalFields}"),
                Text = LanguageWwitchover.Dialog("NS_KetRight_Detect", "已检测字段") + $": {validFields}/{totalFields}",
                FontWeight = FontWeights.Bold,
                FontSize = 16,
                Margin = new Thickness(0, 0, 0, 15),
                Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#aaaaaa"))
            };
            mainPanel.Children.Add(statusLabel);

            // 收集有效和无效的字段
            List<string> validFieldNames = new List<string>();
            List<string> invalidFieldNames = new List<string>();

            foreach (var kvp in fieldValidStatus)
            {
                string fieldName = lagGetDisplayName(kvp.Key);
                if (kvp.Value)
                {
                    validFieldNames.Add(fieldName);
                }
                else
                {
                    invalidFieldNames.Add(fieldName);
                }
            }

            // 创建有效字段文本块
            if (validFieldNames.Count > 0)
            {
                TextBlock validFieldsBlock = new TextBlock
                {
                    TextWrapping = TextWrapping.Wrap,
                    Margin = new Thickness(0, 0, 0, 5),
                    Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#4CAF50"))
                };

                // 添加对号和字段名称列表
                foreach (var f in validFieldNames)
                {
                    validFieldsBlock.Text += "✓ " + f + "\r\n";
                }
                //validFieldsBlock.Inlines.Add(new Run(string.Join(", ", validFieldNames)));

                mainPanel.Children.Add(validFieldsBlock);
            }

            // 创建无效字段文本块
            if (invalidFieldNames.Count > 0)
            {
                TextBlock invalidFieldsBlock = new TextBlock
                {
                    TextWrapping = TextWrapping.Wrap,
                    Margin = new Thickness(0, 5, 0, 0),
                    Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#F44336"))
                };

                // 添加错号和字段名称列表
                foreach (var f in invalidFieldNames)
                {
                    invalidFieldsBlock.Text += "✗ " + f + "\r\n";
                }
                //invalidFieldsBlock.Inlines.Add(new Run(string.Join(", ", invalidFieldNames)));

                mainPanel.Children.Add(invalidFieldsBlock);
            }

            resultPanel.Children.Add(mainBorder);

        }
        //    private void UpdateRecognitionResults(Panel resultPanel)
        //    {

        //    resultPanel.Children.Clear();
        //    // 计算识别率
        //    int totalFields = fieldValidStatus.Count;
        //    int validFields = fieldValidStatus.Values.Count(v => v);
        //    // 创建一个带背景色的面板
        //    Border mainBorder = new Border
        //    {
        //        Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#f2f2f2")),
        //        Padding = new Thickness(5),
        //        Margin = new Thickness(0)
        //    };
        //    StackPanel mainPanel = new StackPanel();
        //    mainBorder.Child = mainPanel;
        //    // 添加状态标题
        //    TextBlock statusLabel = new TextBlock
        //    {
        //        Text = $"已检测字段: {validFields}/{totalFields}",
        //        FontWeight = FontWeights.Bold,
        //        Margin = new Thickness(0, 0, 0, 5),
        //        Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#333333"))
        //    };
        //    mainPanel.Children.Add(statusLabel);
        //    // 添加每个字段 - 确保内容在一行显示
        //    foreach (var kvp in fieldValidStatus)
        //    {
        //        // 状态标记(对号或错号)
        //        string statusSymbol = kvp.Value ? "✓" : "✗";

        //        // 设置颜色
        //        Brush statusColor = kvp.Value ?
        //            new SolidColorBrush((Color)ColorConverter.ConvertFromString("#4CAF50")) : // 绿色
        //            new SolidColorBrush((Color)ColorConverter.ConvertFromString("#F44336")); // 红色

        //        // 创建单行文本块
        //        TextBlock fieldText = new TextBlock
        //        {
        //            Foreground = statusColor,
        //            Margin = new Thickness(0, 2, 0, 2),
        //            TextTrimming = TextTrimming.CharacterEllipsis,  // 文本过长时显示省略号
        //            TextWrapping = TextWrapping.NoWrap  // 确保文本不会换行
        //        };
        //        // 添加状态符号和字段名称
        //        fieldText.Text = $"{statusSymbol} {GetDisplayName(kvp.Key)}";

        //        mainPanel.Children.Add(fieldText);
        //    }
        //    resultPanel.Children.Add(mainBorder);
        //}

        /// <summary>
        /// 清除所有数据
        /// </summary>
        public void ClearAllRecognitionData()
        {
            foreach (var key in new List<string>(recognizedData.Keys))
            {
                recognizedData[key] = string.Empty;
                fieldValidStatus[key] = false;

                if (fieldControls.TryGetValue(key, out TextBox textBox))
                {
                    if (key.ToUpper() == "LOT")
                    {
                        textBox.Text = string.Empty;
                    }
                    else
                    {
                        textBox.Text = string.Empty;
                    }

                    UpdateControlStyle(textBox, key, false, false);
                }
            }

            UpdateRecognitionResults(ResultItemsPanel);
            DataUpdated?.Invoke(this, "clear");
        }

        /// <summary>
        /// 模拟检测批次号
        /// </summary>
        public async Task SimulateLotDetection()
        {
            // 显示检测中
            if (fieldControls.TryGetValue("LOT", out TextBox lotTextBox))
            {
                lotTextBox.Text = "正在检测...";
                lotTextBox.IsEnabled = false;
            }

            // 模拟延迟
            await Task.Delay(2000);

            // 随机结果
            Random rnd = new Random();
            bool success = rnd.Next(0, 100) < 70;

            if (success)
            {
                // 生成批次号
                string lotNumber = $"LOT-{rnd.Next(100000, 999999)}";
                UpdateRecognitionData("LOT", lotNumber);
            }
            else
            {
                // 检测失败
                if (fieldControls.TryGetValue("LOT", out lotTextBox))
                {
                    lotTextBox.Text = "检测失败";
                    lotTextBox.IsEnabled = true;
                }
                UpdateRecognitionResults(ResultItemsPanel);
            }
        }

        /// <summary>
        /// 更新单个字段数据
        /// </summary>
        public void UpdateRecognitionData(string key, string value)
        {
            // 更新数据
            recognizedData[key] = value;

            // 更新状态
            fieldValidStatus[key] = !string.IsNullOrEmpty(value);

            // 更新控件
            if (fieldControls.TryGetValue(key, out TextBox textBox))
            {
                textBox.Text = value;

                // 特殊处理LOT
                if (key.ToUpper() == "LOT")
                {
                    textBox.IsEnabled = !string.IsNullOrEmpty(value);
                }

                // 更新样式
                UpdateControlStyle(textBox, key, fieldValidStatus[key], false);
            }

            // 更新结果
            UpdateRecognitionResults(ResultItemsPanel);

            // 通知
            DataUpdated?.Invoke(this, key);
        }

        /// <summary>
        /// 获取识别数据
        /// </summary>
        public Dictionary<string, string> GetRecognitionData()
        {
            return new Dictionary<string, string>(recognizedData);
        }
        // public static event NS_KetRight PrintAiing;
        /// <summary>
        /// 打印标签按钮事件
        /// </summary>
        private void PrintLabel_Click(object sender, RoutedEventArgs e)
        {
            // 检查是否所有字段都为空
            bool allFieldsEmpty = recognizedData.Any(kvp => string.IsNullOrWhiteSpace(kvp.Value));

            if (allFieldsEmpty)
            {
                string text = LanguageWwitchover.Dialog("PrintFieldsNoData", "无法打印标签,字段没有数据");
                bool result=NeoAlertBox.Show("",text,AlertType.Warning,"NEO SCAN",true); 
                LogNet.log.Info("无法打印标签: " + JsonConvert.SerializeObject(recognizedData.Where(kvp => string.IsNullOrWhiteSpace(kvp.Value))));
                // System.Windows.MessageBox.Show("无法打印标签,字段没有数据", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                //MessageBox.Show("无法打印标签,所有字段都没有数据", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                if (!result)
                    return;
            }
            PrintLabelRequested?.Invoke(this, EventArgs.Empty);
        }
        private void SkipButton_Click(object sender, RoutedEventArgs e)
        {
            Cherkfun?.Invoke(this, EventArgs.Empty);
        }

        /// <summary>
        /// 适应WinForms容器大小
        /// </summary>
        public void AdjustSizeForWinForms(System.Windows.Size size)
        {
            this.Width = size.Width;
            this.Height = size.Height;
        }

        private void UserControl_Unloaded(object sender, RoutedEventArgs e)
        {
            // 确保UI元素完全加载后更新语言
            UpdateLanguage();
        }
    }
}