Item_General.cs 36.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 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
using Asa.FaceControl;
using DocumentFormat.OpenXml.Drawing.Charts;
using Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Script.Serialization;
using System.Windows.Forms;
using System.Windows.Threading;
using static BLL.BLLCommon;
using static BLL.Replacekeywords;
using Http = Model.Http;

namespace BLL
{
    public class General : IExtension
    {
        public event IExtension.PrintDelegate Printing;
        public event IExtension.PrintDelegate SaveRetrospect;

        private Config config;
        private List<ExtensionControl> extensions;
        List<string> macroKey;
        List<string> macroKeyValue;
        private void ReadMacro()
        {
            macroKey = new();
            if (System.IO.File.Exists(FilePath.CONFIG_MACRO_KEY))
            {
                string[] lines = System.IO.File.ReadAllLines(FilePath.CONFIG_MACRO_KEY);
                macroKey.AddRange(lines);
            }
            macroKeyValue = new();
            if (System.IO.File.Exists(FilePath.CONFIG_MACRO_Value))
            {
                string[] lines = System.IO.File.ReadAllLines(FilePath.CONFIG_MACRO_Value);
                macroKeyValue.AddRange(lines);
            }
        }
        private DebounceHelper<FaceComboBox, string> debounceHelper;
        public General(Config config)
        {
            this.config = config;
            ReadMacro();
            debounceHelper = new DebounceHelper<FaceComboBox, string>(500); // 设置抗抖动的间隔,单位为毫秒
            debounceHelper.DebouncedTextChanged += DebounceHelper_DebouncedTextChanged;

        }

        private void DebounceHelper_DebouncedTextChanged(object sender, string e)
        {
            var s = sender as Asa.FaceControl.FaceComboBox;
            //if (s.Text == e)
            //    return;
            s.Items.Clear();
            var data = ExtraFileData.DataTitle
                .Where(a => a.Contains(e))
                .Distinct()
                .OrderBy(tit => tit)
                .ToArray();
            s.Items.AddRange(data);

            //s.SelectedIndex = -1;
            //s.Enabled = true;
            //s.Text = e;
        }


        public void Clear()
        {
            LogNet.log.Info("Clear()");
            for (int i = 0; i < extensions.Count; i++)
            {
                if (!extensions[i].CanClear) continue;
                if (extensions[i].Control is FaceComboBox box)
                    box.Items.Clear();
                extensions[i].Control.Text = "";
            }
        }

        public void Dispose()
        {
        }

        public void Load(List<ExtensionControl> extensions)
        {
            this.extensions = extensions;
        }

        static bool mesResult = false;
        bool islast = false;

        Dictionary<string, string> lastkey = null;
        // 用于存储上一次的 key
        private Dictionary<string, string> lastKeys;
        // 定义事件


        protected virtual void OnKeySet(string templateName,string[] originalCode, Dictionary<string, string> key, bool hasMatch)
        {
            extension.set(templateName , originalCode, key, hasMatch);
        }
        public Dictionary<string, string> GetUIKeywords() {
            return extension.GetUIKeywords();
        }
        protected virtual void CheckText(string text)
        {
            extension.Check(text);
        }

        public bool SetKey(string templateName, string[] originalCode, Dictionary<string, string> key, bool hasMatch, out string errmsg)
        {
            errmsg = "";
            mesResult = false;
            var now = DateTime.Now;
            // 比较当前 key 和上次的 key
            bool isSame = false;
            bool isFirstCapture = lastKeys == null;

            try
            {
                //OnKeySet(originalCode, key, hasMatch);
                if (extensions != null && !extensions[0].Control.InvokeRequired)
                {
                    //第一次刷新界面
                    for (int i = 0; i < extensions.Count; i++)
                    {
                        extensions[i].Control.ForeColor = System.Drawing.Color.White;
                        if (key.ContainsKey(extensions[i].Key))
                            extensions[i].Control.Text = key[extensions[i].Key].Replace("<OCR>", "");
                        if (extensions[i].LinkName == "ischeckresult" && lastKeys != null)
                        {
                            //if (BLLCommon.extension.labelText=="NG")
                            //{
                            //    extensions[i].Control.Text = BLLCommon.extension.labelText;
                            //    extensions[i].Control.ForeColor = System.Drawing.Color.Red;
                            //}
                            //else
                            //{
                            //    extensions[i].Control.Text = BLLCommon.extension.labelText;
                            //    extensions[i].Control.ForeColor = System.Drawing.Color.Green;
                            //}


                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            Application.DoEvents();

            #region  判断指定关键字是否存在内容   
            bool isdisplay = true;
            string str = ConfigHelper.Config.Get("DataSource_ForceMatching", "");
            if (!string.IsNullOrWhiteSpace(str))
            {
                string[] arr = str.Split(',');
                foreach (var item in arr)
                {
                    key.TryGetValue(item, out string value);
                    if (string.IsNullOrWhiteSpace(value))
                    {
                        isdisplay = false;
                        break;
                    }
                }
            }
            #endregion



            //客户定制key
            string exKey = ConfigHelper.Config.Get("Ex_UserDataKey", "Manufactured_Date");
            if (macroKey.Contains(exKey))
            {
                if (key.ContainsKey(exKey))
                {
                    key[exKey] = DateTime.Now.ToString(ConfigHelper.Config.Get("Ex_UserDataRule", "MM/dd/yyyy"));
                }
                else
                {
                    key.Add(exKey, DateTime.Now.ToString(ConfigHelper.Config.Get("Ex_UserDataRule", "MM/dd/yyyy")));
                }
            }

            // 添加或更新 dataTime 字段为当前日期(格式:yyyy年MM月dd日)
            bool addDateTime = false;
            foreach (var item in BLLCommon.macroKeyValue)
            {
                string[] parts = item.Split('\t');
                if (parts.Length >= 3 && parts[0].ToLower() == "DateTime".ToLower() && parts[2].Trim().Equals("True", StringComparison.OrdinalIgnoreCase))
                {
                    addDateTime = true;
                    break;
                }
            }
            // 只有当DataTime配置存在且启用时才添加
            if (addDateTime)
            {
                if (key.ContainsKey("DateTime"))
                {
                    key["DateTime"] = DateTime.Now.ToString(ConfigHelper.Config.Get("Ex_UserDataRule", "dd-MM-yyyy"));
                }
                else
                {
                    key.Add("DateTime", DateTime.Now.ToString(ConfigHelper.Config.Get("Ex_UserDataRule", "dd-MM-yyyy")));
                }
            }
            LogNet.log.Info($"OnKeySet1");
            OnKeySet(templateName, originalCode, key, hasMatch);
            // 添加或替换自增ID
            string reelIdKeyWord = config.ReelIDKeyWord;
            if (!string.IsNullOrEmpty(config.ReelIDKeyWord) && isdisplay)
            {
                var Reelidstr = GetReelid();
                if (key.ContainsKey(config.ReelIDKeyWord))
                {
                    key[config.ReelIDKeyWord] = Reelidstr;
                }
                else
                {
                    key.Add(config.ReelIDKeyWord, Reelidstr);
                }
            }



            // 如果有字段更新,则再次调用OnKeySet更新WPF界面
            LogNet.log.Info($"OnKeySet2");
            OnKeySet(templateName, originalCode, key, hasMatch);            
            if (lastKeys == null && !islast && BLLCommon.config.CheckFunction)
            {

                lastKeys = new Dictionary<string, string>(key); // 更新 lastKey

            }


            //第二次刷新界面
            for (int i = 0; i < extensions.Count; i++)
            {
                #region 如果是下拉框加载内容
                if (extensions[i].Type == "ComboBox")
                {
                    var s = extensions[i].Control as Asa.FaceControl.FaceComboBox;
                    s.Items.Clear();
                    var data = ExtraFileData.DataTitle
                        .Where(a => a.Contains(extensions[i].Control.Text))
                        .Distinct()
                        .OrderBy(tit => tit)
                        .ToArray();
                    s.Items.AddRange(data);
                    s.Text = "";
                    s.SelectedIndex = -1;
                    s.Enabled = true;
                }
                #endregion
                extensions[i].Control.ForeColor = System.Drawing.Color.White;
                if (key.ContainsKey(extensions[i].Key))
                {
                    extensions[i].Control.Text = key[extensions[i].Key].Replace("<OCR>", "");
                }
                if (extensions[i].LinkName == "ischeckresult")
                {
                    extensions[i].Control.Text = BLLCommon.extension.labelText;
                }
            }


            //if (BLLCommon.config.CheckFunction)
            //{
            //    if (isFirstCapture)
            //    {
            //        if (!updatereelid(key, out errmsg))
            //            return false;
            //    }
            //}
            //else
            //{
            if (!updatereelid(key, out errmsg))
            {
                LogNet.log.Info($"updatereelid false");
               
                return false;
            }
            // }



            if (extensions != null && !extensions[0].Control.InvokeRequired)
            {
                //使用key填充时,请处理字段开头的<OCR>字段
                //查询excel数据填充
                if (key.ContainsKey(Config.DataSource_DataKey))
                {
                    string CleanData = key[Config.DataSource_DataKey].Replace("<OCR>", "");
                    if (key.ContainsKey(Config.DataSource_DataKey) && ExtraFileData.AllData.ContainsKey(CleanData))
                    {
                        var extraData = ExtraFileData.AllData[CleanData];
                        foreach (var d in extraData)
                        {
                            if (!string.IsNullOrEmpty(d.Value))
                                key[d.Key] = d.Value;
                        }
                    }
                }
                lastkey = key;
                islast = false;
                if (lastKeys != null)
                {
                    if (BLLCommon.config.CheckFunction)
                    {
                        if (BLLCommon.config.Language.Equals("English"))
                        {
                            BLLCommon.extension.labelText = "Waiting";
                            CheckText("Waiting");
                        }
                        else if (BLLCommon.config.Language.Equals("日语"))
                        {
                            BLLCommon.extension.labelText = "待機中";
                            CheckText("待機中");
                        }
                        else
                        {
                            BLLCommon.extension.labelText = "等待中";
                            CheckText("等待中");
                        }
                        islast = false;
                    }
                    // 创建不包含自增ID的临时字典进行比较
                    //var keyWithoutReelID = new Dictionary<string, string>(key);
                    //var lastKeysWithoutReelID = new Dictionary<string, string>(lastKeys);

                    //// 从比较中排除自增ID
                    //if (!string.IsNullOrEmpty(reelIdKeyWord))
                    //{
                    //    keyWithoutReelID.Remove(reelIdKeyWord);
                    //    lastKeysWithoutReelID.Remove(reelIdKeyWord);
                    //}

                    //// 比较不包含自增ID的字典
                    //isSame = keyWithoutReelID.Count == lastKeysWithoutReelID.Count &&
                    //         !keyWithoutReelID.Except(lastKeysWithoutReelID).Any();
                    //if (isSame)
                    //{
                    //    BLLCommon.extension.labelText = "OK";
                    //    CheckText("OK");
                    //    lastKeys = null;
                    //    islast = true;
                    //    // 两次的 key 相同,可添加相应逻辑
                    //}
                    //else
                    //{    // 两次的 key 不同,可添加相应逻辑
                    //    BLLCommon.extension.labelText = "NG";
                    //    CheckText("NG");
                    //}
                }
                else
                {
                    if (BLLCommon.config.CheckFunction)
                    {
                        if (BLLCommon.config.Language.Equals("English"))
                        {
                            BLLCommon.extension.labelText = "Waiting";
                            CheckText("Waiting");
                        }
                        else if (BLLCommon.config.Language.Equals("日语"))
                        {
                            BLLCommon.extension.labelText = "待機中";
                            CheckText("待機中");
                        }
                        else
                        {
                            BLLCommon.extension.labelText = "等待中";
                            CheckText("等待中");
                        }
                        islast = false;

                    }
                }


            }


            Application.DoEvents();
            



            //禁用打印按钮
            bool close = ConfigHelper.Config.Get("isprinclose", false);
            if (close)
            {
                if (extensions != null)
                {
                    var batt = extensions.Where(a => a.Type == "Button" && a.Control.Name == "BtnPrint").FirstOrDefault();
                    if (batt != null)
                    {
                        batt.Control.Enabled = true;
                    }
                }

            }
            //if (BLLCommon.config.CheckFunction&&!islast)
            //{
            //    return false;
            //}

            return true;
        }
        public static void DoEvents()
        {
            var frame = new DispatcherFrame();
            Dispatcher.CurrentDispatcher.BeginInvoke(
                DispatcherPriority.Background,
                new DispatcherOperationCallback(ExitFrame),
                frame);
            Dispatcher.PushFrame(frame);
        }

        private static object ExitFrame(object frame)
        {
            ((DispatcherFrame)frame).Continue = false;
            return null;
        }
        bool updatereelid(Dictionary<string, string> key, out string errmsg)
        {
            errmsg = "";
            try
            {
                LogNet.log.Info($"接口上传信息 url: {config.HttpReelID.Trim()}, data: {JsonConvert.SerializeObject(key)}");
                if (!string.IsNullOrEmpty(config.HttpReelID.Trim()))
                {
                    Dictionary<string, object> pairs = new Dictionary<string, object>();
                    if (!GetHttpReelID(key, out errmsg, out pairs))
                    {
                        LogNet.log.Error("GetHttpReelID:" + errmsg);
                        return false;
                    }
                    LogNet.log.Error("GetHttpReelID:true" );
                    //key["ReelID"] = newid;
                }
                if (extensions != null && extensions.Count > 0 && !extensions[0].Control.InvokeRequired)
                {
                    for (int i = 0; i < extensions.Count; i++)
                    {
                        if (extensions[i].Key.ToLower() == "reelid" && key.ContainsKey("reelid"))
                            extensions[i].Control.Text = key["reelid"];
                    }
                }
            }
            catch (Exception ex)
            {

                LogNet.log.Info("ex" + ex.ToString());
            }

            if(!DidRegisterValidate(key, out errmsg))
            {
                return false;
            }
            //SaveRetrospect?.Invoke(key);
            return true;



        }

        private bool DidRegisterValidate(Dictionary<string, string> content, out string errmsg)
        {
            errmsg = "";
            try
            {
                if (BLLCommon.neximApiUtils.registerNewDid(content, out string msg))
                {
                    return true;
                }
                else
                {
                    errmsg = msg;
                    MessageboxNeo.Show("RegisterDidError", errmsg, "NEO SCAN", true);
                    return false;
                }

            }
            catch (Exception ex)
            {
                LogNet.log.Info("DidRegisterValidate" + ex.ToString());
            }
            return false;
        }

        public void Update()
        {
        }

        private string GetReelid()
        {
            LogNet.log.Debug("Enter GetReelid Method");
            if (extensions != null)
            {
                int idIndex = extensions.FindIndex(match => match.Key == config.ReelIDKeyWord);
                if (idIndex == -1) return "";
            }

            // 读取参数
            string matchPattern = config.ReelIDMatch;
            int matchPlace = config.ReelIDPlaces;
            bool matchFill = config.ReelIDFillZero;

            // 处理字符类型关键字
            List<string> characterTypeKeywords = ParseCharacterTypeKeywords();
            LogNet.log.Debug($"字符类型关键字: {string.Join(", ", characterTypeKeywords)}");

            // 解析模板中的所有关键字
            string[] keys = ObjConversion.StrGetKey(matchPattern);
            string processedPattern = matchPattern;
            // 读取当前自增ID值
            var reelID = ReadReelID();
            // 格式化自增ID
            string formattedID;
            if (matchFill)
            {
                formattedID = string.Format("{0:D" + matchPlace + "}", reelID);
            }
            else
            {
                formattedID = reelID.ToString();
            }

            for (int i = 0; i < keys.Length; i++)
            {
                string key = keys[i];
                string keyPlaceholder = $"[{key}]";
                // 处理流水号关键字
                if (key.ToLower() == "serialnumber")
                {
                    processedPattern = processedPattern.Replace(keyPlaceholder, formattedID);
                    continue;
                }
                // 1. 处理日期时间关键字
                if (key.ToLower().StartsWith("datetime"))
                {
                    var d = key.Split(':');
                    if (d.Length == 2)
                    {
                        processedPattern = processedPattern.Replace(keyPlaceholder, DateTime.Now.ToString(d[1]));
                    }
                    else
                    {
                        processedPattern = processedPattern.Replace(keyPlaceholder, DateTime.Now.ToString());
                    }
                    continue;
                }

                // 2. 处理字符类型关键字 - 它们直接保留原始文本
                if (characterTypeKeywords.Contains(key))
                {
                    processedPattern = processedPattern.Replace(keyPlaceholder, key);
                    // 对于字符类型,直接保留不替换
                    continue;
                }
                var uikey = GetUIKeywords();
                if (uikey.ContainsKey(key))
                    processedPattern = processedPattern.Replace(keyPlaceholder, uikey[key]);

                //// 3. 处理普通关键字(从UI控件获取值)
                //if (extensions != null)
                //{
                //    int index = extensions.FindIndex(match => match.Key == key);
                //    if (index == -1) continue;
                //    processedPattern = processedPattern.Replace(keyPlaceholder, extensions[index].Control.Text);
                //}
            }

            string finalText = processedPattern;

            LogNet.log.Info(string.Format("GetReelid pattern={0}, id={1}, text={2}", matchPattern, reelID, finalText));

            return finalText;
        }

        // 辅助方法:将字符串格式的字符类型关键词解析为列表
        private List<string> ParseCharacterTypeKeywords()
        {
            string keywordsStr = BLLCommon.config.CharacterTypeKeywords;
            if (string.IsNullOrEmpty(keywordsStr))
                return new List<string>();

            return keywordsStr.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                             .Select(k => k.Trim())
                             .ToList();
        }

        private int ReadReelID()
        {
            int reelID = 1;
            try
            {
                var reelidfile = FilePath.CONFIG_REELID;
                if (Config.REEL_ID_AutoResetStrategy == 1)
                {
                    Directory.CreateDirectory(reelidfile + "_dir");
                    reelidfile = Path.Combine(FilePath.CONFIG_REELID + "_dir", DateTime.Now.ToString("yyyyMMdd"));
                }
                else if (Config.REEL_ID_AutoResetStrategy == 2)
                {
                    Directory.CreateDirectory(reelidfile + "_dir");
                    reelidfile = Path.Combine(FilePath.CONFIG_REELID + "_dir", DateTime.Now.ToString("yyyyMM"));
                }
                if (File.Exists(reelidfile))
                {
                    string text = File.ReadAllText(reelidfile);
                    bool bln = int.TryParse(text, out reelID);
                    LogNet.log.Info($"ReadReelID {reelidfile}, {bln}, text={text}");
                    File.WriteAllText(reelidfile, (reelID + 1).ToString());
                    LogNet.log.Info($"Save ReelID:{reelID + 1}");
                }
                else
                {
                    reelID = 1;
                    File.WriteAllText(reelidfile, (reelID + 1).ToString());
                    LogNet.log.Info($"ReadReelID {reelidfile} Create");
                }
            }
            catch (Exception ex)
            {
                LogNet.log.Error("ReadReelID", ex);
                //MessageBox.Show(ex.Message, "Warning", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
            }
            return reelID;
        }
          
        private void GetHttpReelID(object sender, EventArgs e)
        {
            updatereelid(lastkey, out _);
            LogNet.log.Info($"updatereelid GetHttpReelID");
        }
        private void BtnSkip_Click(object sender, EventArgs e)
        {
            if (BLLCommon.config.Language.Equals("English"))
            {
                bool result = MessageboxNeo.Show("", "Whether to skip this operation?", "NEO SCAN", true);

                if (result)
                {
                    lastKeys = null;
                    BLLCommon.extension.labelText = "Waiting";
                }
            }
            else if (BLLCommon.config.Language.Equals("日语"))
            {
                bool result = MessageboxNeo.Show("",
     "この操作をスキップしますか?",
     "NEO SCAN",
     true);

                if (result)
                {
                    lastKeys = null;

                    BLLCommon.extension.labelText = "待機中";
                }
            }
            else
            {
                bool result = MessageboxNeo.Show("",
      "是否跳过此操作?",
      "NEO SCAN",
      true);


                if (result)
                {
                    lastKeys = null;

                    BLLCommon.extension.labelText = "等待中";
                }


            }

        }
        public void CheckClear()
        {

        }
        private void ComboBoxTextChanged(object sender, EventArgs e)
        {
            var txt = ((FaceComboBox)sender).Text;
            debounceHelper.HandleTextChanged((FaceComboBox)sender, txt);

        }
        private Dictionary<string, string> UpdateLastKey(Dictionary<string, string> lastkey)
        {
            Dictionary<string, string> keyValues = new Dictionary<string, string>();
            if (lastkey == null)
                return null;
            foreach (var temp in lastkey.Keys)
            {
                keyValues.Add(temp, lastkey[temp]);

                if (temp.Contains(":"))
                {
                    string date = temp.Split(':')[1];
                    if (int.TryParse(date, out int value) && value == 0 && int.TryParse(lastkey[temp], out int value2))
                    {
                        keyValues[temp] = value2.ToString($"D{date.Length}");
                    }
                }
            }
            return keyValues;
        }
        private void PrintLabel(object sender, EventArgs e)
        {
            LogNet.log.Info("Enter PrintLabel Method");
            if (lastkey == null) return;



            for (int i = 0; i < extensions.Count; i++)
            {
                if (extensions[i].Key == "") continue;
                if (lastkey.ContainsKey(extensions[i].Key))
                    lastkey[extensions[i].Key] = extensions[i].Control.Text;
                else
                    lastkey.Add(extensions[i].Key, extensions[i].Control.Text);
            }
            lastkey = UpdateLastKey(lastkey);
            LogNet.log.Info("lastkey:" + JsonConvert.SerializeObject(lastkey));
            #region  判断指定关键字是否存在内容   
            List<string> strings = new List<string>();
            string str = ConfigHelper.Config.Get("DataSource_ForceMatching", "");
            if (!string.IsNullOrWhiteSpace(str))
            {
                string[] arr = str.Split(',');
                foreach (var item in arr)
                {
                    lastkey.TryGetValue(item, out string value);
                    if (string.IsNullOrWhiteSpace(value))
                    {

                        strings.Add(item);
                    }
                }
            }
            LogNet.log.Info("DataSource_ForceMatching:" + string.Join(",", strings));
            #endregion
            for (int i = 0; i < extensions.Count; i++)
            {
                if (strings.Contains(extensions[i].Key))
                {
                    extensions[i].Control.BackColor = System.Drawing.Color.Red;
                    return;
                }
            }
            #region 点击打印按钮,rid内容为空时,生成rid
            if (!string.IsNullOrEmpty(config.ReelIDKeyWord))
            {
                if (lastkey.ContainsKey(config.ReelIDKeyWord))
                {
                    string rid = lastkey[config.ReelIDKeyWord];
                    if (string.IsNullOrWhiteSpace(rid))
                    {
                        var Reelidstr = GetReelid();
                        lastkey[config.ReelIDKeyWord] = Reelidstr;
                    }
                }
            }
            #endregion

            Printing?.Invoke(lastkey);
            bool close = ConfigHelper.Config.Get("isprinclose", false);
            if (close)
            {
                var batt = extensions.Where(a => a.Type == "Button" && a.Control.Name == "BtnPrint").FirstOrDefault();
                if (batt != null)
                {
                    batt.Control.Enabled = isprint;
                    isprint = false;
                }
            }
            //进行追溯配置保存
            SaveRetrospect?.Invoke(lastkey);
            for (int i = 0; i < extensions.Count; i++)
            {
                extensions[i].Control.BackColor = System.Drawing.Color.FromArgb(255, 20, 20, 20);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <param name="errmsg"></param>
        /// <param name="dic">返回请求后,替换完成的键值对</param>
        /// <returns></returns>
        private bool GetHttpReelID(Dictionary<string, string> key, out string errmsg, out Dictionary<string, object> dic)
        {
            errmsg = "";
            dic = null;
            string url = config.HttpReelID.Trim();
            string json = Http.PostJson(url, null, key);
            if (json == "")
            {
                errmsg = "Api error";
                if (extensions != null && !extensions[0].Control.InvokeRequired)
                    return MessageboxNeo.Show("BoxReelIDInfoMaintain", errmsg, "NEO SCAN", true);
                // new FaceMessageBox("BoxReelIDInfoMaintain", errmsg, System.Windows.Forms.MessageBoxButtons.OK, true).ShowDialog();

                return false;
            }
            JavaScriptSerializer serializer = new();
            //Dictionary<string, object> dic;
            try
            {
                var raw = (Dictionary<string, object>)serializer.DeserializeObject(json);

                // 重新建一个忽略大小写的字典,把数据拷进去
                dic = new Dictionary<string, object>(raw, StringComparer.OrdinalIgnoreCase);
            }
            catch
            {
                errmsg = "Api parse error:\r\n" + json;
                if (extensions != null && !extensions[0].Control.InvokeRequired)
                    return MessageboxNeo.Show("BoxReelIDInfoMaintain", errmsg, "NEO SCAN", true);
                //new FaceMessageBox("BoxReelIDInfoMaintain", errmsg, System.Windows.Forms.MessageBoxButtons.OK, true).ShowDialog();

                return false;
            }

            if (!dic.TryGetValue("CODE", out object value))
            {
                if (extensions != null && !extensions[0].Control.InvokeRequired)
                    return MessageboxNeo.Show("BoxReelIDInfoMaintain", errmsg, "NEO SCAN", true);
                //new FaceMessageBox("BoxReelIDInfoMaintain", "Api return data error:\r\n" + json, System.Windows.Forms.MessageBoxButtons.OK, true).ShowDialog();
                else
                    errmsg = "Api return data error:\r\n" + json;
                return false;
            }

            if (Convert.ToInt32(value) != 0)
            {
                errmsg = "Api parse error:\r\n" + dic["MSG"].ToString();
                if (extensions != null && !extensions[0].Control.InvokeRequired)
                    return MessageboxNeo.Show("BoxReelIDInfoMaintain", errmsg, "NEO SCAN", true);

                return false;
            }

            foreach (var kc in key.Keys)
            {
                if (dic.TryGetValue(kc, out value))
                {
                    key[kc] = value.ToString();
                }
            }

            if (key.ContainsKey("ReelID") && !string.IsNullOrEmpty(key["ReelID"]))
            {
                return true;
            }
            else
                return false;
        }
        // 定义动态按钮点击事件处理方法
        /// <summary>
        /// 通过http获取数据替换关键字内容
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DynamicButtonClick(object sender, EventArgs e)
        {
            try
            {
                var listexten = extensions.Where(a => a.Type == "TextBox").ToDictionary(kvp => kvp.Key, kvp => kvp.Control.Text);
                string jsondata = Replacekeywordss(listexten);
                if (jsondata != null)
                {
                    ResponseDatas lists = JsonConvert.DeserializeObject<ResponseDatas>(jsondata);
                    foreach (var responseItems in lists.Items)
                    {
                        foreach (var item in responseItems)
                        {
                            foreach (var items in extensions.Where(a => a.Type == "TextBox"))
                            {
                                if (items.Key == item.Name)
                                {
                                    items.Control.Text = item.Value.ToString();
                                }
                                //items.Control.Text = item.Value.ToString();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogNet.log.Error($"替换数据时出错:{ex.Message}");
            }
        }

        private void GetDataButtonClick(object sender, EventArgs e)
        {
            Dictionary<string, string> valuePairs = new Dictionary<string, string>();
            try
            {
                string datakey = Config.DataSource_DataKey;
                foreach (var items in extensions.Where(a => (a.Type == "TextBox" || a.Type == "ComboBox") && a.Key == datakey))
                {
                    string value = items.Control.Text;
                    var data = ExtraFileData.AllData[value];
                    foreach (var item in data)
                    {
                        var ext = extensions.Where(a => (a.Type == "TextBox" || a.Type == "ComboBox") && a.Key == item.Key).ToList();
                        foreach (var Control in ext)
                        {
                            Control.Control.Text = item.Value;
                            valuePairs.Add(Control.Key, item.Value);
                        }
                    }
                }

                lastkey = valuePairs;
            }
            catch (Exception)
            {
                LogNet.log.Info("GetDataButtonClick:请求本地文件数据替换出错!");
            }
        }
        public void DrawTextBackground(Dictionary<string, string> key)
        {
            if (extensions != null && extensions.Count > 0 && !extensions[0].Control.InvokeRequired)
            {
                bool focused = false; // 用于跟踪是否已经聚焦到第一个匹配的文本框
                for (int i = 0; i < extensions.Count; i++)
                {
                    if (key.ContainsKey(extensions[i].Key))
                    {
                        if (key[extensions[i].Key].StartsWith("<OCR>"))
                        {
                            extensions[i].Control.ForeColor = System.Drawing.Color.Yellow;
                        }
                        if (!focused && key[extensions[i].Key].StartsWith("<OCR>"))
                        {
                            extensions[i].Control.Focus();
                            focused = true; // 已经聚焦,不再继续
                        }
                    }

                }
            }
            Application.DoEvents();
        }

        bool isprint = false;
        public void Print(bool match, Dictionary<string, string> key)
        {
            if (extensions != null && extensions.Count > 0 && !extensions[0].Control.InvokeRequired)
            {
                //自动打印and模板匹配成功,只负责打印标签
                //if (config.AutoPrint && match)
                {
                    isprint = true;
                    PrintLabel(true, EventArgs.Empty);
                }
                //bool close = ConfigHelper.Config.Get("isprinclose", false);               
            }
            ////进行追溯配置保存
            //SaveRetrospect?.Invoke(key);
        }

        public Dictionary<string, string> ReplaceData(Dictionary<string, string> key)
        {
            string err = null;
            Dictionary<string, object> dic = new Dictionary<string, object>();
            if (!GetHttpReelID(key, out err, out dic))
            {
                return key;
            }
            return dic?.ToDictionary(a => a.Key, a => a.Value.ToString());
        }
    }
}