FrmMain.cs 47.4 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 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
using Asa.FaceControl;
using BLL;
using HandyControl.Tools.Extension;
using Model;
using Newtonsoft.Json;
using OnlineStore.Common.util;
using SmartScan.SetControl.WPF;
using SmartScan.SetControl.WPF.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Web.UI.WebControls;
using System.Windows.Forms;
using System.Windows.Forms.Integration;
using static BLL.BLLCommon;
using static SmartScan.SetControl.WPF.Model.NeoAlertBox;

namespace SmartScan
{
    public partial class FrmMain : FaceFormNormal
    {
        private MonitorMouseKeyboard monitor;
        private ScanWork scanWork;
        public NS_KetRight wpfControl;
        private ElementHost elementHost;
        private VerticalMenuControl wpfMenu;
        public ImageViewerControl imageViewer;
        public image_text Imagetest;
        private MainWindow_Top MF_top;
        //定义成静态变量供子窗体调用
        //kmon
        //2025-6-24
        public static FrmMain mon_frmMain;
        public FrmMain()
        {

            //成静态变量赋值为本窗体
            //kmon
            //2025-6-24
            mon_frmMain = this;
            InitializeComponent();
            // 初始化导航栏
            InitializeMFTop();
            // 初始化菜单
            InitializeWpfMenu();
            this.Load += Ns_rigth_Load;
            BtnStart.Tag = "not";
            if (Config.AppUI_HideLogo)
                this.Icon = null;
            else
                this.Icon = global::SmartScan.Properties.Resources.App;
            // wpf更新字体
            UpdateNS_VericalMenuControl();
            //初始化图片界面
            //先注释
            //kmon
            InitializeImageControls();
            // 添加窗体大小调整事件
            this.Resize += YourWinFormClass_Resize;

        }
        private void YourWinFormClass_Resize(object sender, EventArgs e)
        {
            // 更新wpf_top面板宽度以匹配窗体宽度
            this.wpf_top.Width = this.ClientSize.Width;

            // 重新布局ElementHost
            elementHost.Width = this.wpf_top.Width;

            // 如果窗体状态变化,通知WPF控件
            MF_top.UpdateWindowState(this.WindowState == FormWindowState.Maximized);
        }
        /// <summary>
        /// 初始化顶部标题栏
        /// </summary>
        private void InitializeMFTop()
        {
            // 创建WPF UserControl实例
            MF_top = new MainWindow_Top();

            // 创建ElementHost来承载WPF控件
            elementHost = new ElementHost();
            this.wpf_top.Dock = DockStyle.Top;  // 或者使用Fill,取决于您希望它占据的位置
            this.wpf_top.Height = 53;  // 设置标题栏高度
            elementHost.Dock = DockStyle.Fill; // 填充父容器
            elementHost.Child = MF_top;
            elementHost.Height = 53;
            // 将ElementHost添加到您的wpf_top面板中
            this.wpf_top.Controls.Add(elementHost);

            // 设置交互逻辑 - 例如,将WinForm窗口的最小化、最大化和关闭按钮连接到WPF控件
            MF_top.MinimizeClicked += (sender, e) => this.WindowState = FormWindowState.Minimized;
            MF_top.MaximizeClicked += (sender, e) =>
            {
                if (this.WindowState == FormWindowState.Maximized)
                    this.WindowState = FormWindowState.Normal;
                else
                    this.WindowState = FormWindowState.Maximized;

                // 通知WPF控件窗口状态已更改
                MF_top.UpdateWindowState(this.WindowState == FormWindowState.Maximized);
            };
            MF_top.CloseClicked += (sender, e) => this.Close();
            // 订阅语言更改事件
            MF_top.LanguageChanged += MF_top_LanguageChanged;
            //拖动
            MF_top.DragRequested += MF_top_DragRequested;


        }
        private bool isDragging = false;
        private System.Drawing.Point dragStartPoint;
        /// <summary>
        /// wpf窗体移动事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MF_top_DragRequested(object sender, EventArgs e)
        {
            isDragging = true;
            dragStartPoint = Control.MousePosition;

            // 使用WinForms的鼠标移动事件来处理拖动
            this.MouseMove += FrmMain_MouseMove; ;
            this.MouseUp += FrmMain_MouseUp;
        }
        /// <summary>
        /// winfrom窗体移动事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmMain_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            // 只有当左键按下且窗口状态为正常时才处理拖动
            if (isDragging && (Control.MouseButtons & MouseButtons.Left) == MouseButtons.Left &&
                this.WindowState == FormWindowState.Normal)
            {
                System.Drawing.Point currentPosition = Control.MousePosition;
                this.Location = new System.Drawing.Point(
                    this.Location.X + (currentPosition.X - dragStartPoint.X),
                    this.Location.Y + (currentPosition.Y - dragStartPoint.Y)
                );
                dragStartPoint = currentPosition;
            }
            else if ((Control.MouseButtons & MouseButtons.Left) != MouseButtons.Left)
            {
                // 如果左键不再按下,停止拖动
                StopDragging();
            }

        }
        // 处理鼠标按钮释放以停止拖动
        private void FrmMain_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            // 当鼠标按钮释放时,停止拖动
            if (e.Button == MouseButtons.Left)
            {
                StopDragging();
            }
        }
        // 清理拖动状态的辅助方法
        private void StopDragging()
        {
            if (isDragging)
            {
                isDragging = false;
                this.MouseMove -= FrmMain_MouseMove;
                this.MouseUp -= FrmMain_MouseUp;
            }
        }
        /// <summary>
        /// wpf语言切换事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="language"></param>
        private void MF_top_LanguageChanged(object sender, string language)
        {
            // 处理语言变更
            //if (BLLCommon.config.Language != language)
            {
                Language.LoadLanguage(language);
                BLLCommon.config.Language = language;
                BLLCommon.config.Save();
                changeBtnStartText();
                Language.SetLanguage(this);
                LanguageWwitchover.LoadLanguage(language);
                wpfMenu.ApplyLanguage();
                //wpfControl.UpdateRight();
                // 调用新的UpdateLanguage方法,而不仅仅是UpdateRight
                wpfControl.UpdateLanguage();


            }
        }
        // 当窗口状态改变时,通知WPF控件
        protected override void OnSizeChanged(EventArgs e)
        {
            try
            {
                base.OnSizeChanged(e);
                if (MF_top != null)
                {
                    MF_top.UpdateWindowState(this.WindowState == FormWindowState.Maximized);
                }
            }
            catch (Exception ex)
            {


            }

        }

        /// <summary>
        /// 初始化图片查看控件
        /// </summary>
        private void InitializeImageControls()
        {
            try
            {
                // 创建ElementHost来承载WPF控件
                elementHost = new ElementHost();

                elementHost.Dock = DockStyle.Fill;

                // 创建WPF图片查看控件实例
                Imagetest = new image_text();

                elementHost.Child = Imagetest;

                // 将ElementHost添加到名为"wpf-image"的Panel控件中
                System.Windows.Forms.Panel wpfImagePanel = this.Controls.Find("wpf_image", true)[0] as System.Windows.Forms.Panel;
                //elementHost.Size = wpfImagePanel.ClientSize; // 设置ElementHost的大小与面板匹配
                wpfImagePanel.Padding = new Padding(0); // 确保面板没有内边距   
                // 面板大小变化时,也调整ElementHost的大小

                if (wpfImagePanel != null)
                { // 创建WPF图片查看控件实例




                    // 将ElementHost添加到面板中
                    wpfImagePanel.Controls.Clear(); // 清除Panel中的所有控件
                    wpfImagePanel.Controls.Add(elementHost); // 添加ElementHost
                    //wpfImagePanel.Dock=DockStyle.Fill;
                    // 默认不显示WPF控件
                    wpfImagePanel.Visible = true;
                    // 注册SizeChanged事件
                    wpfImagePanel.SizeChanged += (sender, args) =>
                    {
                        // 当Panel大小改变时,通知WPF控件重新适应图片
                        if (Imagetest != null)
                        {
                            Imagetest.FitToScreen();
                        }
                    };
                }
                else
                {
                    LogNet.log.Error("找不到名为'wpf-image'的Panel控件");
                }
            }
            catch (Exception ex)
            {
                LogNet.log.Error($"初始化WPF图片查看控件失败:{ex.Message}");
            }
        }

        public void Showlogs(string text)
        {
            this.Invoke((MethodInvoker)delegate { wpfMenu.ShowLog.Text = text; });



        }
        // 在主窗体类中添加
        public image_text GetImageViewer()
        {
            return Imagetest;
        }
        /// <summary>
        /// 初始化左侧菜单栏
        /// </summary>
        private void InitializeWpfMenu()
        {
            // 创建ElementHost控件来承载WPF控件f
            ElementHost host = new ElementHost();
            host.Dock = DockStyle.Left;
            host.Width = 205;
            host.Height = this.ClientSize.Height - 55 - 10; // 减去标题区域的高度(假设为40像素)
            // wpfMenu.Button1Text = "设置";
            host.Location = new Point(10, 55); // 将控件放在标题区域下方
            host.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom; // 确保在窗体大小调整时保持相对位置
                                                                                      // 创建WPF菜单控件
            wpfMenu = new VerticalMenuControl();

            // 设置属性


            // 添加事件处理
            wpfMenu.BtnStartClicked += (s, e) =>
            {

                LogNet.log.Info("按钮点击触发Work");
                if (BLLCommon.config.EnabledCamera)
                {
                    scanWork.isstart = true;
                    Task.Run(() =>
                    {
                        scanWork.Scan();
                        //scanWork.TouchOff();
                    });
                }
                else
                {
                    string YU = BLLCommon.config.Language;
                    if (YU == "English")
                    {
                        bool result = NeoAlertBox.Show("Camera Not Connected", "Unable to detect the camera device or the camera device is offline.\nPlease check the camera connection status.", AlertType.Warning, "NEO SCAN", true);
                    }
                    else if (YU == "日语")
                    {
                        bool result = NeoAlertBox.Show("カメラが接続されていません", "カメラデバイスが検出できませんでした/カメラデバイスがオフライン状態です。\nカメラの接続状態をご確認ください。", AlertType.Warning, "NEO SCAN", true);
                    }
                    else
                    {
                        bool result = NeoAlertBox.Show("相机未连接", "无法检测到相机设备或相机设备处于离线状态。\n请检查相机连接状态。", AlertType.Warning, "NEO SCAN", true);
                    }

                }

            };
            wpfMenu.BtnRetrospectClicked += (s, e) =>
            {
                monitor.Pause = true;
                new FrmRetrospect().ShowDialog();
                monitor.Pause = false;
            };

            wpfMenu.BtnSetClicked += (s, e) =>
            {
                monitor.Pause = true;
                FrmSet set = new FrmSet();
                set.Width = PicShow.Width;
                set.Height = PicShow.Height;
                set.ShowDialog();
                monitor.Pause = false;
            };
            wpfMenu.BtnAIClicked += (s, e) =>
            {
                try
                {
                    // 使用完整路径指向WPF应用程序
                    string appPath = BLLCommon.config.AI.ToString();

                    // 验证文件存在
                    if (System.IO.File.Exists(appPath))
                    {
                        // 启动WPF应用程序
                        System.Diagnostics.Process.Start(appPath);
                    }
                    else
                    {
                        string YU = BLLCommon.config.Language;
                        if (YU == "English")
                        {
                            bool result = NeoAlertBox.Show("", $"Application not found: {appPath}", AlertType.Warning, "NEO SCAN", true);
                        }
                        else if (YU == "日语")
                        {
                            bool result = NeoAlertBox.Show("", $"アプリケーションが見つかりません: {appPath}", AlertType.Warning, "NEO SCAN", true);
                        }
                        else
                        {
                            bool result = NeoAlertBox.Show("", $"找不到应用程序: {appPath}", AlertType.Warning, "NEO SCAN", true);
                        }

                    }
                }
                catch (Exception ex)
                {
                    string YU = BLLCommon.config.Language;
                    if (YU == "English")
                    {
                        bool result = NeoAlertBox.Show("", $"Error launching application: {ex.Message}", AlertType.Warning, "NEO SCAN", true);
                    }
                    else if (YU == "日语")
                    {
                        bool result = NeoAlertBox.Show("", $"アプリケーションの起動時にエラーが発生しました:: {ex.Message}", AlertType.Warning, "NEO SCAN", true);
                    }
                    else
                    {
                        bool result = NeoAlertBox.Show("", $"启动应用程序时出错: {ex.Message}", AlertType.Warning, "NEO SCAN", true);
                    }


                }
            };
            wpfMenu.BtnAboutClicked += (s, e) =>
            {
                monitor.Pause = true;
                new FrmAbout().ShowDialog();
                monitor.Pause = false;
            };
            wpfMenu.BtnTriggerIOClicked += (s, e) =>
            {
                scanWork.bendi = true;
                LogNet.log.Info("按钮点击触发Work");
                scanWork.isstart = false;
                Task.Run(() =>
                {
                    scanWork.Scan(true);
                    //scanWork.TouchOff();
                });
            };

            // 将WPF控件设置为ElementHost的子控件
            host.Child = wpfMenu;

            // 将ElementHost添加到窗体
            this.Controls.Add(host);

            // 确保它位于Z顺序的顶部
            host.BringToFront();

        }



        public void UpdateNS_VericalMenuControl()
        {
            string YU = BLLCommon.config.Language;
            if (YU == "English")
            {

                YU = "en-US";
            }
            else if (YU == "日语")
            {
                YU = "ja-JP";
            }
            else
            {
                YU = "zh-CN";
            }
            LanguageWwitchover.LoadPath(FilePath.LANGUAGE_DIR);
            LanguageWwitchover.LoadLanguage(YU);
            wpfMenu.ApplyLanguage();

        }
        /// <summary>
        /// 主界面右侧初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Ns_rigth_Load(object sender, EventArgs e)
        {
            InitializeWpfControl();
            MF_top_LanguageChanged(this, BLLCommon.config.Language);
        }
        //private  General generals;

        //private修改为public
        //kmon
        //2025-6-24
        public void InitializeWpfControl()
        {
            // 创建 WPF 控件实例
            wpfControl = new NS_KetRight();
            // 订阅打印标签事件
            wpfControl.PrintLabelRequested += WpfControl_PrintLabelRequested;
            wpfControl.Cherkfun += WpfControl_Cherkfun;
            wpfControl.ISPrint += WpfControl_ISPrint; ;
            // 创建 ElementHost 来托管 WPF 控件
            elementHost = new ElementHost();
            elementHost.Dock = DockStyle.Fill;
            elementHost.Child = wpfControl;


            // 清除 PnlExtension 的现有内容
            PnlExtension.Controls.Clear();

            // 将 ElementHost 添加到 PnlExtension 容器中
            PnlExtension.Controls.Add(elementHost);
            // 可选:设置背景色以匹配 WPF 控件
            // PnlExtension.Width = BLLCommon.config.ExtensionWidth;
            PnlExtension.Left = Width - PnlExtension.Width - 12;
            PnlExtension.BackColor = System.Drawing.Color.FromArgb(20, 20, 20);
            wpfControl.UpdateMultipleRecognitionData(BLLCommon.macroKeyValue);
            if (BLLCommon.config.CheckFunction)
            {
                Extension_Checks("2");
            }

        }

        private void WpfControl_Cherkfun(object sender, EventArgs e)
        {
            if (BLLCommon.config.Language.Equals("English"))
            {
                bool result = MessageboxNeo.Show("", "Whether to skip this operation?", "NEO SCAN", true);
                if (result)
                {
                    wpfControl.ClearFieldContents(); // 这会将文本设置为空,颜色设置为白色
                    scanWork.WaitLabelRecheck = false;
                    //lastKeys = null;
                    string text = "";
                    if (BLLCommon.config.Language.Equals("English"))
                    {
                        text = "Waiting";

                    }
                    else if (BLLCommon.config.Language.Equals("日语"))
                    {
                        text = "待機中";

                    }
                    else
                    {
                        text = "等待中";

                    }
                    wpfControl.SetSkipButtonVisibility(false);
                    wpfControl.SetResultText(text, "#FFCC00"); // 显示NG
                }
            }
            else if (BLLCommon.config.Language.Equals("日语"))
            {
                bool result = MessageboxNeo.Show("",
     "この操作をスキップしますか?",
     "NEO SCAN",
     true);


                if (result)
                {

                    wpfControl.ClearFieldContents(); // 这会将文本设置为空,颜色设置为白色
                    scanWork.WaitLabelRecheck = false;
                    //lastKeys = null;
                    string text = "";
                    if (BLLCommon.config.Language.Equals("English"))
                    {
                        text = "Waiting";

                    }
                    else if (BLLCommon.config.Language.Equals("日语"))
                    {
                        text = "待機中";

                    }
                    else
                    {
                        text = "等待中";

                    }
                    wpfControl.SetSkipButtonVisibility(false);
                    wpfControl.SetResultText(text, "#FFCC00"); // 显示NG
                }
            }
            else
            {
                bool result = MessageboxNeo.Show("", "是否跳过此操作?", "NEO SCAN", true);

                if (result)
                {
                    wpfControl.ClearFieldContents(); // 这会将文本设置为空,颜色设置为白色
                    scanWork.WaitLabelRecheck = false;
                    //lastKeys = null;
                    string text = "";
                    if (BLLCommon.config.Language.Equals("English"))
                    {
                        text = "Waiting";

                    }
                    else if (BLLCommon.config.Language.Equals("日语"))
                    {
                        text = "待機中";

                    }
                    else
                    {
                        text = "等待中";

                    }
                    wpfControl.SetSkipButtonVisibility(false);
                    wpfControl.SetResultText(text, "#FFCC00"); // 显示NG

                }

            }

            extension.CheckClears();
        }

        private void WpfControl_ISPrint(object sender, EventArgs e)
        {
            scanWork.Ispring = false;
        }

        private void WpfControl_PrintLabelRequested(object sender, EventArgs e)
        {
            try
            {
                // 获取当前识别的数据
                Dictionary<string, string> recognitionData = wpfControl.GetRecognitionData();
                // 新字典构建(保留第一个斜杠前的内容)
                Dictionary<string, string> simplifiedData = recognitionData
                    .Select(kvp =>
                    {
                        // 分割键名(对应图中KeyValuePair².key列)
                        string[] keyParts = kvp.Key.Split(new[] { '\t' }, StringSplitOptions.RemoveEmptyEntries);
                        string simpleKey = keyParts.Length > 0 ? keyParts[0] : kvp.Key;

                        return new { Key = simpleKey, Value = kvp.Value };
                    })
                    // 处理键名冲突(保留第一个出现的值)
                    .GroupBy(x => x.Key)
                    .ToDictionary(g => g.Key, g => g.First().Value);

                // 如果需要进一步验证数据
                if (simplifiedData != null && simplifiedData.Count > 0)
                {

                    // 调用打印方法
                    Extension_Printing(simplifiedData);
                    Extension_SaveRetrospect(simplifiedData);
                }
                else
                {
                    string YU = BLLCommon.config.Language;
                    if (YU == "English")
                    {
                        bool result = NeoAlertBox.Show("Print Error", "Unable to print label, no valid identification data", 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);
                    }
                }
            }
            catch (Exception ex)
            {
                LogNet.log.Error($"打印标签时出错: {ex.Message}", ex);
                string YU = BLLCommon.config.Language;
                if (YU == "English")
                {
                    bool result = NeoAlertBox.Show("", $"Error printing label: {ex.Message}", AlertType.Warning, "NEO SCAN", true);
                }
                else if (YU == "日语")
                {
                    bool result = NeoAlertBox.Show("", $"ラベル印刷時にエラーが発生しました:: {ex.Message}", AlertType.Warning, "NEO SCAN", true);
                }
                else
                {
                    bool result = NeoAlertBox.Show("", $"打印标签时出错: {ex.Message}", AlertType.Warning, "NEO SCAN", true);
                }
            }
        }

        private List<string> GetRequiredFields()
        {
            // 返回所需的字段列表
            return new List<string> { "LOT", "Date", "ProductNo", "ischeckresult" };
        }
        private bool CheckCamera()
        {
            if (BLLCommon.config.EnabledCamera)
            {
                if (!Camera.IsConnected())
                {
                    LblCameraExist.BackColor = Color.Red;
                    wpfMenu.LblCameraExist.Background = System.Windows.Media.Brushes.Red;
                    // 更新状态卡片 - 相机已启用但未连接
                    wpfMenu.UpdateCameraStatus(true, false);
                    return false;
                }
                else
                {
                    LblCameraExist.ForeColor = Color.Lime;
                    wpfMenu.LblCameraExist.Foreground = System.Windows.Media.Brushes.Lime;
                    // 更新状态卡片 - 相机已启用且已连接
                    wpfMenu.UpdateCameraStatus(true, true);
                    return true;
                }
            }
            else
            {
                LogNet.log.Info("相机已禁用");
                LblCameraExist.ForeColor = Color.Lime;
                wpfMenu.LblCameraExist.Background = System.Windows.Media.Brushes.Red;
                // 更新状态卡片 - 相机已禁用
                wpfMenu.UpdateCameraStatus(false, false);
                wpfMenu.LblCameraExist.Content = "相机已禁用";
                return true;
            }
        }

        private bool CheckIOModule()
        {

            if (BLLCommon.config.EnabledIO)
            {
                BLLCommon.ioModule.DI_Changed_Event += IoModule_DI_Changed_Event;
                if (BLLCommon.ioModule.IsConn)
                {
                    LogNet.log.Info($"IO模块 {BLLCommon.ioModule.IP} 连接成功");
                    wpfMenu.LblIOExist.Background = System.Windows.Media.Brushes.Lime;
                    wpfMenu.LblIOExist.Content = $"IO模块 {BLLCommon.ioModule.IP} 连接成功";
                    wpfMenu.UpdateIOStatus(true);

                    LblIOExist.ForeColor = Color.Lime;
                    return true;
                }
                else
                {
                    wpfMenu.UpdateIOStatus(false);
                    LogNet.log.Info($"IO模块 {BLLCommon.ioModule.IP} 没有连接");
                    LblIOExist.BackColor = Color.Red;
                    wpfMenu.LblIOExist.Background = System.Windows.Media.Brushes.Red; wpfMenu.LblIOExist.Content = $"IO模块 {BLLCommon.ioModule.IP} 没有连接";
                    return false;
                }
            }
            else
            {
                wpfMenu.UpdateIOStatus(false);
                LogNet.log.Info("IO模块已禁用");
                LblIOExist.ForeColor = Color.Lime;
                wpfMenu.LblIOExist.Background = System.Windows.Media.Brushes.Red;
                wpfMenu.LblIOExist.Content = "IO模块已禁用";
                return true;
            }
        }

        private void SaveRetrospect(Bitmap labelBmp, string[] barcode, Dictionary<string, string> content)
        {

            string path = FilePath.RETROSPECT_DIR + string.Format("{0:yyyy-MM-dd}\\", DateTime.Now);
            if (!System.IO.Directory.Exists(path))
                System.IO.Directory.CreateDirectory(path);
            string fileName = string.Format("{0:HHmmssfff}", DateTime.Now);

            switch (BLLCommon.config.HistoryImage)
            {
                case HistoryImage.Original:
                    if (PicShow.Image != null)
                        PicShow.Image.Save(path + fileName + "_camera.png", System.Drawing.Imaging.ImageFormat.Png);
                    if (labelBmp != null)
                        labelBmp.Save(path + fileName + "_label.png", System.Drawing.Imaging.ImageFormat.Png);
                    break;
                case HistoryImage.Condense:
                    if (PicShow.Image != null)
                    {
                        int w = 1024;
                        int h = w * PicShow.Image.Height / PicShow.Image.Width;
                        Bitmap bmp = new(w, h);
                        Graphics g = Graphics.FromImage(bmp);
                        g.DrawImage(PicShow.Image, new Rectangle(0, 0, w, h), new Rectangle(0, 0, PicShow.Image.Width, PicShow.Image.Height), GraphicsUnit.Pixel);
                        g.Save();
                        bmp.Save(path + fileName + "_camera.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                    }
                    if (labelBmp != null)
                        labelBmp.Save(path + fileName + "_label.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                    break;
                case HistoryImage.NoImage:
                    break;
            }

            //if (workCodeInfo != null)
            //{
            //    object[] obj = new object[workCodeInfo.Count];
            //    for (int i = 0; i < workCodeInfo.Count; i++)
            //    {
            //        Dictionary<string, string> dicCode = new()
            //        {
            //            { "X", workCodeInfo[i].Center.X.ToString() },
            //            { "Y", workCodeInfo[i].Center.Y.ToString() },
            //            { "Text", workCodeInfo[i].Text }
            //        };
            //        obj[i] = dicCode;
            //    }
            Dictionary<string, object[]> dic = new()
                {
                    { "Code", scanWork.SaveCodeInfo() },
                    { "Label", barcode },
                    {"Content",new object[]{ content } },
                };
            JavaScriptSerializer serializer = new();
            string json = serializer.Serialize(dic);
            System.IO.File.WriteAllText(path + fileName + "_code.json", json);
            //}
            LogNet.log.Info("保存历史记录");
        }

        private void IoModule_DI_Changed_Event(BLL.Status[] sta)
        {
            if (sta == null)
                LogNet.log.Info("Work IO Status = null");
            else if (sta.Length <= BLLCommon.config.IOTouch)
                LogNet.log.Info($"Work Status.Length({sta.Length}) <= {BLLCommon.config.IOTouch}");
            else if (sta[BLLCommon.config.IOTouch] == BLL.Status.Off)
                scanWork.TouchOff();
            else
            {
                LogNet.log.Info("IO模块触发Work");
                scanWork.Scan();
            }
        }

        private void Extension_SaveRetrospect(Dictionary<string, string> content)
        {
            try
            {
                string str = "追溯内容:";
                foreach (string key in content.Keys)
                    str += string.Format("({0}:{1})", key, content[key]);
                LogNet.log.Info(str);
                BLLCommon.SCMM.SendData(content);
                Bitmap labelBmp = BLLCommon.labelEdit.PrintImage(BLLCommon.config.DefaultPrintLabel, content, out _);
                //Common.labelEdit.PrintLast(Common.config.DefaultPrintLabel, Common.config.PrinterName, Common.config.PrintLandscape, content, out string[] barcode);
                //LogNet.log.Info(string.Format("打印标签 Label[{0}] Printer[{1}]", Common.config.DefaultPrintLabel, Common.config.PrinterName));
                var barcode = content.Values.ToArray();
                SaveRetrospect(labelBmp, barcode, content);
            }
            catch (Exception ex)
            {
                LogNet.log.Error("Extension_Printing", ex);
            }
        }
        string dir_Res = ConfigHelper.Config.Get("DirReelResult", ".\\ReelResult");
        string reelResultFileNameKey = ConfigHelper.Config.Get("FileNameKeyReelResult", "");
        /// <summary>
        /// 保存检测结果
        /// </summary>
        /// <param name="content"></param>
        void SaveResult(Dictionary<string, string> content)
        {
            //if (string.IsNullOrEmpty(dir_Res))
            //    return;
            //if(!Directory.Exists(dir_Res))
            //    Directory.CreateDirectory(dir_Res);
            //string filename = "";
            //if (string.IsNullOrEmpty(reelResultFileNameKey))
            //{
            //    filename = dir_Res + DateTime.Now.ToString() + ".csv";
            //}
            //else
            //{
            //    filename = dir_Res + content[reelResultFileNameKey] + ".csv";
            //}
            //StringBuilder sb = new StringBuilder();
            //sb.AppendLine("ReelID,PartNumber,Vendor,Lot,UserData1,UserData2,UserData3,UserData4,UserData5,InitialQuantity,MSDLevel,MSDInitialFloorTime ,MSDBagSealDate,MarketUsage,QuantityOverride,ShelfTime,SPMaterialName,WarningLimit,MaximumLimit,Comments,WarmupTime,StorageUnit,SubStorageUnit,LocationOverride,ExpirationDate,ManufacturingDate,PartClass,PSDOverride,AltPartNumber");
            //sb.AppendLine($"1,1005C,,,,,,,,2,,,,,1,,,,,,,SMT,,,,,,,");
            ////sb.AppendLine(string.Join(",", content.Keys.ToArray()));
            ////sb.AppendLine(string.Join(",", content.Values.ToArray()));
            //System.IO.File.WriteAllText(filename, sb.ToString(), Encoding.UTF8);
        }
        public delegate void CheckResultEventHandler(object sender, bool value);
        public static event CheckResultEventHandler Checkresult;
        public Dictionary<string, string> lastContent;

        private bool CompareContent(Dictionary<string, string> content)
        {
            if (lastContent != null)
            {
                return content.Count == lastContent.Count && !content.Except(lastContent).Any();
            }
            return false;

        }

        private void Extension_Printing(Dictionary<string, string> content)
        {
            try
            {
                LogNet.log.Info("打印内容:" + JsonConvert.SerializeObject(content));
                SaveResult(content);
                //Bitmap labelBmp = Common.labelEdit.PrintImage(Common.config.DefaultPrintLabel, content, out _);
                BLLCommon.labelEdit.PrintLast(BLLCommon.config.DefaultPrintLabel, BLLCommon.config.PrinterName, BLLCommon.config.PrintLandscape, content, out List<string> barcode);
                LogNet.log.Info(string.Format("打印标签 Label[{0}] Printer[{1}] Barcode[{2}]", BLLCommon.config.DefaultPrintLabel, BLLCommon.config.PrinterName, string.Join(",", barcode)));

                try
                {
                    // 确保目录存在
                    string directory = Path.GetDirectoryName(FilePath.CONFIG_Code_Value);
                    if (!Directory.Exists(directory))
                    {
                        Directory.CreateDirectory(directory);
                    }

                    // 覆盖文件内容(只保留最新日志)
                    File.WriteAllText(FilePath.CONFIG_Code_Value, string.Join("\r\n", barcode));
                }
                catch (Exception ex)
                {
                    LogNet.log.Error($"写入文件失败: {ex.Message}");
                }


                var bmp = BLLCommon.labelEdit.PrintImage(BLLCommon.config.DefaultPrintLabel, content, out _);
                if (bmp != null)
                {
                    Dictionary<string, string> paramMap = new Dictionary<string, string>();
                    foreach (string key in content.Keys)
                    {
                        paramMap.Add(key, content[key]);
                    }
                    paramMap.Add("cid", BLLCommon.config.CID + "_2");
                    _ = UnifiedDataHandler.PostSmfImageAsync(bmp, paramMap, bmp.Width, bmp.Height);
                    //_ = UnifiedDataHandler.PostSmfImageAsync(bmp, new Dictionary<string, string> { { "cid", BLLCommon.config.CID + "_2" } }, bmp.Width, bmp.Height);
                }
                bmp.Dispose();
                //SaveRetrospect(labelBmp, barcode);
                UnifiedDataHandler.RecordPrintNg(false, true, out string[] strarrys);
                if (BLLCommon.config.PrintCompletedClear)
                    BLLCommon.extension.Clear();
                lastContent = new Dictionary<string, string>(content);
            }
            catch (Exception ex)
            {
                LogNet.log.Error($"Extension_Printing", ex);
            }

        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            bool rtn = UserLoginWindow.Show();
            if (!rtn)
            {
                Close();
                return;
            }
            BLLCommon.SCMM = new();
            if (!BLL.Config.Backgrounder)
            {
                monitor = new();
                Application.AddMessageFilter(monitor);
                monitor.Timeout += Monitor_Timeout;
                monitor.Start(BLLCommon.config.OperateTimeout);
            }

            scanWork = new();
            scanWork.generals = new General(BLLCommon.config);
            BLLCommon.extension.KeySets += OnBllKeySet;
            BLLCommon.extension.GetUIKeyWords += Extension_GetUIKeyWords;

            BLLCommon.extension.Checks += Extension_Checks;
            scanWork.Check2s += Extension_Checks;

            LblVersion.Text = BLLCommon.config.SoftVersion;
            LblUserName.Text = BLLCommon.config.UserName;
            if (LblUserName.Text == "None user")
                LblUserName.Visible = false;
            BtnSet.Enabled = BLLCommon.config.UserLevel == UserLevel.Admin;

            FrmRetrospect.Print += Extension_Printing;
            UsrWorkMode.Printing += Extension_Printing;
            WebCallWork.PrintAiing += Extension_Printing;
            //扩展面板
            PnlExtension.Width = BLLCommon.config.ExtensionWidth;
            PnlExtension.Left = Width - PnlExtension.Width - 12;
            PicShow.Width = PnlExtension.Left - PicShow.Left - 6;
            BLLCommon.extension.Printing += Extension_Printing;
            BLLCommon.extension.SaveRetrospect += Extension_SaveRetrospect;
            BLLCommon.extension.LoadPanel(PnlExtension, BLLCommon.macroKey);

            //语言
            CboLanguage.Items.AddRange(Language.Name.ToArray());
            CboLanguage.SelectedText = BLLCommon.config.Language;
            BLLCommon.AutoGenRules = AutoGenRule.LoadFile();
            //if (BLLCommon.config.OpenMaximize) Maximize();
            this.StartPosition = FormStartPosition.Manual;

            // 获取主屏幕的分辨率
            Rectangle screenBounds = Screen.PrimaryScreen.WorkingArea;

            // 设置窗体位置为屏幕左边
            this.Location = new Point(0, 0);

            // 设置窗体大小为屏幕宽度的四分之三,高度为屏幕高度
            this.Size = new Size((int)(screenBounds.Width * 0.75), screenBounds.Height);

            if (CheckCamera() && CheckIOModule())
            {
                BtnStart.Enabled = true;
                if (BLLCommon.config.OpenStartWork)
                {
                    BtnStart.HoldPress = true;
                    scanWork.Open();
                }
            }
            else
            {
                BtnStart.Enabled = false;
            }
            changeBtnStartText();
        }

        private Dictionary<string, string> Extension_GetUIKeyWords()
        {
            return wpfControl.GetRecognitionData();
        }

        private void Extension_Checks(string text)
        {

            if (this.InvokeRequired)
            {
                this.Invoke(new Action(() => Extension_Checks(text)));
                return;
            }
            if (text == "1")
            {
                wpfControl.SetSkipButtonVisibility(true);
                return;
            }
            if (text == "2")
            {
                wpfControl.SetSkipButtonVisibility(false);
                return;
            }
            if (text == "OK")
            {
                wpfControl.SetResultOK();
            }
            else if (text == "等待中" || text == "Waiting" || text == "待機中")
            {
                wpfControl.SetResultText(text, "#FFCC00"); // 显示NG
            }
            else
            {
                wpfControl.SetResultNG(); // 显示NG
            }
        }

        private void OnBllKeySet(string templateName, string[] originalCode, Dictionary<string, string> key, bool hasMatch)
        {
            LogNet.log.Info($"OnBllKeySet templateName:{templateName}, hasMatch:{hasMatch}, key:" + JsonConvert.SerializeObject(key));
            wpfControl.templateName = templateName;
            // 1. 更新UI显示原始码
            wpfControl.UpdateOriginalCodeDisplay(originalCode);

            // 2. 更新识别数据
            wpfControl.UpdateMultipleRecognitionData(key);

            // 3. 显示匹配状态
            wpfControl.UpdateMatchStatus(hasMatch);
        }

        private void Generals_KeySets(string[] originalCode, Dictionary<string, string> key, bool hasMatch)
        {
            throw new NotImplementedException();
        }

        private void Monitor_Timeout(object sender, EventArgs e)
        {
            if (InvokeRequired)
            {
                Invoke(new EventHandler(Monitor_Timeout), sender, e);
            }
            else
            {
                //Hide();
                bool rtn = UserLoginWindow.Show();
                if (rtn)
                {
                    Show();
                    monitor.Start(BLLCommon.config.OperateTimeout);
                }
                else
                {
                    Close();
                }
            }
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            monitor?.Stop();
            BLLCommon.extension?.Dispose();
            //if (Common.config.IOLight == -1)
            //    Common.SerialPort.Close();
        }

        private void FrmMain_Activated(object sender, EventArgs e)
        {
            if (BLL.Config.Backgrounder) Hide();
        }

        private void CboLanguage_SelectedIndexChanged(object sender, EventArgs e)
        {
            return;
            if (BLLCommon.config.Language != CboLanguage.Text)
            {
                Language.LoadLanguage(CboLanguage.Text);
                BLLCommon.config.Language = CboLanguage.Text;
                BLLCommon.config.Save();
                changeBtnStartText();
                Language.SetLanguage(this);
                LanguageWwitchover.LoadLanguage(CboLanguage.Text);
                if (wpfMenu != null && wpfControl != null)
                {
                    wpfMenu.ApplyLanguage();
                    wpfControl.UpdateRight();
                }



            }
        }
        void changeBtnStartText()
        {
            if (BLLCommon.config.Language.Equals("English"))
            {
                BtnStart.Font = new Font("Arial", 14, FontStyle.Bold);

            }
            else
            {
                BtnStart.Font = new Font("微软雅黑", 14, FontStyle.Bold);
            }
            if (scanWork?.isRun ?? false)
            {
                BtnStart.Text = Language.Dialog("Exit", "退出");
            }
            else
            {
                BtnStart.Text = Language.Dialog("Start", "开始");
            }
        }


        #region 通过webservice触发
        public WebCodeAll[] WebTouchWork()
        {
            LogNet.log.Info("Web触发Work");
            scanWork.Scan();
            scanWork.TouchOff();
            return scanWork.GetWebCodeAll();
        }

        public WebCodeText[] WebTouchWork(string[] code)
        {
            LogNet.log.Info("Web触发Work code");
            scanWork.Scan(code);
            scanWork.TouchOff();
            return scanWork.GetWebCodeText();
        }
        #endregion

        #region 左侧菜单
        private void BtnStart_Click(object sender, EventArgs e)
        {
            if (BtnStart.HoldPress)
                scanWork.Open();
            else
                scanWork.Close();
            changeBtnStartText();
        }

        private void BtnRetrospect_Click(object sender, EventArgs e)
        {
            monitor.Pause = true;
            new FrmRetrospect().ShowDialog();
            monitor.Pause = false;
            WPF_Date_From wPF_Date_From = new WPF_Date_From();
            wPF_Date_From.Show();
        }

        private void BtnSet_Click(object sender, EventArgs e)
        {
            monitor.Pause = true;
            FrmSet set = new FrmSet();
            set.Width = PicShow.Width;
            set.Height = PicShow.Height;
            set.ShowDialog();
            monitor.Pause = false;
        }

        private void BtnAbout_Click(object sender, EventArgs e)
        {
            monitor.Pause = true;
            new FrmAbout().ShowDialog();
            monitor.Pause = false;
        }

        private void BtnTriggerIO_Click(object sender, EventArgs e)
        {
            LogNet.log.Info("按钮点击触发Work");
            Task.Run(() =>
            {
                scanWork.Scan();
                //scanWork.TouchOff();
            });
        }

        private void BtnMatchedName_Click(object sender, EventArgs e)
        {
            new FrmMatchingInfo((sender as FaceButton).Text, scanWork.workCodeKeyword).ShowDialog();
        }

        #endregion

        public DialogResult ShowWaittingDialog()
        {
            Common.frmWaitting = new FrmWaitting();
            return Common.frmWaitting.ShowDialog();
        }
        public void CloseWaittingDialog()
        {
            if (Common.frmMain.InvokeRequired)
            {
                if (Common.frmWaitting.Created)
                {
                    try
                    {
                        Common.frmMain.Invoke(delegate ()
                        {
                            CloseWaittingDialog();
                        });
                    }
                    catch { }
                }
                ;
                return;
            }
            Common.frmWaitting.Close();
        }
        public void SetWaittingMsg(string msg, int keepsec = 3)
        {
            if (Common.frmMain.InvokeRequired)
            {
                Common.frmMain.Invoke(delegate ()
                {
                    SetWaittingMsg(msg);
                });
                return;
            }
            //BLLCommon.SCMM.ShowMsg(msg, keepsec, msgType.INFO);
            Common.frmWaitting.SetMessage(msg);
            Application.DoEvents();
        }

        public void DrawTextForm(Dictionary<string, string> valuePairs)
        {
            //
            if (Common.frmMain.InvokeRequired)
            {
                Common.frmMain.Invoke(delegate ()
                {
                    DrawTextForm(valuePairs);
                });
                return;
            }
            //BLLCommon.SCMM.ShowMsg(msg, 3, msgType.INFO);
            //Common.frmWaitting.SetMessage(msg);
            BLLCommon.extension.DrawTextBackground(valuePairs);
            Application.DoEvents();
        }

        private void LblVersion_Click(object sender, EventArgs e)
        {
            //var HCEditor = new HCEditor();

            //if (Config.Get<int>("HB_ENABLE") >= 1)
            //    new HBEditor();

            ConfigHelper.AdvanceConfigForm.ShowEditDialog(this, true);
        }
    }
}