using MeterVision.Config;
using MeterVision.db;
using MeterVision.Dlg;
using MeterVision.model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
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.Patch
{
    /// <summary>
    /// UCCompMain.xaml 的交互逻辑
    /// </summary>
    public partial class UCCompMain : UserControl,INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

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

        private const int COLUMN_LEFT_WIDTH = 450;
        private bool LeftVisiable = true;       //表示左侧的显示状态

        public ObservableCollection<KeyValuePair<CompFindType, string>> CompFindTypeKVs { get; set; }

        //当前选择的筛选类型
        private CompFindType _selectedCompFindType;
        public CompFindType SelectedCompFindType
        {
            get => _selectedCompFindType;
            set
            {
                if(_selectedCompFindType != value)
                {
                    _selectedCompFindType = value;
                    OnPropertyChanged(nameof(SelectedCompFindType));
                    //改变显示明细的项的函数
                    ucCompGird.ChangeCompItemOrFindType(SelectedCompItem, SelectedCompFindType);
                }
            }
        }

        public PageModel CompPage { get; set; }

        //定义比较目录的数据源
        public ObservableCollection<CompItem> CompItemList { get; set; }

        public CfginiItem mConfigItem { get; set; }

        private CompItem _selectedCompItem;
        public CompItem SelectedCompItem
        {
            get => _selectedCompItem;
            set
            {
                _selectedCompItem = value;
                OnPropertyChanged(nameof(SelectedCompItem));
                //调用显示明细项的函数
                ucCompGird.ChangeCompItemOrFindType(SelectedCompItem, SelectedCompFindType);
                Apply_UCCompDetail_Title(value);
            }
        }

        private void Apply_UCCompDetail_Title(CompItem compItem)
        {
            if(compItem == null)
            {
                pnlDetailFunc.Visibility = Visibility.Hidden;
                txtCompName.Text = "请选择左侧比较项";
            }
            else
            {
                pnlDetailFunc.Visibility = Visibility.Visible;
                txtCompName.Text = $"{compItem.Index}. {compItem.NPatchName} vs {compItem.OPatchName}";
            }
        }

        //总共的Comp数量
        private int _totalCompRecords;
        public int TotalCompRecords
        {
            get => _totalCompRecords;
            set
            {
                if(_totalCompRecords != value)
                {
                    _totalCompRecords = value;
                    OnPropertyChanged(nameof(TotalCompRecords));
                }
            }
        }

        private void InitCompFindTypeKVs()
        {
            CompFindTypeKVs = new ObservableCollection<KeyValuePair<CompFindType, string>>()
            {
                new KeyValuePair<CompFindType, string>(CompFindType.ALL,"所有"),
                new KeyValuePair<CompFindType, string>(CompFindType.NERROR_ORIGHT,"新错+旧对"),
                new KeyValuePair<CompFindType, string>(CompFindType.NRIGHT_OERROR,"新对+旧错"),
                new KeyValuePair<CompFindType, string>(CompFindType.NRIGHT_ORIGHT,"新旧都对"),
                new KeyValuePair<CompFindType, string>(CompFindType.NERROR_OERROR,"新旧都错"),
            };
        }

        public UCCompMain()
        {
            InitializeComponent();

            CompItemList = new ObservableCollection<CompItem>();
            dgComp.ItemsSource = CompItemList;

            Apply_UCCompDetail_Title(null);

            mConfigItem = CfginiItem.GetConfigItem();

            CompPage = new PageModel
            {
                PageSize = mConfigItem.PatchCatalogPageSize,
                PageNumber = 1
            };

            mConfigItem.OnPatchCatalogPageSizeChnaged += MConfigItem_OnPatchCatalogPageSizeChnaged;

            this.DataContext = this;

            LoadCompItemListAsync();
            InitCompFindTypeKVs();
            SelectedCompFindType = CompFindType.ALL;
                //CompFindType.NERROR_ORIGHT;

            //控制左侧栏目的显示
            LeftVisiable = true;
            ChangeLeftVisiable(LeftVisiable);
        }

        private async void MConfigItem_OnPatchCatalogPageSizeChnaged(int pageSize)
        {
            CompPage.InitDefaulValue(pageSize);
            bool blLoad = await LoadCompItemList();
            if (blLoad)
            {
                SelectedCompItem = null;
            }
        }

        private async void LoadCompItemListAsync()
        {
            await LoadCompItemList();
        }

        private async Task<bool> LoadCompItemList()
        {
            CompItemList.Clear();

            try
            {
                var result = await Task.Run(() =>
                {
                    return DBComp.GetPagedVComps(CompPage.PageNumber, CompPage.PageSize);
                });

                TotalCompRecords = result.Item1;
                CompPage.PageCount = result.Item2;
                List<VComp> comps = result.Item3;

                int index = 0;
                foreach(VComp vComp in comps)
                {
                    index++;
                    CompItem compItem = new CompItem(vComp);
                    compItem.Index = index + (CompPage.PageNumber - 1) * CompPage.PageSize;
                    CompItemList.Add(compItem);
                }
                return true;
            }
            catch(Exception ex)
            {
                MessageBox.Show(Application.Current.MainWindow,
                    $"e加载数据时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }
        }


        private async void BtnAddComp_Click(object sender, RoutedEventArgs e)
        {
            AddCompDlg2 dialog = new AddCompDlg2()
            {
                Owner = Application.Current.MainWindow,
                WindowStartupLocation = WindowStartupLocation.CenterOwner
            };
            if(dialog.ShowDialog() == true)
            {
                TComp comp = dialog.NewComp;
                CompPage.InitDefaulValue();
                bool blLoad = await LoadCompItemList();
                if(blLoad && CompItemList.Count > 0)
                {
                    SelectedCompItem = CompItemList[0];
                    dgComp.ScrollIntoView(SelectedCompItem);
                }
            }
        }

        private async void BtnDelComp_Click(object sender, RoutedEventArgs e)
        {
            bool blDelete = await DeleteCompItem();
        }

        private async void MiDeleteCompr_Click(object sender, RoutedEventArgs e)
        {
            bool blDelete = await DeleteCompItem();
        }

        private async Task<bool> DeleteCompItem()
        {
            bool blDelete = false;
            if (SelectedCompItem == null) return blDelete;

            // 弹出确认对话框
            MessageBoxResult result = MessageBox.Show(
                $"您确定要删除[{SelectedCompItem.NPatchName} VS {SelectedCompItem.OPatchName}]的比较吗？\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 = DBComp.DelteTComp(SelectedCompItem.CompId);
                    //Task.Delay(200).Wait(); // 模拟延迟                   
                });

                if (deleteSuccess)
                {
                    //await LoadPatchItemList();
                    // 在 UI 线程上更新 ObservableCollection
                    await Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        CompItemList.Remove(SelectedCompItem);
                        SelectedCompItem = null;
                        TotalCompRecords -= 1;
                    }));
                    blDelete = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(Application.Current.MainWindow, $"删除失败：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                //关闭等待窗口
                waitWindow.Close();
            }
            return blDelete;
        }

        private void BtnRefreshDetail_Click(object sender, RoutedEventArgs e)
        {
            ucCompGird.ChangeCompItemOrFindType(null, SelectedCompFindType);
            ucCompGird.ChangeCompItemOrFindType(SelectedCompItem, SelectedCompFindType);
        }


        private async void BtnRefresh_Click(object sender, RoutedEventArgs e)
        {
            CompPage.InitDefaulValue();
            bool blLoad = await LoadCompItemList();
            if(blLoad && CompItemList.Count > 0)
            {
                dgComp.ScrollIntoView(CompItemList[0]);
            }
        }

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


        private async void BtnCompPrePage_Click(object sender, RoutedEventArgs e)
        {
            if (CompPage.PageNumber > 1)
            {
                CompPage.PageNumber -= 1;
                bool blLoad = await LoadCompItemList();
                if (blLoad && CompItemList.Count > 0)
                {
                    dgComp.ScrollIntoView(CompItemList[0]);

                }
            }
        }

        private async void BtnCompNextPage_Click(object sender, RoutedEventArgs e)
        {
            if (CompPage.PageNumber < CompPage.PageCount)
            {
                CompPage.PageNumber += 1;
                bool blLoad = await LoadCompItemList();
                if (blLoad && CompItemList.Count > 0)
                {
                    dgComp.ScrollIntoView(CompItemList[0]);
                }
            }
        }

        private void BtnCompDetailFirstPage_Click(object sender, RoutedEventArgs e)
        {
            ucCompGird.FirstPage();
        }

        private void BtnCompDetailPrePage_Click(object sender, RoutedEventArgs e)
        {
            ucCompGird.PrePage();
        }

        private void BtnCompDetailNextPage_Click(object sender, RoutedEventArgs e)
        {
            ucCompGird.NextPage();
        }

        private void BtnCompDetailLastPage_Click(object sender, RoutedEventArgs e)
        {
            ucCompGird.LastPage();
        }

        private void BtnCompDetailSpeciPage_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                int pageNumber = int.Parse(txtCompDetailPageNumber.Text.ToString());
                ucCompGird.SpeciPage(pageNumber);
            }
            catch
            {

            }
        }

        //-----------------------------------------------------------------------

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

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

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

    public enum CompFindType
    {
        ALL = 1,
        NERROR_ORIGHT = 2,       /* 旧对新错 */
        NRIGHT_OERROR = 3,       /* 新对旧错 */
        NRIGHT_ORIGHT = 4,       /* 新旧均对 */
        NERROR_OERROR = 5       /* 新旧均错 */
    }

    //////////////////////////////////////////////////////////////////////////
}
