using MeterVision.Config;
using MeterVision.db;
using MeterVision.Dlg;
using MeterVision.Helper;
using MeterVision.model;
using MeterVision.Util;
using Microsoft.Win32;
using Newtonsoft.Json;
using OfficeOpenXml;
using OfficeOpenXml.Style;
using Ookii.Dialogs.Wpf;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
//using System.Windows.Shapes;

namespace MeterVision.Stand
{
    /// <summary>
    /// UCStand.xaml 的交互逻辑
    /// </summary>
    public partial class UCStandMain : UserControl, INotifyPropertyChanged
    {
        private const int COLUMN_LEFT_WIDTH = 220;
        private const int COLUMN_RIGHT_WIDTH = 400;

        private bool LeftVisiable = true;   //表示左侧的显示状态
        private bool RightVisiable = true;  //表示右侧的显示状态

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        //ItemsSource="{Binding StationMarkTypeKVs}"
        //                              SelectedValue="{Binding SelectedStationMarkType,Mode=TwoWay}"         

        private SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
        private SemaphoreSlim _semaphore2 = new SemaphoreSlim(1, 1);


        public ObservableCollection<KeyValuePair<MarkFindType, string>> StationMarkTypeKVs { get; set; }

        private void InitStationMarkTypeKVS()
        {
            StationMarkTypeKVs = new ObservableCollection<KeyValuePair<MarkFindType, string>>()
            {
                new KeyValuePair<MarkFindType, string>(MarkFindType.ALL,"所有"),
                new KeyValuePair<MarkFindType, string>(MarkFindType.MARK_YES,"已配置"),
                new KeyValuePair<MarkFindType, string>(MarkFindType.MARK_NO, "未配置")
            };
        }

        private MarkFindType _selectedStationMarkType;
        public MarkFindType SelectedStationMarkType
        {
            get => _selectedStationMarkType;
            set
            {
                if(_selectedStationMarkType != value)
                {
                    _selectedStationMarkType = value;
                    //OnPropertyChanged(nameof(SelectedStationMarkType));
                    if (SelectedStandItem != null)
                    {
                        ucStationGrid.ChangeFindAsync(FindStationId, SelectedStationMarkType, SelectedStandItem.StandId);
                    }
                }
            }
        }



        public PageModel StandPage { get; set; }

        //定义模板目录数据源
        public BulkObservableCollection<StandItem> StandItemList { get; set; }

        // 定义"标准答案编辑"依赖属性
        public static readonly DependencyProperty IsResultEditingProperty =
            DependencyProperty.Register("IsResultEditing", typeof(bool), typeof(UCStandMain), new PropertyMetadata(false));

        public bool IsResultEditing
        {
            get { return (bool)GetValue(IsResultEditingProperty); }
            set { SetValue(IsResultEditingProperty, value); }
        }

        private StandItem _selectedStandItem;
        public StandItem SelectedStandItem
        {
            get => _selectedStandItem;
            set
            {
                if (_selectedStandItem != value)
                {
                    if (!_semaphore2.Wait(0)) return;
                    try
                    {
                        _selectedStandItem = value;
                        OnPropertyChanged(nameof(SelectedStandItem));   //通知更新
                        if (_selectedStandItem != null)
                        {
                            ucStationGrid.ChangeFindAsync(FindStationId, SelectedStationMarkType, _selectedStandItem.StandId);
                        }
                        else
                        {
                            ucStationGrid.ChangeFindAsync(FindStationId, SelectedStationMarkType, "");
                        }
                        Apply_UCStandDetaisl_Title(value);
                    }
                    catch { }
                    finally
                    {
                        _semaphore2.Release();
                    }
                }
            }//set
        }

        private StationItem _selectedStationItem;
        public StationItem SelectedStationItem
        {
            get => _selectedStationItem;
            set
            {
                if(_selectedStationItem != value){
                    _selectedStationItem = value;
                    OnPropertyChanged(nameof(SelectedStationItem));
                    ucStandGird.CurStationItem = value;
                    //Apply_UCStandDetaisl_Title(value);
                    Apply_Station_Title(value);
                }
            }
        }


        private int _totalStandRecords;
        public int TotalStandRecords
        {
            get => _totalStandRecords;
            set
            {
                if (_totalStandRecords != value)
                {
                    _totalStandRecords = value;
                    OnPropertyChanged(nameof(TotalStandRecords));
                }
            }
        }

        public CfginiItem mConfigItem { get; set; }


        private void Apply_UCStandDetaisl_Title(StandItem standItem)
        {
            txtStandName.Text = standItem == null ? "" :  $"{standItem.Index}.";
        }

        //站点名称
        private void Apply_Station_Title(StationItem stationItem)
        {
            pnlDetailsFunc.Visibility = stationItem == null ? Visibility.Hidden : Visibility.Visible;
            txtStationName.Text = stationItem == null ? "请选择站点" : $"站点: {stationItem.StationId}";
        }


        private void InitRightControls(StandDetailItem standDetailsItem)
        {
            pnlImage.Visibility = txtRightItemIndex.Visibility =
                standDetailsItem == null ? Visibility.Collapsed : Visibility.Visible;
            //pnlResult.Visibility = Visibility.Hidden;
        }


        private string _findStationId;
        public string FindStationId
        {
            get => _findStationId;
            set
            {
                if (_findStationId != value)
                {
                    _findStationId = value;
                    OnPropertyChanged(nameof(FindStationId));
                    //ucStationGrid.ChangeFindStationId(FindStationId);
                }
            }
        }

        public UCStandMain()
        {
            InitializeComponent();

            StandItemList = new BulkObservableCollection<StandItem>();
            dgStand.ItemsSource = StandItemList;

            //this.btnStandExport.Click += BtnStandExport_Click;
            
            ucStandGird.OnSelectedStandDetailItemChanged += UcStandGird_OnSelectedStandDetailsItemChanged;
           
            IsResultEditing = false;
            Apply_UCStandDetaisl_Title(null);

            Apply_Station_Title(null);

            //SelectedStandItem = null;
            txtFindStationId.Text = "";
            FindStationId = "";

            InitRightControls(null);

            mConfigItem = CfginiItem.GetConfigItem();

            StandPage = new PageModel
            {
                //PageSize = mConfigItem.CatalogPageSize,
                PageSize = mConfigItem.PageSize1, //mConfigItem.StandCatalogPageSize,
                PageNumber = 1,
            };
            //LoadStandItemList();

            //ucStandGird.OnStandItemCountChanged += UcStandGird_OnStandItemCountChanged1;
                //UcStandGird_OnStandItemCountChanged;
            ucStandGird.OnDeleteStandDetailItem += UcStandGird_OnDeleteStandDetailItem;

            //mConfigItem.OnStandCatalogPageSizeChanged += MConfigItem_OnStandCatalogPageSizeChanged;
            mConfigItem.OnPageSize1Changed += MConfigItem_OnPageSize1Changed;

            this.DataContext = this;
            // 启动异步初始化，确保不会阻塞构造函数
            LoadStandItemListAsync();
            InitStationMarkTypeKVS();
            SelectedStationMarkType = MarkFindType.ALL;

            //控制左右2侧栏目的显示
            LeftVisiable = true;
            ChangeLeftVisiable(LeftVisiable);
            RightVisiable = true;
            ChangeRightVisiable(RightVisiable);

            ucStationGrid.OnStationItemChange += UcStationGrid_OnStationItemChange;
            //ucStationGrid.Station_Config += UcStationGrid_Station_Config;
            ucStandGird.OnStandDetailMark += UcStandGird_OnStandDetailMark;
        }



        private void UcStandGird_OnStandDetailMark(string standId, string stationId)
        {
            //throw new NotImplementedException();
            ucStationGrid.ChangeMarkCount();
        }

        //修改参数
        //private void UcStationGrid_Station_Config(StationItem item)
        //{
        //    //第一条数据
        //    EditStationDlg2 dialog = new EditStationDlg2(item)
        //    {
        //        Owner = Application.Current.MainWindow,
        //        WindowStartupLocation = WindowStartupLocation.CenterOwner
        //    };
        //    if (dialog.ShowDialog() == true)
        //    {
        //        //stationItem = dialog.mStationItem;
        //        item = dialog.mStationItem;
        //    }
        //}

        private void UcStationGrid_OnStationItemChange(StationItem stationItem)
        {
            SelectedStationItem = stationItem;
        }

        private async void MConfigItem_OnPageSize1Changed(int pageSize1)
        {
            if (!_semaphore.Wait(0)) return;  // 防止重复点击

            try
            {
                StandPage.InitDefaulValue(pageSize1);
                bool blLoad = await LoadStandItemList();
                if (blLoad)
                {
                    SelectedStandItem = null;
                }
            }
            catch { }
            finally
            {
                _semaphore.Release();
            }
        }

        //private async void MConfigItem_OnStandCatalogPageSizeChanged(int pageSize)
        //{
        //    //throw new NotImplementedException();
        //    StandPage.InitDefaulValue(pageSize);
        //    bool blLoad = await LoadStandItemList();
        //    if (blLoad)
        //    {
        //        SelectedStandItem = null;
        //    }
        //}

        private async void LoadStandItemListAsync()
        {
            if (!_semaphore.Wait(0)) return;  // 防止重复点击
            try
            {
                await LoadStandItemList();
            }
            catch { }
            finally
            {
                _semaphore.Release();
            }
        }

        //private void UcStandGird_OnStandItemCountChanged(object sender, StandItemCountChangedEventArgs e)
        //{
        //    //Detail的数量发生变化        
        //    RefreshStandItemById(e.mStandItem.StandId);
        //}

        //private void UcStandGird_OnStandItemCountChanged1(StandItem standItem)
        //{
        //    //Detail的数量发生变化        
        //    RefreshStandItemById(standItem.StandId);
        //}

        private void UcStandGird_OnDeleteStandDetailItem(string standId)
        {
            RefreshStandItemById(standId);
        }

        private async void RefreshStandItemById(string standId)
        {
            if ( string.IsNullOrWhiteSpace(standId) ) return;

            VStand vStand = null;
            await Task.Run(() =>
            {
                vStand = DBStand.GetVStandById(standId);
            });

            if (vStand != null)
            {
                //var NewStandItem = new StandItem(vStand);
                foreach (var standItem in StandItemList)
                {
                    if (standItem.StandId == vStand.StandId)
                    {
                        // ObjectHelper.CopyMatchingFields(NewStandItem, standItem);
                        ObjectHelper.CopyMatchingFields(vStand, standItem);
                        break;
                    }
                }//foreach
            }//if vpatch!=null
        }


        private async Task<bool> LoadStandItemList()
        {
            StandItemList.Clear();

            try
            {
                var result = await Task.Run(() =>
                {
                   return DBStand.GetPagedVStands(StandPage.PageNumber, StandPage.PageSize);
                });

                TotalStandRecords = result.Item1;
                StandPage.PageCount = result.Item2;
                List<VStand> stands = result.Item3;

                //int index = 0;
                //foreach (VStand vStand in stands)
                //{
                //    index++;
                //    StandItem standItem = new StandItem(vStand);
                //    standItem.Index = index + (StandPage.PageNumber - 1) * StandPage.PageSize;
                //    StandItemList.Add(standItem);
                //}
                var standItems = stands.Select((vStand, i) => new StandItem(vStand)
                {
                    Index = (StandPage.PageNumber - 1) * StandPage.PageSize + i + 1
                }).ToList();
                StandItemList.AddRange(standItems);

                if (StandItemList.Count > 0)
                {
                    //dgStand.ScrollIntoView(StandItemList[0]);
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(Application.Current.MainWindow,
                $"加载数据时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }
        }


        private void UcStandGird_OnSelectedStandDetailsItemChanged(object sender, StandDetailItemChangedEventArgs e)
        {
            InitRightControls(e.SelectedDataItem);
            txtRightItemIndex.Text = string.Empty;
            if (e.SelectedDataItem != null)
            {
                ucImageSource.ImageSource = e.SelectedDataItem.SrcImage;
                ucImageSource.ImageName = "原始图片";
                //txtRightResult.Text = e.SelectedDataItem.StandValue;
                IsResultEditing = false;

                if(SelectedStandItem != null)
                {
                    txtRightItemIndex.Text = $"{SelectedStandItem.Index}. - {e.SelectedDataItem.Index}.";
                }
            }          
        }

        //导出模板
        private void BtnStandExport_Click(object sender, RoutedEventArgs e)
        {
            //查询所有的数据
            if (SelectedStandItem == null) return;

            List<TStandDetail> standDetails = DBStand.GetAllStandDetails(SelectedStandItem.StandId);
            if (standDetails.Count <= 0) return;

            string fileName = $"{SelectedStandItem.StandName}_{standDetails.Count}.xlsx"; 

            //创建保存文件对话框
            VistaSaveFileDialog saveFileDialog = new VistaSaveFileDialog
            {
                Filter = "Excel 文件 (*.xlsx)|*.xlsx",
                FileName = fileName,
                Title = "选择模板保存路径"
            };

            // 如果用户选择了路径并点击保存
            if (saveFileDialog.ShowDialog() == true){
                string titleInfo = "正在导出模板数据，请稍后...";
                WaitWindow waitWindow = new WaitWindow(titleInfo)
                {
                    Owner = Application.Current.MainWindow,
                    WindowStartupLocation = WindowStartupLocation.CenterOwner
                };
                waitWindow.Show();

                string filePath = saveFileDialog.FileName;

                try{
                    // 创建Excel包
                    using (ExcelPackage package = new ExcelPackage()){
                        var worksheet = package.Workbook.Worksheets.Add("Sheet1");

                        // 表头
                        worksheet.Cells[1, 1].Value = "图像";
                        worksheet.Cells[1, 2].Value = "标准答案";

                        // 设置表头样式
                        using (var range = worksheet.Cells[1, 1, 1, 2])
                        {
                            //range.Style.Font.Bold = false;
                            range.Style.Font.Name = "等线";
                            range.Style.Font.Size = 11;
                            //range.Style.Fill.PatternType = ExcelFillStyle.Solid;
                            //range.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightBlue);
                            range.AutoFitColumns();
                        }

                        // 填充数据
                        for (int i = 0; i < standDetails.Count; i++)
                        {
                            worksheet.Cells[i + 2, 1].Value = standDetails[i].SrcImage;
                            worksheet.Cells[i + 2, 2].Value = standDetails[i].StandValue;

                            // 设置行字体
                            worksheet.Cells[i + 2, 1, i + 2, 2].Style.Font.Name = "等线";
                            worksheet.Cells[i + 2, 1, i + 2, 2].Style.Font.Size = 11;
                            //worksheet.Cells[i + 2, 1, i + 2, 2].Style.Font.Color.SetColor(System.Drawing.Color.Black);
                        }

                        // 设置列宽
                        worksheet.Column(1).Width = 50;  // 姓名列
                        worksheet.Column(2).Width = 20;  // 年龄列

                        // 或者自动调整列宽
                        //worksheet.Cells.AutoFitColumns();

                        // 保存到用户选择的路径
                        FileInfo excelFile = new FileInfo(filePath);
                        package.SaveAs(excelFile);                        
                        MessageBox.Show("Excel导出成功！");
                    }
                }
                catch (Exception ex){                
                    MessageBox.Show($"导出失败: {ex.Message}");
                }
                waitWindow.Close();
            }
        }

        private void BtnStandImport_Click(object sender, RoutedEventArgs e)
        {
            //throw new NotImplementedException();
        }

        private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            // 只允许数字输入
            e.Handled = !Regex.IsMatch(e.Text, @"^\d$");
        }

        private void TxtRightResult_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            // 只允许数字输入
            e.Handled = !Regex.IsMatch(e.Text, @"^\d$");
        }

        private void BtnEditRightResult_Click(object sender, RoutedEventArgs e)
        {
            IsResultEditing = true;
        }

        private void BtnSubmitRightResult_Click(object sender, RoutedEventArgs e)
        {
            IsResultEditing = false;
        }

        private void BtnCancelRightResult_Click(object sender, RoutedEventArgs e)
        {
            IsResultEditing = false;
        }

        private async void BtnStandNextPage_Click(object sender, RoutedEventArgs e)
        {
            if (!_semaphore.Wait(0)) return;  // 防止重复点击

            try
            {
                if (StandPage.PageNumber < StandPage.PageCount)
                {
                    StandPage.PageNumber += 1;
                    bool blLoad = await LoadStandItemList();
                    if (blLoad && StandItemList.Count > 0)
                    {
                        //dgStand.ScrollIntoView(StandItemList[0]);
                        var scrollViewer = GetDgStandScrollViewer(dgStand);
                        scrollViewer?.ScrollToTop();
                    }
                }
            }
            catch { }
            finally
            {
                _semaphore.Release();
            }
        }

        private async void BtnStandPrePage_Click(object sender, RoutedEventArgs e)
        {
            if (!_semaphore.Wait(0)) return;  // 防止重复点击
            try
            {
                if (StandPage.PageNumber > 1)
                {
                    StandPage.PageNumber -= 1;
                    bool blLoad = await LoadStandItemList();
                    if (blLoad && StandItemList.Count > 0)
                    {
                        //dgStand.ScrollIntoView(StandItemList[0]);               
                        var scrollViewer = GetDgStandScrollViewer(dgStand);
                        scrollViewer?.ScrollToTop();
                    }
                }
            }
            catch { }
            finally
            {
                _semaphore.Release();
            }
        }

        private void BtnStandDetailFirstPage_Click(object sender, RoutedEventArgs e)
        {
            ucStandGird.FirstPage();
        }

        private void BtnStandDetailNextPage_Click(object sender, RoutedEventArgs e)
        {
            ucStandGird.NextPage();
        }

        private void BtnStanddetailPrePage_Click(object sender, RoutedEventArgs e)
        {
            ucStandGird.PrePage();
        }

        private void BtnStandDetailLastPage_Click(object sender, RoutedEventArgs e)
        {
            ucStandGird.LastPage();
        }

        private void BtnStandDetailSpeciPage_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                int pageNumber = int.Parse(txtStandDetailPageNumber.Text.ToString());
                ucStandGird.SpeciPage(pageNumber);
            }
            catch
            {

            }           
        }

        private async void BtnAddStand_Click(object sender, RoutedEventArgs e)
        {
            //List<string> tableNames = SQLiteHelper.GetAllTables();
            if (!_semaphore.Wait(0)) return;  // 防止重复点击
            try
            {
                var dialog = new AddStandDialog()
                {
                    Owner = Application.Current.MainWindow,
                    WindowStartupLocation = WindowStartupLocation.CenterOwner
                };
                if (dialog.ShowDialog() == true)
                {
                    StandPage.InitDefaulValue();
                    bool blLoad = await LoadStandItemList();
                    if (blLoad && StandItemList.Count > 0)
                    {
                        SelectedStandItem = StandItemList[0];
                        //dgStand.ScrollIntoView(StandItemList[0]);
                        var scrollViewer = GetDgStandScrollViewer(dgStand);
                        scrollViewer?.ScrollToTop();
                    }
                }
            }
            catch { }
            finally
            {
                _semaphore.Release();
            }
        }

        private void BtnDelStand_Click(object sender, RoutedEventArgs e)
        {
            DeleteStandItem();
        }

        private async void DeleteStandItem()
        {
            //bool blDelete = false;
            if (SelectedStandItem == null) return;  // blDelete;

            MessageBoxResult result = MessageBox.Show(
                $"您确定要删除[{SelectedStandItem.StandName}]任务吗？\n此操作无法撤销。",
                "确认删除",
                MessageBoxButton.YesNo, // 提供“是”和“否”按钮
                MessageBoxImage.Warning // 使用警告图标
            );

            if (result != MessageBoxResult.Yes)
            {
                return; // blDelete;
            }

            //开始删除操作
            string titleInfo = "正在删除，请稍候...";
            WaitWindow waitWindow = new WaitWindow(titleInfo)
            {
                Owner = Application.Current.MainWindow,
                WindowStartupLocation = WindowStartupLocation.CenterOwner
            };

            waitWindow.Show();

            try
            {
                //执行异步删除逻辑
                bool deleteSuccess = false;
                await Task.Run(() =>
                {
                    deleteSuccess = DBStand.DeleteStandAndDetails(SelectedStandItem.StandId);
                    //Task.Delay(200).Wait(); // 模拟延迟
                });

                if (deleteSuccess)
                {
                    StandItemList.Remove(SelectedStandItem);                        
                    SelectedStandItem = null;
                    TotalStandRecords -= 1;
                    //blDelete = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(Application.Current.MainWindow, $"删除失败：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                //关闭等待窗口
                waitWindow.Close();
            }
            //return blDelete;
        }


        private async void BtnRefresh_Click(object sender, RoutedEventArgs e)
        {
            if (!_semaphore.Wait(0)) return;  // 防止重复点击

            try
            {
                StandPage.InitDefaulValue();
                bool blLoad = await LoadStandItemList();
                if (blLoad && StandItemList.Count > 0)
                {
                    //dgStand.ScrollIntoView(StandItemList[0]);    
                    var scrollViewer = GetDgStandScrollViewer(dgStand);
                    scrollViewer?.ScrollToTop();
                }
            }
            catch { }
            finally
            {
                _semaphore.Release();
            }
        }

        private void MiDeleteStand_Click(object sender, RoutedEventArgs e)
        {
            DeleteStandItem();
        }

        private void MiUpdateStandname_Click(object sender, RoutedEventArgs e)
        {
            if (SelectedStandItem == null) return;

            EditNameDlg editNameDlg = new EditNameDlg("模板", SelectedStandItem.StandName)
            {
                Owner = Application.Current.MainWindow,
                WindowStartupLocation = WindowStartupLocation.CenterOwner
            };
            if (editNameDlg.ShowDialog() == true)
            {
                UpdateStandName(SelectedStandItem, editNameDlg.EditName);
            }
        }

        private async void UpdateStandName(StandItem standItem,string newStandName)
        {
            try
            {
                bool blUpdate = false;
                await Task.Run(() =>
                {
                    blUpdate = DBStand.UpdateStandName(standItem.StandId, newStandName);
                });
                if (blUpdate)
                {
                    standItem.StandName = newStandName;
                }
                else
                {
                    MessageBox.Show(Application.Current.MainWindow, $"修改模板名称失败。", "警告",
                        MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(Application.Current.MainWindow, $"修改模板名称：{ex.Message}错误", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void BtnRefreshDetail_Click(object sender, RoutedEventArgs e)
        {
            //ucStandGird.CurStandItem = null;
            //ucStandGird.CurStandItem = SelectedStandItem;
            //ucStandGird.CurStationItem = null;
            ucStandGird.CurStationItem = SelectedStationItem;
        }

        //private async void BtnSelectImageFloder_Click(object sender, RoutedEventArgs e)
        //{
        //    // 创建 VistaFolderBrowserDialog 实例
        //    var dialog = new VistaFolderBrowserDialog();
        //    dialog.Description = "请选择模板图片文件夹";
        //    dialog.UseDescriptionForTitle = true; // 使用 Description 作为窗口标题

        //    // 显示对话框并检查用户是否点击了“确定”
        //    if (dialog.ShowDialog() == true)
        //    {
        //        // 获取用户选择的文件夹路径
        //        string selectedFolderPath = dialog.SelectedPath;
        //        await ucStandGird.ImportStandImageFloder(selectedFolderPath);
        //    }
        //}

        private void BtnLeftCtl_Click(object sender, RoutedEventArgs e)
        {
            bool visiable = !LeftVisiable;
            ChangeLeftVisiable(visiable);
        }

        private void BtnRightCtl_Click(object sender, RoutedEventArgs e)
        {
            bool visiable = !RightVisiable;
            ChangeRightVisiable(visiable);
        }

        private void ChangeLeftVisiable(bool visiable)
        {
            LeftVisiable = visiable;
            colLeft.Width = new GridLength(visiable ? COLUMN_LEFT_WIDTH : 0);
            btnLeftCtl.Content = visiable ? "◀️" : "▶️";
            btnLeftCtl.ToolTip = visiable ? "点击隐藏左侧栏" : "点击显示左侧栏";
        }

        private void ChangeRightVisiable(bool visiable)
        {
            RightVisiable = visiable;
            colRight.Width = new GridLength(visiable ? COLUMN_RIGHT_WIDTH : 0);
            btnRightCtl.Content = visiable ? "▶️" : "◀️";
            btnRightCtl.ToolTip = visiable ? "点击隐藏右侧栏" : "点击显示右侧栏";
        }

        private async void BtnStationFirstPage_Click(object sender, RoutedEventArgs e)
        {
            if (!await _semaphore2.WaitAsync(0)) return;  // 防止重复点击
            try
            {
                await ucStationGrid.FirstPage();
            }
            catch { }
            finally
            {
                _semaphore2.Release();
            }
        }

        private async void BtnStationPrePage_Click(object sender, RoutedEventArgs e)
        {
            if (!await _semaphore2.WaitAsync(0)) return;  // 防止重复点击
            try
            {
                await ucStationGrid.PrePage();

            }
            catch { }
            finally
            {
                _semaphore2.Release();
            }
        }

        private async void BtnStationNextPage_Click(object sender, RoutedEventArgs e)
        {
            if (!await _semaphore2.WaitAsync(0)) return;  // 防止重复点击
            try
            {
                await ucStationGrid.NextPage();
            }
            catch { }
            finally
            {
                _semaphore2.Release();
            }

        }

        private async void BtnStationLastPage_Click(object sender, RoutedEventArgs e)
        {
            if (!await _semaphore2.WaitAsync(0)) return;  // 防止重复点击
            try
            {
                await ucStationGrid.LastPage();
            }
            catch { }
            finally
            {
                _semaphore2.Release();
            }

        }

        private async void BtnStationSpeciPage_Click(object sender, RoutedEventArgs e)
        {
            if (!await _semaphore2.WaitAsync(0)) return;  // 防止重复点击
            try
            {
                int pageNumber = int.Parse(txtStationPageNumber.Text.ToString());
                await ucStationGrid.SpeciPage(pageNumber);
            }
            catch{}
            finally
            {
                _semaphore2.Release();
            }
        }

        private async void BtnQuery_Click(object sender, RoutedEventArgs e)
        {
            if (!await _semaphore2.WaitAsync(0)) return;  // 防止重复点击

            try
            {
                FindStationId = txtFindStationId.Text.Trim();
                await ucStationGrid.ChangeFind(FindStationId, SelectedStationMarkType, SelectedStandItem.StandId);
                //Apply_UCStandDetaisl_Title(SelectedStationItem);
                Apply_Station_Title(SelectedStationItem);
            }
            catch { }
            finally
            {
                _semaphore2.Release();
            }
        }

        private async void BtnRefreshStation_Click(object sender, RoutedEventArgs e)
        {
            if (!await _semaphore2.WaitAsync(0)) return;  // 防止重复点击

            try
            {
                FindStationId = txtFindStationId.Text.Trim();
                await ucStationGrid.ChangeFind(FindStationId, SelectedStationMarkType, SelectedStandItem.StandId);
                //Apply_UCStandDetaisl_Title(SelectedStationItem);
                Apply_Station_Title(SelectedStationItem);
            }
            catch { }
            finally
            {
                _semaphore2.Release();
            }
        }

        private void BtnImportStand_Click(object sender, RoutedEventArgs e)
        {           
            ImportStand(SelectedStandItem);
        }

        private void BtnExportStand_Click(object sender, RoutedEventArgs e)
        {
            ExportStand(SelectedStandItem,null);
        }

        //部分导出
        private void BtnPartExportStand_Click(object sender, RoutedEventArgs e)
        {
            //查找站点中MarkCount中大于>0的数据
            PartExportStand(SelectedStandItem);
        }

        private void MiExport_Click(object sender, RoutedEventArgs e)
        {

            ExportStand(SelectedStandItem,null);
        }

        private void MiImport_Click(object sender, RoutedEventArgs e)
        {
            ImportStand(SelectedStandItem);
        }

        private void MiPartExport_Click(object sender, RoutedEventArgs e)
        {

            PartExportStand(SelectedStandItem);
        }

        private void PartExportStand(StandItem standItem)
        {
            if (standItem == null)
            {
                MessageBox.Show(Application.Current.MainWindow, "请先选择模板!","提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            btnPartExportStand.IsEnabled = false;

            List<TStation> stationList = DBStation.GetAllVStation(SelectedStandItem.StandId);

            SelecteStationDlg dialog = new SelecteStationDlg(stationList)
            {
                Owner = Application.Current.MainWindow,
                WindowStartupLocation = WindowStartupLocation.CenterOwner
            };
            if (dialog.ShowDialog() == true)
            {
                List<TStation> selctedStationList = dialog.StationList2.ToList();
                ExportStand(SelectedStandItem, selctedStationList);
            }

            btnPartExportStand.IsEnabled = true;
        }


        //导出
        private async void ExportStand(StandItem standItem,List<TStation> stations)
        {
            if (standItem == null)
            {
                MessageBox.Show(Application.Current.MainWindow, "请先选择模板!", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            string fileName = $"{standItem.StandName}_{ThisApp.GetNowTime_yyyyMMddHHmmss()}.json";

            // 2. 弹出保存对话框
            VistaSaveFileDialog saveFileDialog = new VistaSaveFileDialog
            {
                FileName = fileName, //Path.GetFileName(sourcePath),  // 默认文件名
                DefaultExt = Path.GetExtension(fileName),
                Filter = $"JSON Files (*{Path.GetExtension(fileName)})|*{Path.GetExtension(fileName)}|All Files (*.*)|*.*"
            };

            if (saveFileDialog.ShowDialog() != true)
            {
                return;
            }

            string titleInfo = "正在导出数据，请稍后...";
            WaitWindow waitWindow = new WaitWindow(titleInfo)
            {
                Owner = Application.Current.MainWindow,
                WindowStartupLocation = WindowStartupLocation.CenterOwner
            };
            waitWindow.Show();

            try
            {
                var blExport = await Task.Run(() =>
                {
                    return ExportStand_to_json(standItem,stations,saveFileDialog.FileName);
                });
                string exportResult = "导出" + (blExport ? "成功" : "失败");
                MessageBox.Show(Application.Current.MainWindow, exportResult, "提示", MessageBoxButton.OK,
                    MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(Application.Current.MainWindow, $"失败：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                //关闭等待窗口
                waitWindow.Close();
            }
        }

        private bool ExportStand_to_json(StandItem standItem,List<TStation> stations,string fileName)
        {
            //查找站点中MarkCount中大于>0的数据

            List<TStation> stationList; // = DBStation.GetAllVStation(standItem.StandId);
            if(stations == null)
            {
                stationList = DBStation.GetAllVStation(standItem.StandId); 
            }
            else
            {
                stationList = stations;
            }


            List<TStandDetail> allStandDetails = new List<TStandDetail>();

            foreach (var station in stationList)
            {
                var standDetails = DBStand.GetAllStandDetails(standItem.StandId, station.StationId);

                allStandDetails.AddRange(standDetails);
            }

            if (allStandDetails.Count <= 0)
            {
                Dispatcher.Invoke(() =>
                {
                    MessageBox.Show(Application.Current.MainWindow, "没有已标注的数据可导出！", "提示", MessageBoxButton.OK,
                        MessageBoxImage.Error);
                });
                return false;
            }

            string json = JsonConvert.SerializeObject(allStandDetails, Formatting.Indented); // 格式化 JSON
            File.WriteAllText(fileName, json);

            return true;
        }

        //导入
        private async void ImportStand(StandItem standItem)
        {
            if (standItem == null)
            {
                MessageBox.Show(Application.Current.MainWindow, "请先选择模板!","提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            // 打开文件选择对话框
            var openFileDialog = new OpenFileDialog
            {
                //Filter = "Excel Files (*.xls;*.xlsx)|*.xls;*.xlsx",
                Filter = "Json Files (*.json)|*.json",
                Title = "选择JSON文件"
            };


            if (openFileDialog.ShowDialog() != true)
            {
                return;
            }

            string fileName = openFileDialog.FileName;

            string titleInfo = "正在导入数据，请稍后...";
            WaitWindow waitWindow = new WaitWindow(titleInfo)
            {
                Owner = Application.Current.MainWindow,
                WindowStartupLocation = WindowStartupLocation.CenterOwner
            };
            waitWindow.Show();

            try
            {
                var blExport = await Task.Run(() =>
                {
                    return ImportStand_from_json(standItem, fileName);
                });
                string exportResult = "导入" + (blExport ? "成功" : "失败");
                MessageBox.Show(Application.Current.MainWindow, exportResult, "提示", MessageBoxButton.OK,
                    MessageBoxImage.Information);

                //导入后要刷新数据
                //ucStationGrid.ChangeFind()
                //SelectedStandItem = null;
                //再获取数据更新
                VStand vStand = DBStand.GetVStandById(standItem.StandId);
                StandItem newStandItem = new StandItem();
                if(vStand != null)
                {
                    ObjectHelper.CopyMatchingFields(vStand, SelectedStandItem);
                }

                //刷新一下
                //ucStationGrid.ChangeFind(FindStationId, SelectedStationMarkType, "");                
                await ucStationGrid.ChangeFind(FindStationId, SelectedStationMarkType, _selectedStandItem.StandId);

                //SelectedStandItem = newStandItem;
                //dgStand.SelectedItem = SelectedStandItem;
            }
            catch (Exception ex)
            {
                MessageBox.Show(Application.Current.MainWindow, $"失败：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                //关闭等待窗口
                waitWindow.Close();
            }
        }

        private bool ImportStand_from_json(StandItem standItem,string fileName)
        {
            string json = File.ReadAllText(fileName);
            List<TStandDetail> standDetails =  JsonConvert.DeserializeObject<List<TStandDetail>>(json) ?? new List<TStandDetail>();

            if(standDetails == null || standDetails.Count == 0)
            {
                Dispatcher.Invoke(() =>
                {
                    MessageBox.Show(Application.Current.MainWindow, "没有有效的数据可导入！", "提示", MessageBoxButton.OK,
                        MessageBoxImage.Error);
                });
                return false;
            }

            //使用新的stand_id值，即其它
            foreach(var detail in standDetails)
            {
                detail.StandId = standItem.StandId;
                detail.StandDetailId = Guid.NewGuid().ToString().Replace("-","");
                detail.CreateTime = ThisApp.GetNowTime_yyyyMMddHHmmss();
            }

            //开始批量插入数据库
            bool blInsert = DBStand.InsertStandDetails(standDetails);

            if (blInsert)
            {
                //获取不重复的站点
                List<StationInfo> stationInfos = DBStand.GetUniqueStationInfo(standItem.StandId);
                //先删除属于standId的站点，再插入
                blInsert = false;
                //bool blDelete = DBStation.DeleteTStationByStandId(standItem.StandId);
                //if(blDelete)
                //{
                    blInsert = DBStation.InsertTStations(stationInfos);
                //}

            }


            return blInsert;
        }

        private ScrollViewer _dgStandScrollViewer;

        private ScrollViewer GetDgStandScrollViewer(DependencyObject obj)
        {
            if (_dgStandScrollViewer != null)
            {
                return _dgStandScrollViewer;
            }

            if (obj is ScrollViewer)
            {
                _dgStandScrollViewer = (ScrollViewer)obj;
                return obj as ScrollViewer;
            }

            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                var child = VisualTreeHelper.GetChild(obj, i);
                var scrollViewer = GetDgStandScrollViewer(child);
                if (scrollViewer != null)
                {
                    _dgStandScrollViewer = scrollViewer;
                    return scrollViewer;
                }
            }

            return null;
        }
        /////////////////////////////////////////////////////////////////////////////
    }

    public enum MarkFindType
    {
        ALL = 1,
        MARK_YES = 2,
        MARK_NO = 3
    }

    //-----------------------------------------------------------
}
