ScanWork.cs 42.3 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
using Asa.FaceControl;
using BLL;
using MemoryRead;
using Model;
using OnlineStore.Common.util;
using SmartScan.SetControl.WPF;
using SmartScan.SetControl.WPF.Model;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
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 static BLL.BLLCommon;
using static SmartScan.SetControl.WPF.Model.NeoAlertBox;

namespace SmartScan
{
    public class ScanWork
    {
        public bool isRun = false;
        private bool isTouch = false;
        private readonly FacePictureBox picShow;
        private readonly FaceButton btnMatchedName;
        //private readonly System.Windows.Forms.Panel wpfImagePanel;
        public List<CameraVisionLib.Model.BarcodeInfo> workCodeInfo;
        public Dictionary<string, string> workCodeKeyword;
        public string[] originalCodeText;
        private bool[] originalCodeIsUsed;

        //bool falg = true;
        public General generals;

        public ScanWork()
        {
            picShow = (FacePictureBox)Common.frmMain.Controls["PicShow"];
            btnMatchedName = (FaceButton)Common.frmMain.Controls["BtnMatchedName"];
            //wpfImagePanel = Common.frmMain.Controls.Find("wpf_image", true)[0] as System.Windows.Forms.Panel;

        }

        private void Extension_Checks(string text)
        {
            throw new NotImplementedException();
        }

        public void Open()
        {
            isRun = true;
            isTouch = false;
            Common.frmMain.Controls["BtnSet"].Visible = false;
            Common.frmMain.Controls["BtnRetrospect"].Visible = false;
            Common.frmMain.Controls["BtnAbout"].Visible = false;
            Common.frmMain.Controls["BtnTriggerIO"].Visible = true;
            LogNet.log.Info("Work Start");

            if (BLLCommon.config.EnabledCamera)
                Camera.Open();

            if (BLLCommon.config.TriggerOpenLight)  //触发时才打开光源
                BLLCommon.lightSource?.TurnOff();
            else
                BLLCommon.lightSource?.TurnOn();
        }

        public void Close()
        {
            isRun = false;
            Common.frmMain.Controls["BtnSet"].Visible = true;
            Common.frmMain.Controls["BtnRetrospect"].Visible = true;
            Common.frmMain.Controls["BtnAbout"].Visible = true;
            Common.frmMain.Controls["BtnTriggerIO"].Visible = false;
            LogNet.log.Info("Work Stop");

            if (BLLCommon.config.EnabledCamera)
                Camera.Close();

            BLLCommon.lightSource?.TurnOff();
        }

        public void TouchOff()
        {
            isTouch = false;
        }

        private readonly object lockObject = new object();

        static System.Diagnostics.Stopwatch reckontime = new System.Diagnostics.Stopwatch();
        public bool bendi = false;
        protected virtual void CheckText(string text)
        {
            extension.Check(text);
        }
        public delegate void Check2(string text);
        public event Check2 Check2s;
        public void Scan(bool fromlocalfile = false)
        {
            //此段代码加锁是因为,客户在连续点击识别设备按钮时,线程会同时生成rid=123并且rid赋值是重复的123123
            //在测试时也遇到这个情况,但只成功复现了一次;故加锁。
            lock (lockObject)
            {

                if (!isRun) return;
                if (isTouch) return;

                if (BLLCommon.config.CheckFunction)
                {
                    Check2s?.Invoke("1");
                }
                isTouch = true;
                btnMatchedName.Invoke(delegate ()
                {

                    if (!BLL.Config.Backgrounder)
                        btnMatchedName.Visible = false;
                    BLLCommon.extension.Clear();
                });

                // LoadingScreen.Instance.Show("拍照中", "请稍候...");
                //Common.frmMain.SetWaittingMsg(Language.Dialog("MaterialScanning"));//拍照识别...
                var t = Task.Run(() =>
                {
                    //Common.frmMain.Showlogs("运行中");
                    reckontime.Restart();
                    try
                    {

                        //Common.frmMain.SetWaittingMsg(Language.Dialog("MaterialScanning"));//拍照识别...
                        workCodeInfo = new();
                        workCodeKeyword = new(StringComparer.OrdinalIgnoreCase);
                        originalCodeText = null;
                        originalCodeIsUsed = null;
                        LoadingScreen.Instance.Hide();

                        if (!GetCodeInfo(fromlocalfile))
                        {
                            isTouch = false;
                            Common.frmMain.CloseWaittingDialog();
                            return;
                        }

                        string title = SmartScan.SetControl.WPF.LanguageWwitchover.Dialog("MaterialTemplateMatching", "匹配中");
                        string subtitle = SmartScan.SetControl.WPF.LanguageWwitchover.Dialog("PleaseWaiting", "请稍候...");
                        LoadingScreen.Instance.Show(title, subtitle);

                        Common.frmMain.Invoke(delegate ()
                        {
                            AddCodeCenter();
                        });
                        LogNet.log.Info($"获取图片耗时{reckontime.ElapsedMilliseconds}ms");
                        //Common.frmMain.SetWaittingMsg(Language.Dialog("MaterialTemplateMatching"),5);//模版匹配...
                        reckontime.Restart();
                        //Common.frmMain.Showlogs("OCR识别中请稍后");
                        Common.frmMain.Showlogs("");
                        LogNet.log.Info($"WaitLabelRecheck:{WaitLabelRecheck},CheckFunction:{BLLCommon.config.CheckFunction}");
                        if (WaitLabelRecheck && BLLCommon.config.CheckFunction)
                        {
                            LoadingScreen.Instance.Hide();
                            originalCodeText = Camera.GetBarCodeText(workCodeInfo);
                            // 检查条码内容是否与文件中的内容匹配
                            bool isMatched = CheckCodeWithFileContent(originalCodeText, out List<string> matchedTexts);
                            if (isMatched)
                            {
                                isMatched = Request_API_C2(matchedTexts);
                            }

                            Dictionary<string, string> lastKey = BLLCommon.extension.GetUIKeywords();
                            if (lastKey == null)
                                lastKey = new Dictionary<string, string>(workCodeKeyword);
                            else
                                lastKey = new Dictionary<string, string>(lastKey, StringComparer.OrdinalIgnoreCase);
                            //nexim对接
                            if (isMatched && (!DidRegisterValidate(lastKey, out string errmsg)))
                            {
                                isMatched = false; 
                                LogNet.log.Info("DidRegisterValidate error ,isMatched = false"); 
                            }

                             if (isMatched)
                            {
                                Check2s?.Invoke("2");
                                // Common.frmMain.wpfControl.SetResultOK();
                                Check2s?.Invoke("OK");
                                WaitLabelRecheck = false;
                            }
                            else
                            {
                                Check2s?.Invoke("NG");

                            }
                        }
                        else
                        {

                            string text =LanguageWwitchover.Dialog("Waiting", "等待中"); 
                            Check2s?.Invoke(text);
                            bool hasMatch = MatchingTemplate(out string templateName);
                            LogNet.log.Info($"模板匹配耗时{reckontime.ElapsedMilliseconds}ms");
                            reckontime.Restart();

                            //Common.frmMain.SetWaittingMsg(Language.Dialog("MaterialProcessing"),5);//计算结果...
                            Common.frmMain.Invoke(delegate ()
                            {
                                SetKey(hasMatch, templateName);
                            });

                            Common.frmMain.Showlogs("");
                            isTouch = false;
                            LogNet.log.Info("Work scan is done");
                            LogNet.log.Info($"渲染控件耗时{reckontime.ElapsedMilliseconds}ms");

                        }


                    }
                    catch (Exception ex)
                    {
                        LogNet.log.Error("Scan", ex);
                    }
                    finally
                    {
                        bendi = false;
                        isTouch = false;
                        Common.frmMain.CloseWaittingDialog();
                    }
                });
                Common.frmMain.Invoke(delegate ()
                {
                    //Common.frmMain.ShowWaittingDialog();
                });
            }
        }

        private bool DidRegisterValidate(Dictionary<string, string> content, out string errmsg)
        {
            errmsg = "";
            if (!BLLCommon.neximApiUtils.IsEnalbe())
            {
                return true;
            }
            try
            {
                string pn = BLLCommon.neximApiUtils.getReelInfo(content, "PN");
                string msg;
                bool result;
                Dictionary<string, object> pmData = BLLCommon.neximApiUtils.getPartMasters(pn, out msg);
                if (!string.IsNullOrEmpty(msg))
                {
                    LogNet.log.Error($"getPartMasters failed, pn={pn}, msg={msg},开始注册PN");

                    result = BLLCommon.neximApiUtils.postPartMasters(content, out msg);
                    if (result)
                    {
                        LogNet.log.Info($"postPartMasters OK, pn={pn}");
                    }
                    else
                    {
                        LogNet.log.Error($"getPartMasters failed, pn={pn}, msg={msg}");
                        errmsg = msg; 
                        MessageboxNeo.Show("Register PartMasters Failure Notice", errmsg, "NEO SCAN", false );
                        return false;
                    }
                }
                else
                {
                    string reelId = BLLCommon.neximApiUtils.getReelInfo(content, "RI");
                    //获取did信息,获取成功直接返回
                    Dictionary<string, object> didData = BLLCommon.neximApiUtils.getDid(reelId, out msg);
                    LogNet.log.Error($"getPartMasters OK, getDid OK,直接返回 true");
                    if (string.IsNullOrEmpty(msg))
                    {
                        return true;
                    }
                }

                if (BLLCommon.neximApiUtils.registerNewDid(content, pmData, out msg))
                {
                    return true;
                }
                else
                {
                    errmsg = msg;
                    //Register Failure Notice
                    MessageboxNeo.Show("Register Failure Notice", errmsg, "NEO SCAN", false );
                    return false;
                }

            }
            catch (Exception ex)
            {
                LogNet.log.Info("DidRegisterValidate" + ex.ToString());
            }
            return false;
        }
        private bool Request_API_C2(List<string> matchedTexts)
        {
            string url = config.HttpLabelReport.Trim();

            if (string.IsNullOrWhiteSpace(url))
                return true;

            var keylist = matchedTexts.Select(x => new { Content = x }).ToList();

            var errmsg = "";
            Dictionary<string, object> dic = null;

            string json = Http.PostJson(url, null, keylist);
            if (json == "")
            {
                LogUtil.info("Api C2 response empty error");
                return false;
            }
            JavaScriptSerializer serializer = new();
            try
            {
                var raw = (Dictionary<string, object>)serializer.DeserializeObject(json);
                // 重新建一个忽略大小写的字典,把数据拷进去
                dic = new Dictionary<string, object>(raw, StringComparer.OrdinalIgnoreCase);
            }
            catch
            {
                errmsg = "Api C2 parse error:\r\n" + json;
                LogUtil.info("Api C2 parse error:\r\n" + json);
                return MessageboxNeo.Show("BoxReelIDInfoMaintain", errmsg, "NEO SCAN", true);
            }

            if (!dic.TryGetValue("ERRORCODE", out object value))
            {
                LogUtil.info("Api C2 return data error:\r\n" + json);
                errmsg = "Api C2 return data error:\r\n" + json;
                return MessageboxNeo.Show("BoxReelIDInfoMaintain", errmsg, "NEO SCAN", true);
            }

            if (Convert.ToInt32(value) != 0)
            {
                LogUtil.info("Api C2 parse error:\r\n" + dic["MSG"].ToString());
                errmsg = "Api C2 parse error:\r\n" + dic["MSG"].ToString();
                return MessageboxNeo.Show("BoxReelIDInfoMaintain", errmsg, "NEO SCAN", true);
            }

            return true;
        }

        // 修改方法定义
        private bool CheckCodeWithFileContent(string[] codeTexts, out List<string> matchedCodeText)
        {
            matchedCodeText = new List<string>();
            if (codeTexts == null || codeTexts.Length == 0)
            {
                LogNet.log.Warn("条码文本数组为空,无法进行匹配");
                return false;
            }

            try
            {
                // 检查文件是否存在
                if (!File.Exists(FilePath.CONFIG_Code_Value))
                {
                    LogNet.log.Warn($"匹配文件不存在: {FilePath.CONFIG_Code_Value}");
                    return false;
                }

                // 读取文件内容
                string fileContent = File.ReadAllText(FilePath.CONFIG_Code_Value);
                List<string> lines = fileContent.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToList();
                LogNet.log.Info("扫描到条码:" + string.Join(",", codeTexts));
                LogNet.log.Info("在以下条码中匹配:" + fileContent);
                // 检查文件内容是否包含任一条码文本
                foreach (string ln in lines.ToArray())
                {
                    foreach (string codeText in codeTexts)
                    {
                        if (ln.Trim() == codeText.Trim())
                        {
                            LogNet.log.Info($"条码 {codeText} 在文件中找到匹配");
                            lines.Remove(ln);
                            matchedCodeText.Add(codeText.Trim());
                        }
                    }
                }
                if (lines.Count > 0)
                {
                    LogNet.log.Info("以下条码文件中均未找到匹配:" + string.Join(",", lines.ToArray()));
                    return false;
                }
                else
                    return true;
            }
            catch (Exception ex)
            {
                LogNet.log.Error($"检查文件内容时出错: {ex.Message}");
                return false;
            }
        }
        public void Scan(string[] code)
        {
            try
            {
                if (!isRun) return;
                if (isTouch) return;

                if (!BLL.Config.Backgrounder)
                    btnMatchedName.Visible = false;
                BLLCommon.extension.Clear();
                workCodeInfo = new();
                workCodeKeyword = new(StringComparer.OrdinalIgnoreCase);
                originalCodeText = code;
                originalCodeIsUsed = null;

                var hasMatch = MatchingTemplate(out string templateName);
                SetKey(hasMatch, templateName);

                isTouch = true;
                LogNet.log.Info("Work scan code is done");
            }
            catch (Exception ex)
            {
                LogNet.log.Error("Scan", ex);
            }
        }

        public object[] SaveCodeInfo()
        {
            object[] obj = null;
            if (workCodeInfo == null)
                return obj;

            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;
            }
            return obj;
        }

        public WebCodeAll[] GetWebCodeAll()
        {
            WebCodeAll[] str = new WebCodeAll[workCodeInfo.Count];
            for (int i = 0; i < str.Length; i++)
            {
                str[i] = new()
                {
                    Text = workCodeInfo[i].Text,
                    CodeType = workCodeInfo[i].CodeType,
                    CenterX = workCodeInfo[i].Center.X,
                    CenterY = workCodeInfo[i].Center.Y,
                    Angle = workCodeInfo[i].Angle,
                    Width = workCodeInfo[i].Size.Width,
                    Height = workCodeInfo[i].Size.Height,
                    IsUsed = originalCodeIsUsed[i]
                };
            }
            return str;
        }

        public WebCodeText[] GetWebCodeText()
        {
            WebCodeText[] str = new WebCodeText[originalCodeText.Length];
            for (int i = 0; i < str.Length; i++)
            {
                str[i] = new()
                {
                    Text = originalCodeText[i],
                    IsUsed = originalCodeIsUsed[i]
                };
            }
            return str;
        }
        /// <summary>
        /// 扫描图像处理逻辑
        /// </summary>
        private void ScanCodeImage()
        {
            if (!isRun) return;
            if (isTouch) return;
            isTouch = true;

            btnMatchedName.Invoke(delegate ()
            {
                if (!BLL.Config.Backgrounder)
                    btnMatchedName.Visible = false;
                BLLCommon.extension.Clear();
            });

            //Common.frmMain.SetWaittingMsg(Language.Dialog("MaterialScanning")); //拍照识别...

            var t = System.Threading.Tasks.Task.Run(() =>
            {
                reckontime.Restart();
                try
                {
                    //Common.frmMain.SetWaittingMsg(Language.Dialog("MaterialScanning")); //拍照识别...
                    workCodeInfo = new();
                    workCodeKeyword = new(StringComparer.OrdinalIgnoreCase);

                    if (!GetCodeInfo())
                    {
                        isTouch = false;
                        Common.frmMain.CloseWaittingDialog();
                        return;
                    }

                    Common.frmMain.Invoke(delegate ()
                    {
                        AddCodeCenter();
                    });

                    LogNet.log.Info($"获取图片耗时{reckontime.ElapsedMilliseconds}ms");
                }
                catch (Exception ex)
                {
                    LogNet.log.Error($"扫描处理异常:{ex.Message}");
                    isTouch = false;
                    Common.frmMain.CloseWaittingDialog();
                }
            });
        }
        public bool isstart = false;
        private bool GetCodeInfo(bool fromlocalfile = false)
        {
            LogNet.log.Info("Work GetCodeInfo");

            if (BLLCommon.config.EnabledCamera && !fromlocalfile)// && isstart==true)
            {
                LogNet.log.Info("1");
                if (BLLCommon.config.TriggerOpenLight)
                {
                    BLLCommon.lightSource.TurnOn();
                    System.Threading.Thread.Sleep(100);  //光源打开有一个由暗变亮的过程
                }
                LogNet.log.Info("2");
                List<Bitmap> image = new List<Bitmap>(Camera.CaptureAndGetCode(out workCodeInfo));
                LogNet.log.Info("image" + image.Count);
                LogNet.log.Info("image[0]" + image[0]);
                if (image.Count > 0 && image[0] != null)
                {
                    LogNet.log.Info("3");
                    BLLCommon.mateEdit.CurrntBitmap = WebCallWork.DeepClone(image[0]);
                    Common.frmMain.Invoke(delegate ()
                    {
                        // 使用WPF控件显示图片
                        if (!BLL.Config.Backgrounder)
                        {//在图片画出识别的二维码

                            picShow.Image = image[0];
                            DisplayBitmapInWpfControl(image[0]);
                        }

                        if (BLLCommon.mateEdit.CurrntBitmap != null)
                        {
                            _ = UnifiedDataHandler.PostSmfImageAsync(
                                BLLCommon.mateEdit.CurrntBitmap,
                                new Dictionary<string, string> { { "cid", BLLCommon.config.CID + "_1" } },
                                BLLCommon.mateEdit.CurrntBitmap.Width,
                                BLLCommon.mateEdit.CurrntBitmap.Height);
                        }
                    });
                }
                else
                {
                    LogNet.log.Info("image[1]");
                    return false;
                }


                if (BLLCommon.config.TriggerOpenLight)
                    BLLCommon.lightSource.TurnOff();
                return true;
            }
            else
            {
                Common.frmMain.Invoke(delegate ()
                {
                    if (!BLL.Config.Backgrounder)
                        picShow.Image?.Dispose();
                    BLLCommon.mateEdit.CurrntBitmap?.Dispose();
                });
                string filename = "";
                Common.frmMain.Invoke(delegate ()
                {
                    OpenFileDialog dlg = new() { Filter = "图片文件|*.jpg;*.png;*.bmp;*.jpeg" };
                    DialogResult dr = dlg.ShowDialog();
                    filename = dlg.FileName;
                });
                if (string.IsNullOrEmpty(filename))
                    return false;
                Bitmap bmp = null;
                bmp = ObjConversion.ReadImageFile(filename);
                workCodeInfo = Camera.GetBarCode(bmp);

                //在图片画出识别的二维码
                //DrawCodeIndex(bmp, workCodeInfo);



                Common.frmMain.Invoke(delegate ()
                {
                    if (!BLL.Config.Backgrounder)
                    {
                        DisplayBitmapInWpfControl(bmp);
                        picShow.Image = bmp;
                    }

                    BLLCommon.mateEdit.CurrntBitmap = bmp;
                });
                return true;
            }

            if (workCodeInfo.Count == 0 && !BLL.Config.Backgrounder)
            {
                string text = Language.Dialog(LanguageDialogKey.CODE_COUNT);
                new FaceMessageBox("", text, MessageBoxButtons.OK).ShowDialog(Common.frmMain);
            }

            System.Windows.Forms.Application.DoEvents();
            LogNet.log.Info("条码个数:" + workCodeInfo.Count);
        }

        public static void DrawCodeIndex(Bitmap bmp, List<CameraVisionLib.Model.BarcodeInfo> workCodeInfo)
        {
            int contenI = 1;
            workCodeInfo.ForEach(info =>
            {
                using (Graphics g = Graphics.FromImage(bmp))
                {
                    string str = contenI.ToString();
                    System.Drawing.Font font = new System.Drawing.Font("Arial", 60, System.Drawing.FontStyle.Bold);
                    SizeF sz = g.MeasureString(str, font);

                    // 为了让文字中心落在 info.Center 上
                    RectangleF rc = new RectangleF(
                        info.Center.X - sz.Width / 4,
                        info.Center.Y - sz.Height / 4,
                        sz.Width, sz.Height);
                    // 1. 画白色描边
                    using (GraphicsPath gp = new GraphicsPath())
                    {
                        gp.AddString(str,
                                     font.FontFamily,
                                     (int)font.Style,
                                     font.SizeInPoints,    // 用 Point 单位
                                     rc.Location,
                                     StringFormat.GenericDefault);

                        // 描边宽度可调
                        using (Pen pen = new Pen(System.Drawing.Color.White, 10f))
                        {
                            pen.LineJoin = LineJoin.Round;
                            g.DrawPath(pen, gp);
                        }

                        // 2. 填充红色字
                        using (Brush brush = new SolidBrush(System.Drawing.Color.Red))
                        {
                            g.FillPath(brush, gp);
                        }
                    }
                }
                contenI++;

            });
        }

        //根据中心点取四个角的坐标
        //kmon
        //2025-6-25
        //private PointF[] GetRotatedRectanglePoints(PointF center, float length, float width, float angle)
        //{
        //    // 将角度转换为弧度
        //    float radians =(float) (angle * (Math.PI / 4));
        //    float halfLength = length / 2;
        //    float halfWidth = width / 2;

        //    PointF[] points = new PointF[4];
        //    points[0] = new PointF(center.X + halfLength, center.Y - halfWidth); // 左上角
        //    points[1] = new PointF(center.X + halfLength, center.Y + halfWidth); // 右下角
        //    points[2] = new PointF(center.X - halfLength, center.Y + halfWidth); // 左下角
        //    points[3] = new PointF(center.X - halfLength, center.Y - halfWidth); // 右上角

        //    // 应用旋转变换
        //    PointF[] rotatedPoints = new PointF[4];
        //    for (int i = 0; i < points.Length; i++)
        //    {
        //        float dx = points[i].X - center.X;
        //        float dy = points[i].Y - center.Y;
        //        float newX = center.X + (dx * (float)Math.Cos(radians) - dy * (float)Math.Sin(radians));
        //        float newY = center.Y + (dx * (float)Math.Sin(radians) + dy * (float)Math.Cos(radians));
        //        rotatedPoints[i] = new PointF(newX, newY);
        //    }
        //    return rotatedPoints;
        //}
        // 新增方法:将Bitmap显示在WPF控件中
        private void DisplayBitmapInWpfControl(Bitmap bitmap)
        {
            try
            {
                if (bitmap == null)
                    return;

                // 确保在UI线程上执行,同时简化嵌套的Invoke调用
                Common.frmMain.BeginInvoke(new Action(() =>
                {
                    try
                    {
                        var imageTest = Common.frmMain.GetImageViewer();
                        if (imageTest != null && imageTest.imageBox != null)
                        {
                            Console.WriteLine("正在加载图片到WPF控件...");
                            // 释放旧图像(如果有)
                            if (imageTest.imageBox.Image != null)
                            {
                                imageTest.imageBox.Image.Dispose();
                            }
                            // 创建新图片的副本以避免资源冲突
                            Bitmap bitmapCopy = new Bitmap(bitmap);


                            // 处理条码中心点
                            if (workCodeInfo != null && workCodeInfo.Count > 0)
                            {
                                // 获取中心点
                                System.Drawing.PointF[] centers = workCodeInfo
                                    .Where(info => info.Center != null)
                                    .Select(info => info.Center)
                                    .ToArray();
                                if (centers.Length > 0)
                                {
                                    //Console.WriteLine($"绘制 {centers.Length} 个条码中心点");
                                    // 使用新的直接绘制方法
                                    //imageTest.DrawCenterPointsOnImage(centers);

                                    DrawCodeIndex(bitmapCopy, workCodeInfo);
                                }

                            }
                            imageTest.imageBox.Image = bitmapCopy;

                            // 适应屏幕显示
                            imageTest.FitToScreen();



                        }
                        else
                        {
                            Console.WriteLine("Imagetest为空,无法显示图片");
                        }
                    }
                    catch (Exception innerEx)
                    {
                        Console.WriteLine($"显示图片内部错误: {innerEx.Message}\n{innerEx.StackTrace}");
                    }
                }));

            }
            catch (Exception ex)
            {
                LogNet.log.Error($"显示图片到WPF控件失败: {ex.Message}", ex);
            }
        }
        //private bool GetCodeInfo()
        //{
        //    LogNet.log.Info("Work GetCodeInfo");

        //    if (BLLCommon.config.EnabledCamera)
        //    {
        //        if (BLLCommon.config.TriggerOpenLight)
        //        {
        //            BLLCommon.lightSource.TurnOn();
        //            System.Threading.Thread.Sleep(100);  //光源打开有一个由暗变亮的过程
        //        }
        //        List<Bitmap> image = new List<Bitmap>(Camera.CaptureAndGetCode(out workCodeInfo));
        //        if (image.Count > 0 && image[0]!=null)
        //        {
        //            BLLCommon.mateEdit.CurrntBitmap = WebCallWork.DeepClone(image[0]);
        //            if (!BLL.Config.Backgrounder) 
        //                picShow.Image = image[0];
        //            if (BLLCommon.mateEdit.CurrntBitmap!=null)
        //            _ = UnifiedDataHandler.PostSmfImageAsync(BLLCommon.mateEdit.CurrntBitmap, new Dictionary<string, string> { { "cid", BLLCommon.config.CID + "_1" } }, BLLCommon.mateEdit.CurrntBitmap.Width, BLLCommon.mateEdit.CurrntBitmap.Height);
        //        }else
        //            return false;

        //        if (BLLCommon.config.TriggerOpenLight)
        //            BLLCommon.lightSource.TurnOff();
        //        return true;
        //    }
        //    else
        //    {
        //        Common.frmMain.Invoke(delegate ()
        //        {
        //            if (!BLL.Config.Backgrounder)
        //                picShow.Image?.Dispose();
        //            BLLCommon.mateEdit.CurrntBitmap?.Dispose();
        //        });
        //        string filename = "";
        //        Common.frmMain.Invoke(delegate ()
        //        {
        //            OpenFileDialog dlg = new() { Filter = "图片文件|*.jpg;*.png;*.bmp;*.jpeg" };
        //            DialogResult dr = dlg.ShowDialog();
        //            filename = dlg.FileName;
        //        });
        //        if (string.IsNullOrEmpty(filename))
        //            return false;
        //        Bitmap bmp = null;
        //        bmp = ObjConversion.ReadImageFile(filename);
        //        workCodeInfo = Camera.GetBarCode(bmp);
        //        Common.frmMain.Invoke(delegate ()
        //        {
        //            if (!BLL.Config.Backgrounder)
        //                picShow.Image = bmp;
        //            BLLCommon.mateEdit.CurrntBitmap = bmp;
        //        });
        //        return true;
        //    }

        //    if (workCodeInfo.Count == 0 && !BLL.Config.Backgrounder)
        //    {
        //        string text = Language.Dialog(LanguageDialogKey.CODE_COUNT);
        //        new FaceMessageBox("", text, MessageBoxButtons.OK).ShowDialog(Common.frmMain);
        //    }

        //    Application.DoEvents();
        //    LogNet.log.Info("条码个数:" + workCodeInfo.Count);
        //}

        private void AddCodeCenter()
        {
            LogNet.log.Info("Work AddCodeCenter");
            if (!BLL.Config.Backgrounder)
                picShow.CodeCenterClear();
            if (workCodeInfo.Count == 0) return;
            PointF[] center = new PointF[workCodeInfo.Count];
            for (int i = 0; i < workCodeInfo.Count; i++)
                center[i] = workCodeInfo[i].Center;
            if (!BLL.Config.Backgrounder)
                picShow.AddCodeCenter(center);
            System.Windows.Forms.Application.DoEvents();


        }

        public bool MatchingTemplate(out string templateName)
        {
            templateName = "";
            LogNet.log.Info("Work MatchingTemplate");
            //没有条码也继续进行模板匹配
            //if (workCodeInfo.Count == 0) return false;
            originalCodeText = Camera.GetBarCodeText(workCodeInfo);

            bool rtn = BLLCommon.mateEdit.MatchingTemplate(workCodeInfo, BLLCommon.config.DefaultMaterialName, false, out string mateName, out workCodeKeyword, out AMatch aMatch);
            BLL.MatchAnalysis.ShowResult();
            templateName = mateName;
            Common.frmMain.Invoke(delegate ()
            {
                if (rtn)
                {
                    LogNet.log.Info("模板匹配 " + mateName + ",关键字个数 " + workCodeKeyword.Count);
                    if (!BLL.Config.Backgrounder)
                    {
                        btnMatchedName.Visible = true;
                        btnMatchedName.Text = mateName;

                    }
                }
                else
                {
                    LogNet.log.Info("没有匹配到模板");
                    if (!BLL.Config.Backgrounder)
                    {
                        string text = Language.Dialog("MaterialTemplateNoMatch");
                        NeoAlertBox.Show("", text, AlertType.Warning, "NEO SCAN", true);

                        //var fm = new FaceMessageBox("", text, MessageBoxButtons.OK);
                        //fm.TopMost = true;
                        //fm.ShowDialog(Common.frmMain);
                    }
                }
            });
            return rtn;
        }
        public bool Ispring = true;
        public bool WaitLabelRecheck = false;
        public void SetKey(bool hasMatch, string templateName)
        {
            LogNet.log.Info("Work SetKey hasMatch:" + hasMatch);
            //if (workCodeKeyword.Count == 0){ return;}
            //if(hasMatch)
            Ispring = true;
            bool a = BLLCommon.extension.SetKey(templateName, originalCodeText, workCodeKeyword, hasMatch, out _);
            LoadingScreen.Instance.Hide();
            Common.frmMain.Showlogs("");
            // 通过检查结果状态来判断是否需要打印
            if (!a)
            {
                Check2s?.Invoke("NG");
            }

            // 检查结果是否为"等待中"/"Waiting"/"待機中",以判断是否是第一次拍照
            if (BLLCommon.extension.labelText != null && a)
            {
                string status = BLLCommon.extension.labelText;
                WaitLabelRecheck = (status == "等待中" || status == "Waiting" || status == "待機中");
            }
            if (WaitLabelRecheck && BLLCommon.config.AutoPrint)
            {
                if (workCodeKeyword.Any(a => a.Value.StartsWith("<OCR>")))
                {
                    BLLCommon.extension.DrawTextBackground(workCodeKeyword);
                    bool results = NeoAlertBox.Show("", Language.Dialog("Using_OCR_Result", "是否使用OCR识别结果?"), AlertType.Warning, "NEO SCAN", true);
                    //FrmDrawText frmDraw = new FrmDrawText();
                    if (results == true)
                    {
                        Dictionary<string, string> pairs = workCodeKeyword.ToDictionary(val => val.Key,
                            val => val.Value.StartsWith("<OCR>") ? val.Value.Replace("<OCR>", "") : val.Value
                            );
                        if (!a)
                        {

                        }
                        else
                        {
                            if (bendi)
                            {                 
                                string text = LanguageWwitchover.Dialog("NeedPrinter", "是否打印?");
                                bool result1 = NeoAlertBox.Show("", text, AlertType.Warning, "NEO SCAN", true);
                             
                                if (result1)
                                {
                                    //打印
                                    BLLCommon.extension.Print(hasMatch, pairs);
                                }
                            }
                            else
                            {
                                if (hasMatch)
                                    //打印
                                    BLLCommon.extension.Print(hasMatch, pairs);
                            }

                        }

                    }
                }
                else
                {

                    if (bendi)
                    { 
                        string text = LanguageWwitchover.Dialog("NeedPrinter", "是否打印?");
                        bool result1 = NeoAlertBox.Show("", text, AlertType.Warning, "NEO SCAN", true);
                        if (result1)
                        {
                            BLLCommon.extension.Print(hasMatch, workCodeKeyword);
                        }
                    }
                    else
                    {
                        if (hasMatch)
                            BLLCommon.extension.Print(hasMatch, workCodeKeyword);
                    }
                    //打印



                }
                if (BLLCommon.config.PromptAfterPrinting && !BLL.Config.Backgrounder)
                {
                    string text = Language.Dialog("SelectPrintContent");
                    new FaceMessageBox("", text, MessageBoxButtons.OK).ShowDialog();
                }
                Ispring = true;
            }
            //else
            //{
            //    if (!a)
            //    {

            //    }
            //    else
            //    {
            //        string YU = BLLCommon.config.Language;
            //        bool result = false;
            //        if (YU == "English")
            //        {
            //            result = NeoAlertBox.Show("", "Identified content is incomplete. Continue printing anyway?", AlertType.Warning, "NEO SCAN", true);
            //        }
            //        else if (YU == "日语")
            //        {
            //            result = NeoAlertBox.Show("", "認識内容が不完全です。印刷を続けますか?", AlertType.Warning, "NEO SCAN", true);
            //        }
            //        else
            //        {
            //            result = NeoAlertBox.Show("", "识别的内容不完整,是否继续打印?", AlertType.Warning, "NEO SCAN", true);
            //        }
            //        if (result)
            //        {
            //            if (workCodeKeyword.Any(a => a.Value.StartsWith("<OCR>")))
            //            {
            //                BLLCommon.extension.DrawTextBackground(workCodeKeyword);
            //                //FrmDrawText frmDraw = new FrmDrawText();
            //                //if (frmDraw.ShowDialog() == DialogResult.OK)
            //                //{
            //                Dictionary<string, string> pairs = workCodeKeyword.ToDictionary(val => val.Key,
            //                    val => val.Value.StartsWith("<OCR>") ? val.Value.Replace("<OCR>", "") : val.Value
            //                    );
            //                //打印
            //                BLLCommon.extension.Print(hasMatch, pairs);
            //                //}
            //            }
            //            else
            //            {
            //                if (bendi)
            //                {
            //                    bool result1 = false;
            //                    if (YU == "English")
            //                    {
            //                        result1 = NeoAlertBox.Show("", "Whether to print or not?", AlertType.Warning, "NEO SCAN", true);
            //                    }
            //                    else if (YU == "日语")
            //                    {
            //                        result1 = NeoAlertBox.Show("", "印刷しますか?", AlertType.Warning, "NEO SCAN", true);
            //                    }
            //                    else
            //                    {
            //                        result1 = NeoAlertBox.Show("", "是否打印?", AlertType.Warning, "NEO SCAN", true);
            //                    }
            //                    if (result1)
            //                    {
            //                        BLLCommon.extension.Print(hasMatch, workCodeKeyword);
            //                    }
            //                }
            //                else
            //                {
            //                    BLLCommon.extension.Print(hasMatch, workCodeKeyword);
            //                }
            //            }
            //            if (BLLCommon.config.PromptAfterPrinting && !BLL.Config.Backgrounder)
            //            {
            //                string text = Language.Dialog("SelectPrintContent");
            //                new FaceMessageBox("", text, MessageBoxButtons.OK).ShowDialog();
            //            }
            //            Ispring = true;

            //        }
            //        Ispring = true;
            //    }

            //}

        }
    }
}