NS_Keyword.xaml.cs 39.6 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
using BLL;
using DocumentFormat.OpenXml.ExtendedProperties;
using Model;
using SmartScan.PlusSettingFrm;
using SmartScan.SetControl.WPF.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using static SmartScan.SetControl.WPF.Model.NeoAlertBox;
using Button = System.Windows.Controls.Button;

namespace SmartScan.SetControl.WPF
{
    /// <summary>
    /// NS_Keyword.xaml 的交互逻辑
    /// </summary>
    public partial class NS_Keyword : System.Windows.Controls.UserControl, INotifyPropertyChanged
    {
        private bool _isRIDFieldSelected;

        // 添加用于XAML绑定的属性
        public bool IsRIDFieldSelected
        {
            get { return _isRIDFieldSelected; }
            set
            {
                if (_isRIDFieldSelected != value)
                {
                    _isRIDFieldSelected = value;
                    OnPropertyChanged(nameof(IsRIDFieldSelected));
                }
            }
        }

        // 实现INotifyPropertyChanged接口
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public class KeywordItem
        {
            // 关键词名称
            public string Text { get; set; }
            // 显示文本(在UI上显示)
            public string DisplayText { get; set; }
            // 新增属性用于流水号
            public bool IsSerialNumber { get; set; }     // 是否为流水号
            public string SerialExample { get; set; }    // 流水号示例
            public bool IsEditing { get; set; } // 新增编辑状态属性

        }
        private readonly List<string> keyCopy;
        private readonly List<string> keyCopyValue;
        private List<KeywordItem> selectedKeywords=new  List<KeywordItem>(); // 用于跟踪已选关键词
        public string ButtonContent => LanguageWwitchover.GetText("ButtonContentKey");
        public string TextBlockContent => LanguageWwitchover.GetText("TextBlockContentKey");

        public NS_Keyword()
        {
            InitializeComponent();

            // 设置DataContext为当前实例,以支持绑定
            this.DataContext = this;

            BLLCommon.macroKey = new();
            BLLCommon.macroKeyValue = new();
            if (System.IO.File.Exists(FilePath.CONFIG_MACRO_KEY))
            {
                string[] lines = System.IO.File.ReadAllLines(FilePath.CONFIG_MACRO_KEY);
                BLLCommon.macroKey.AddRange(lines);
                LogNet.log.Debug($"添加关键字 {lines.Length} 行");
            }
            else
            {
                LogNet.log.Debug("关键字文件路径不存在");
            }
            if (System.IO.File.Exists(FilePath.CONFIG_MACRO_Value))
            {
                string[] lines = System.IO.File.ReadAllLines(FilePath.CONFIG_MACRO_Value);
                BLLCommon.macroKeyValue.AddRange(lines);
                LogNet.log.Debug($"添加关键字 {lines.Length} 行");
            }
            else
            {
                if (BLLCommon.macroKey.Count > 0)
                {
                    BLLCommon.macroKeyValue.AddRange(BLLCommon.macroKey.Select(s=>s+"//false"));
                }
                else
                    LogNet.log.Debug("关键字文件路径不存在");
            }
            keyCopy = new(BLLCommon.macroKey);
            keyCopyValue = new(BLLCommon.macroKeyValue);
            selectedKeywords = new List<KeywordItem>();
            setRIkey();
            UpdateListDisplay();

            // 创建关键字按钮
            foreach (var keyText in keyCopy)
            {
                Button button = new Button
                {
                    Content = keyText,
                    Style = (Style)FindResource("KeywordButtonStyle")
                };
                button.Click += KeywordButton_Click;
                KeywordsPanel.Children.Add(button);
            }
            LoadSavedConfiguration();

            // 初始化唯一码生成器界面可见性
            UpdateUniqueCodeGeneratorVisibility();
        }

        // 添加新方法来更新唯一码生成器界面的可见性
        private void UpdateUniqueCodeGeneratorVisibility()
        {
            if (LstKey.SelectedItem != null && LstKey.SelectedIndex >= 0)
            {
                // 获取原始字段名(不带RI标记)
                string originalField = keyCopy[LstKey.SelectedIndex];

                // 检查是否是唯一码字段
                IsRIDFieldSelected = (originalField == BLLCommon.config.ReelIDKeyWord) && !string.IsNullOrEmpty(BLLCommon.config.ReelIDKeyWord);
            }
            else
            {
                IsRIDFieldSelected = false;
            }
            // 注意:使用XAML绑定后不再需要直接设置Visibility属性
            // UniqueCodeGeneratorPanel.Visibility = IsRIDFieldSelected ? Visibility.Visible : Visibility.Collapsed;
        }

        private void LoadSavedConfiguration()
        {
            // 加载唯一码匹配规则
            if (!string.IsNullOrEmpty(BLLCommon.config.ReelIDMatch))
            {
                LogNet.log.Debug($"加载已保存配置: {BLLCommon.config.ReelIDMatch}");
                PreviewTextBlock.Text = BLLCommon.config.ReelIDMatch;

                // 先解析预览文本到选择的关键词
                ParseExistingPreviewToSelectedKeywords();
                // 标记流水号关键字
                MarkSerialNumberKeywords();
                // 再标记字符类型关键词
                MarkCharacterTypeKeywords();

                // 最后更新UI
                UpdateSelectedKeywordsUI();
            }
            else
            {
                LogNet.log.Debug("没有已保存的唯一码匹配规则");
            }
        }
        // 6. 添加标记流水号关键字的方法
        private void MarkSerialNumberKeywords()
        {
            string YU = BLLCommon.config.Language;
            // 检查是否存在流水号关键字
            for (int i = 0; i < selectedKeywords.Count; i++)
            {
                var keyword = selectedKeywords[i];
                if (keyword.Text == "serialnumber")
                {
                    // 创建流水号示例
                    string serialExample = GetSerialNumberExample();

                    // 更新流水号信息
                    keyword.IsSerialNumber = true;
                    keyword.SerialExample = serialExample;
                    if (YU=="English")
                    {
                        keyword.DisplayText = $"serialnumber (Serial: {serialExample})";

                    }
                    else if (YU == "日语")
                    {
                        keyword.DisplayText = $"serialnumber (シリアル番号: {serialExample})";

                    }
                    else
                    {
                        keyword.DisplayText = $"serialnumber (流水: {serialExample})";
                    }
                  

                    // 更新列表
                    selectedKeywords[i] = keyword;
                    LogNet.log.Debug($"已标记关键字: {keyword.Text} 为流水号,示例: {serialExample}");
                    break; // 只需处理第一个匹配项
                }
            }
        }
        private void MarkCharacterTypeKeywords()
        {
            string YU=BLLCommon.config.Language;
            // 解析字符类型关键词
            List<string> characterTypeKeywords = ParseCharacterTypeKeywords();
            // 如果配置中有字符类型关键字列表
            if (characterTypeKeywords.Count > 0)
            {
                // 输出日志以便调试
                LogNet.log.Debug($"标记字符类型关键字: {string.Join(", ", characterTypeKeywords)}");
                for (int i = 0; i < selectedKeywords.Count; i++)
                {
                    var keyword = selectedKeywords[i];
                    // 检查关键字是否在字符类型列表中
                    if (characterTypeKeywords.Contains(keyword.Text))
                    {
                        // 设置显示文本以包含(字符)标识,并确保不重复添加
                        if (keyword.DisplayText == null || !keyword.DisplayText.EndsWith(" (字符)")|| !keyword.DisplayText.EndsWith(" (文字)" )|| !keyword.DisplayText.EndsWith(" (characters)"))
                        {
                            if (YU == "English")
                            {
                                keyword.DisplayText = $"{keyword.Text} (characters)";

                            }
                            else if (YU == "日语")
                            {
                                keyword.DisplayText = $"{keyword.Text} (文字)";
                            }
                            else
                            {
                                keyword.DisplayText = $"{keyword.Text} (字符)";
                            }
                            LogNet.log.Debug($"已标记关键字: {keyword.Text} 为字符类型");
                        }
                    }
                }
                // 更新UI以反映变化
                UpdateSelectedKeywordsUI();
            }
            else
            {
                LogNet.log.Debug("没有字符类型关键字需要标记");
            }
        }
        private void ParseExistingPreviewToSelectedKeywords()
        {
            if (string.IsNullOrEmpty(PreviewTextBlock.Text))
                return;
            string preview = PreviewTextBlock.Text;
            selectedKeywords.Clear();
            LogNet.log.Debug($"解析预览文本: {preview}");
            // 使用简单的方法解析[keyword]格式的文本
            int startIndex = 0;
            while (startIndex < preview.Length)
            {
                int openBracket = preview.IndexOf('[', startIndex);
                if (openBracket < 0) break;
                int closeBracket = preview.IndexOf(']', openBracket);
                if (closeBracket < 0) break;
                string keyword = preview.Substring(openBracket + 1, closeBracket - openBracket - 1);
                LogNet.log.Debug($"找到关键字: {keyword}");
                // 创建关键字项
                KeywordItem item = new KeywordItem { Text = keyword };

                // 默认DisplayText是Text,允许后续处理修改
                item.DisplayText = keyword;
                selectedKeywords.Add(item);
                startIndex = closeBracket + 1;
            }
            LogNet.log.Debug($"解析出 {selectedKeywords.Count} 个关键字");

        }

        // 4. 修改UpdateSelectedKeywordsUI方法,为流水号添加特殊显示
        private void UpdateSelectedKeywordsUI()
        {
            // 清除现有UI
            SelectedKeywordsPanel.Children.Clear();
            for (int i = 0; i < selectedKeywords.Count; i++)
            {
                var keyword = selectedKeywords[i];

                // 为关键词项创建网格
                Grid itemGrid = new Grid();
                itemGrid.Margin = new Thickness(0, 5, 0, 5);
                // 定义列
                itemGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(60) });  // 序号
                itemGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });  // 关键词
                itemGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(40) });  // 上移按钮
                itemGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(40) });  // 下移按钮
                itemGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(40) });  // 删除按钮
                                                                                                      // 序号指示器
                Border numberBorder = new Border
                {
                    Style = (Style)FindResource("CircleNumberStyle"),
                    Child = new System.Windows.Controls.TextBlock
                    {
                        Text = (i + 1).ToString(),
                        Foreground = Brushes.White,
                        HorizontalAlignment = System.Windows.HorizontalAlignment.Center,
                        VerticalAlignment = VerticalAlignment.Center
                    }
                };
                Grid.SetColumn(numberBorder, 0);
                StackPanel contentPanel = new StackPanel { Orientation = System.Windows.Controls.Orientation.Horizontal };
                // 关键词文本 - 这里已经支持显示流水号预览格式
                System.Windows.Controls.TextBlock keywordText = new System.Windows.Controls.TextBlock
                {
                    Text = keyword.DisplayText ?? keyword.Text,
                    Visibility = keyword.IsEditing ? Visibility.Collapsed : Visibility.Visible,
                    Foreground = Brushes.White,
                    VerticalAlignment = VerticalAlignment.Center,
                    Margin = new Thickness(10, 0, 0, 0),
                    FontSize = 14,
                    FontFamily = new System.Windows.Media.FontFamily("微软雅黑"),
                };
                // 可编辑的TextBox
                System.Windows.Controls.TextBox editTextBox = new System.Windows.Controls.TextBox
                {
                    Text = keyword.Text,
                    Visibility = keyword.IsEditing ? Visibility.Visible : Visibility.Collapsed,
                    MinWidth = 100,
                    Margin = new Thickness(10, 0, 0, 0),
                    FontSize = 14,
                    FontFamily = new FontFamily("微软雅黑"),
                    Foreground = Brushes.White,
                    Background = Brushes.Transparent,
                    BorderThickness = new Thickness(1),
                    BorderBrush = Brushes.White
                };
                // 添加键盘事件处理
                editTextBox.KeyDown += (s, e) => {
                    if (e.Key == Key.Enter)
                    {
                        keyword.Text = editTextBox.Text;
                        keyword.DisplayText = editTextBox.Text;
                        keyword.IsEditing = false;
                        UpdateSelectedKeywordsUI();
                    }
                };

                // 失去焦点时保存
                editTextBox.LostFocus += (s, e) => {
                    keyword.Text = editTextBox.Text;
                    keyword.DisplayText = editTextBox.Text;
                    keyword.IsEditing = false;
                    UpdateSelectedKeywordsUI();
                };
                contentPanel.Children.Add(keywordText);
                contentPanel.Children.Add(editTextBox);
                // 双击事件处理
                itemGrid.MouseDown += (s, e) => {
                    if (e.ClickCount == 2 && !keyword.IsEditing)
                    {
                        keyword.IsEditing = true;
                        UpdateSelectedKeywordsUI();
                        // 设置焦点到TextBox
                        Dispatcher.BeginInvoke((Action)(() => {
                            editTextBox.Focus();
                            editTextBox.SelectAll();
                        }), System.Windows.Threading.DispatcherPriority.Render);
                    }
                };
                Grid.SetColumn(keywordText, 1);
                // 上移按钮
                Button upButton = new Button
                {
                    Content = "↑",
                    Style = (Style)FindResource("SecondaryButtonStyle"),
                    IsEnabled = i > 0,
                    Margin = new Thickness(2),
                    Padding = new Thickness(5)
                };
                int currentIndex = i; // 捕获当前索引
                upButton.Click += (s, e) => MoveKeywordUp(currentIndex);
                Grid.SetColumn(upButton, 2);
                // 下移按钮
                Button downButton = new Button
                {
                    Content = "↓",
                    Style = (Style)FindResource("SecondaryButtonStyle"),
                    IsEnabled = i < selectedKeywords.Count - 1,
                    Margin = new Thickness(2),
                    Padding = new Thickness(5)
                };
                downButton.Click += (s, e) => MoveKeywordDown(currentIndex);
                Grid.SetColumn(downButton, 3);
                // 删除按钮
                Button removeButton = new Button
                {
                    Content = "×",
                    Style = (Style)FindResource("SecondaryButtonStyle"),
                    Margin = new Thickness(2),
                    Padding = new Thickness(5)
                };
                removeButton.Click += (s, e) => RemoveKeyword(currentIndex);
                Grid.SetColumn(removeButton, 4);
                // 添加所有元素到网格
                itemGrid.Children.Add(numberBorder);
                //itemGrid.Children.Add(keywordText);
                itemGrid.Children.Add(upButton);
                itemGrid.Children.Add(downButton);
                itemGrid.Children.Add(removeButton);

                // 将网格添加到面板
                Grid.SetColumn(contentPanel, 1);
                itemGrid.Children.Add(contentPanel);
                SelectedKeywordsPanel.Children.Add(itemGrid);
            }
            // 更新预览
            UpdatePreview();
        }

        // 上移关键词
        private void MoveKeywordUp(int index)
        {
            if (index > 0 && index < selectedKeywords.Count)
            {
                var keyword = selectedKeywords[index];
                selectedKeywords.RemoveAt(index);
                selectedKeywords.Insert(index - 1, keyword);
                UpdateSelectedKeywordsUI();
            }
        }

        // 下移关键词
        private void MoveKeywordDown(int index)
        {
            if (index >= 0 && index < selectedKeywords.Count - 1)
            {
                var keyword = selectedKeywords[index];
                selectedKeywords.RemoveAt(index);
                selectedKeywords.Insert(index + 1, keyword);
                UpdateSelectedKeywordsUI();
            }
        }

        // 移除关键词
        private void RemoveKeyword(int index)
        {
            if (index >= 0 && index < selectedKeywords.Count)
            {
                selectedKeywords.RemoveAt(index);
                UpdateSelectedKeywordsUI();
            }
        }

        // 更新预览文本
        private void UpdatePreview()
        {
            StringBuilder preview = new StringBuilder();
            foreach (var keyword in selectedKeywords)
            {
                // 使用Text属性,它不包含(字符)标识
                preview.Append($"[{keyword.Text}]");
            }
            PreviewTextBlock.Text = preview.ToString();
        }

        private void LstKey_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (LstKey.SelectedItem != null && LstKey.SelectedIndex >= 0)
            {
                // 获取原始值(不含RI标记)
                string originalKey = keyCopy[LstKey.SelectedIndex];
                string selectedValue = keyCopyValue[LstKey.SelectedIndex].ToString();

                // 分割字符串
                string[] parts = selectedValue.Split('/');
                // 显示前半部分到Key输入框(去除可能的RI标记)
                string keyText = parts.Length > 0 ? parts[0] : string.Empty;
                lst_key.Text = keyText;
                // 显示后半部分到Name输入框(如果存在)
                lst_name.Text = parts.Length > 1 ? parts[1] : string.Empty;
                isEnable.IsChecked = parts.Length > 2 ? bool.Parse(parts[2]) : (bool?)null;
                // 更新唯一码生成器界面的可见性
                UpdateUniqueCodeGeneratorVisibility();
            }
        }

        private void UpdateAutoIdVisualState()
        {
            // 强制ListBox刷新,以确保样式触发器生效
            LstKey.Items.Refresh();

            // 更新唯一码生成器界面的可见性
            UpdateUniqueCodeGeneratorVisibility();
        }

        private void UpdateListDisplay()
        {
            // 创建临时集合保存处理后的显示值
            var displayItems = new List<string>();

            for (int i = 0; i < keyCopy.Count; i++)
            {
                string displayText = keyCopy[i].Split('/')[0];
                if (BLLCommon.config.ReelIDKeyWord == keyCopy[i])
                {
                    displayText = displayText + " (RI)";
                }
                displayItems.Add(displayText);
            }
            // 绑定处理后的集合到ListBox
            LstKey.ItemsSource = null;
            LstKey.ItemsSource = displayItems;
            // 保留原始数据引用
            LstKey.Tag = keyCopyValue; // 将原始数据存储在Tag属性
        }

        private void BtnAddKey_Click(object sender, RoutedEventArgs e)
        {
            string YU = BLLCommon.config.Language;
            string text = "";
            if (YU == "English")
            {
                 text = "Add Field";


            }
            else if (YU == "日语")
            {
                 text = "フィールドを追加";

            }
            else
            {
                 text = "新增字段";
            }
            string ls_name = lst_name.Text;
            bool isenable = (isEnable.IsChecked.HasValue) ? isEnable.IsChecked.Value : false; ;
            int index = keyCopy.FindIndex(match => match == text);
            if (index == -1)
            {

                keyCopy.Add($"{text}");
                keyCopyValue.Add($"{text}/{ls_name}/{isenable}");
                UpdateListDisplay();

                // 更新唯一码生成器界面的可见性
                UpdateUniqueCodeGeneratorVisibility();
            }
            else
            {
                string hint = Asa.FaceControl.Language.Dialog("KeyExists");
                hint = hint.Replace("[name]", text);
                new Asa.FaceControl.FaceMessageBox("", hint, MessageBoxButtons.OK).ShowDialog();
            }
        }

        private void BtnDelKey_Click(object sender, RoutedEventArgs e)
        {

            int index = LstKey.SelectedIndex;
            if (index == -1 || index >= keyCopy.Count) return;

            string YU = BLLCommon.config.Language;
            bool result = false;
            if (YU == "English")
            {
                result = NeoAlertBox.Show("", "Are you sure you want to delete the selected fields?", 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)
            {
                keyCopy.RemoveAt(index);
                keyCopyValue.RemoveAt(index);
                UpdateListDisplay();
                var keyname = ConfigHelper.Config.Get("Label_Key");
                if (!string.IsNullOrWhiteSpace(keyname))
                {
                    UsrKeywordlabeling.Deletskeyname();
                }

                // 更新唯一码生成器界面的可见性
                UpdateUniqueCodeGeneratorVisibility();
            }

        }

        private void BtnUpdateKey_Click(object sender, RoutedEventArgs e)
        {

            if (LstKey.SelectedIndex == -1) return;
            BLLCommon.config.ReelIDMatch = PreviewTextBlock.Text;
            BLLCommon.config.Save();
            string YU = BLLCommon.config.Language;
            bool result = false;
            if (YU == "English")
            {
                result = NeoAlertBox.Show("", "Save selected fields?", AlertType.Success, "NEO SCAN", true);
            }else if (YU == "日语")
            {
                result = NeoAlertBox.Show("", "選択されたフィールドを保存しますか?", AlertType.Success, "NEO SCAN", true);
            }
            else
            {
                result = NeoAlertBox.Show("", "是否要保存选中的字段?", AlertType.Success, "NEO SCAN", true);
            }
            if (result)
            {
                string text = lst_key.Text;
                string ls_name = lst_name.Text;
                int selectedIndex = LstKey.SelectedIndex;

                // 查找是否已存在相同字段(不含RI标记)
                int index = -1;
                for (int i = 0; i < keyCopy.Count; i++)
                {
                    if (i != selectedIndex && keyCopy[i] == text)
                    {
                        index = i;
                        break;
                    }
                }

                bool isenable = (isEnable.IsChecked.HasValue) ? isEnable.IsChecked.Value : false;

                if (index == -1)
                {
                    var oldname = keyCopy[LstKey.SelectedIndex];
                    var keyname = ConfigHelper.Config.Get("Label_Key");
                    // 从列表中移除
                    keyCopy.RemoveAt(selectedIndex);
                    keyCopyValue.RemoveAt(selectedIndex);
                    // 在相同位置插入新值
                    keyCopy.Insert(selectedIndex, text);
                    keyCopyValue.Insert(selectedIndex, $"{text}/{ls_name}/{isenable}");
                    // 如果修改的是唯一码字段,更新ReelIDKeyWord
                    if (oldname == BLLCommon.config.ReelIDKeyWord)
                    {
                        if (isenable)
                        {
                            BLLCommon.config.ReelIDKeyWord = text;
                        }
                        else
                        {
                            BLLCommon.config.ReelIDKeyWord = "";
                        }
                    }
                    // 检查是否将其设为唯一码字段
                    else if (selectedIndex == 0 && isenable && BLLCommon.config.ReelIDKeyWord == "")
                    {
                        BLLCommon.config.ReelIDKeyWord = text;
                    }
                    // 保持选中状态
                    LstKey.SelectedIndex = selectedIndex;
                    UpdateListDisplay();
                    if (!string.IsNullOrWhiteSpace(keyname))
                    {
                        if (oldname == keyname)
                        {
                            UsrKeywordlabeling.Updatekeyname(text);
                        }
                    }

                    setRIkey();

                    // 更新唯一码生成器界面的可见性
                    UpdateUniqueCodeGeneratorVisibility();
                }
                else
                {
                    string hint = Asa.FaceControl.Language.Dialog("KeyExists");
                    hint = hint.Replace("[name]", text);
                    new Asa.FaceControl.FaceMessageBox("", hint, MessageBoxButtons.OK).ShowDialog();
                }
            }
        }

        void setRIkey()
        {
            // 创建一个新的显示列表
            List<string> displayList = new List<string>();

            // 添加列表项并标记唯一码字段
            for (int i = 0; i < keyCopy.Count; i++)
            {
                string displayText = keyCopy[i];
                if (BLLCommon.config.ReelIDKeyWord == displayText)
                {
                    displayText = displayText + " (RI)";
                }
                displayList.Add(displayText);
            }

            // 更新ListBox的ItemsSource
            LstKey.ItemsSource = null;
            LstKey.ItemsSource = displayList;

            // 更新唯一码生成器界面的可见性
            UpdateUniqueCodeGeneratorVisibility();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            string YU = BLLCommon.config.Language;
            LanguageWwitchover.LoadPath(FilePath.LANGUAGE_DIR);
            LanguageWwitchover.LoadLanguage(YU);
            LanguageWwitchover.SetLanguage(this);
            // 检查LOT字段是否启用
            CheckLOTFieldEnabled();
            // 更新唯一码生成器界面的可见性
            UpdateUniqueCodeGeneratorVisibility();
            // 更新唯一码生成器界面的可见性
            UpdateUniqueCodeGeneratorVisibility();
        }
        // 添加新方法检查LOT字段是否启用
        private void CheckLOTFieldEnabled()
        {
            // 确保有字段存在
            if (keyCopy.Count > 0)
            {
                // 获取第一个字段
                string firstField = keyCopy[0];
                int firstFieldIndex = 0;
                if (keyCopyValue.Count == 0)
                    return;
                // 检查对应的值中是否启用
                string fieldValue = keyCopyValue[firstFieldIndex];
                string[] parts = fieldValue.Split('/');
                // 检查是否有启用标志且为true
                bool isEnabled = parts.Length > 2 && bool.TryParse(parts[2], out bool enabled) && enabled;
                // 根据启用状态设置ReelIDKeyWord
                if (isEnabled)
                {
                    BLLCommon.config.ReelIDKeyWord = firstField;
                }
                else
                {
                    BLLCommon.config.ReelIDKeyWord = "";
                }

                BLLCommon.config.Save();
            }
        }
        public void Save()
        {

            if (LstKey.Tag is List<string> originalData)
            {
                BLLCommon.macroKey.Clear();
                BLLCommon.macroKey.AddRange(keyCopy);
                System.IO.File.WriteAllLines(FilePath.CONFIG_MACRO_KEY, keyCopy.ToArray());
                System.IO.File.WriteAllLines(FilePath.CONFIG_MACRO_Value, originalData.ToArray());

                // 收集字符类型关键字
                List<string> characterTypeKeywords = new List<string>();
                foreach (var keyword in selectedKeywords)
                {
                    // 确保DisplayText已经设置
                    string displayText = keyword.DisplayText ?? keyword.Text;
                    
                        if (displayText.EndsWith(" (字符)")|| displayText.EndsWith(" (文字)") || displayText.EndsWith(" (characters)"))
                    {
                        LogNet.log.Debug($"保存字符类型关键字: {keyword.Text}");
                        characterTypeKeywords.Add(keyword.Text);
                    }
                }

                // 保存字符类型关键字
                SaveCharacterTypeKeywords(characterTypeKeywords);
                // 保存预览文本作为匹配规则
                BLLCommon.config.ReelIDMatch = PreviewTextBlock.Text;
                BLLCommon.config.ReelIDPrefix = "";
                BLLCommon.config.ReelIDPostfix = "";
                BLLCommon.config.Save();
            }
        }

        private void UsrMacro_btn_adddatetime_Click(object sender, RoutedEventArgs e)
        {
            var keyword = new KeywordItem { Text = "datetime:yyyyMMddHHmmss" };
            selectedKeywords.Add(keyword);

            // 更新UI
            UpdateSelectedKeywordsUI();
        }

        private void BtnAutoId_Click(object sender, RoutedEventArgs e)
        {
            if (LstKey.SelectedIndex == -1) return;
            if (keyCopy[LstKey.SelectedIndex] == BLLCommon.config.ReelIDKeyWord)
                BLLCommon.config.ReelIDKeyWord = "";
            else
                BLLCommon.config.ReelIDKeyWord = keyCopy[LstKey.SelectedIndex];

            UpdateAutoIdVisualState();
         
        }

        private void Rule_Click(object sender, RoutedEventArgs e)
        {
            // 创建窗口实例
            WPF_Rule ruleWindow = new WPF_Rule();

            // 订阅关键字生成事件
            ruleWindow.KeywordGenerated += RuleWindow_KeywordGenerated;

            // 显示窗口
            ruleWindow.ShowDialog();
        }

        private void RuleWindow_KeywordGenerated(object sender, string keyword)
        {
            string YU = BLLCommon.config.Language;
            string displayKeyword = "";
            if (YU == "English")
            {
                displayKeyword = $"{keyword} (characters)";
                //keyword.DisplayText = $"{keyword.Text} (characters)";

            }
            else if (YU == "日语")
            {
                displayKeyword = $"{keyword} (文字)";
               // keyword.DisplayText = $"{keyword.Text} (文字)";
            }
            else
            {
                 displayKeyword = $"{keyword} (字符)";
            }
            // 为显示添加(字符)标识
          
            // 添加到已选关键词列表
            var keywordItem = new KeywordItem
            {
                Text = keyword,                    // 原始值,用于生成唯一码
                DisplayText = displayKeyword       // 带标识的显示值
            };
            selectedKeywords.Add(keywordItem);
            // 将该关键字添加到字符类型列表中
            List<string> characterTypeKeywords = ParseCharacterTypeKeywords();
            if (!characterTypeKeywords.Contains(keyword))
            {
                characterTypeKeywords.Add(keyword);
                SaveCharacterTypeKeywords(characterTypeKeywords);
                BLLCommon.config.Save();
            }
            // 更新UI
            UpdateSelectedKeywordsUI();
        }

        private void KeywordButton_Click(object sender, RoutedEventArgs e)
        {
            if (sender is System.Windows.Controls.Button button)
            {
                string keywordText = button.Content.ToString();
                // 解析字符类型关键词
                List<string> characterTypeKeywords = ParseCharacterTypeKeywords();

                // 检查该关键字是否已被标记为字符类型
                bool isCharacterType = characterTypeKeywords.Contains(keywordText);
                string characterTypeLabel;
                // 添加到已选关键词列表
                switch (BLLCommon.config.Language)
                {
                    case "English":
                        characterTypeLabel = "(Character)";
                        break;
                    case "日语":
                        characterTypeLabel = "(文字)";
                        break;
                    case "中文":
                    default:
                        characterTypeLabel = "(字符)";
                        break;
                }
                var keyword = new KeywordItem
                {
                    Text = keywordText,
                    DisplayText = isCharacterType ? $"{keywordText} {characterTypeLabel}" : keywordText
                };
                selectedKeywords.Add(keyword);
                // 更新UI
                UpdateSelectedKeywordsUI();
            }
        }

        private void Generate_a_unique_code_Click(object sender, RoutedEventArgs e)
        {
            BLLCommon.config.ReelIDMatch = PreviewTextBlock.Text;
            BLLCommon.config.Save();
        }

        private void Reset_Click(object sender, RoutedEventArgs e)
        {
            // 清空已选关键词
            selectedKeywords.Clear();

            // 重置预览
            PreviewTextBlock.Text = string.Empty;

            // 更新UI
            UpdateSelectedKeywordsUI();
        }

        private void Serial_number_Click(object sender, RoutedEventArgs e)
        {
            // 创建窗口实例
            WPF_Serialnumber ruleWindow = new WPF_Serialnumber();
            // 订阅流水号窗口完成事件
            ruleWindow.Closed += (s, args) => {
                if (ruleWindow.DialogResult == true)
                {
                    // 生成流水号预览示例
                    string serialExample = GetSerialNumberExample();
                    string serialLabel, serialText;
                    // 根据系统语言确定流水号的显示文本
                    switch (BLLCommon.config.Language)
                    {
                        case "English":
                            serialLabel = "Serial";
                            serialText = "serialnumber";
                            break;
                        case "日语":
                            serialLabel = "シリアル";
                            serialText = "シリアル番号";  // 日语翻译的serialnumber
                            break;
                        case "中文":
                        default:
                            serialLabel = "流水";
                            serialText = "序列号";  // 中文翻译的serialnumber
                            break;
                    }
                    // 添加或更新流水号关键字
                    KeywordItem serialItem = new KeywordItem
                    {
                        Text = "serialnumber",
                        DisplayText = $"{serialText} ({serialLabel}: {serialExample})",
                        IsSerialNumber = true,
                        SerialExample = serialExample
                    };

                    // 查找是否已有流水号关键字
                    int serialIndex = selectedKeywords.FindIndex(k => k.Text == "serialnumber");
                    if (serialIndex >= 0)
                    {
                        // 更新已有的流水号关键字
                        selectedKeywords[serialIndex] = serialItem;
                    }
                    else
                    {
                        // 添加新的流水号关键字
                        selectedKeywords.Add(serialItem);
                    }

                    // 更新UI显示
                    UpdateSelectedKeywordsUI();
                }
            };
            // 显示窗口
            ruleWindow.ShowDialog();
        }
        private string GetSerialNumberExample()
        {
            int places = BLLCommon.config.ReelIDPlaces;
            bool fillZero = BLLCommon.config.ReelIDFillZero;

            if (fillZero)
            {
                return string.Format("{0:D" + places + "}", 1); // 例如:"0000000001"
            }
            else
            {
                return "1"; // 不补零的情况
            }
        }
        // 辅助方法:将字符串格式的字符类型关键词解析为列表
        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 void SaveCharacterTypeKeywords(List<string> keywords)
        {
            string keywordsStr = string.Join(",", keywords);
            BLLCommon.config.CharacterTypeKeywords = keywordsStr;
        }

        
       
    }
}