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

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

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

        public BulkObservableCollection<VPatchStation> StationItemList { get; set; }

        public event Action<VPatchStation> OnItemChanged;

        private VPatchStation _selectedStationItem;

        public VPatchStation SelectedStationItem
        {
            get => _selectedStationItem;
            set
            {
                if(_selectedStationItem != value)
                {
                    _selectedStationItem = value;
                    OnPropertyChanged(nameof(SelectedStationItem));
                    OnItemChanged?.Invoke(value);
                }
            }
        }


        //要查找的站点ID
        private string _findStationId;
        public string FindStationId
        {
            get => _findStationId;
            private set
            {
                if (_findStationId != value)
                {
                    _findStationId = value;
                }
            }
        }

        private string _patchId;
        public string PatchId
        {
            get => _patchId;
            private set
            {
                if (_patchId != value)
                {
                    _patchId = value;
                }
            }
        }

        public void ChangeFind(string stationId, string patchId)
        {
            //bool blChangeFindStationId = false;
            //bool blChangePatchId = false;
            if (!_semaphore.Wait(0)) return; // 如果信号量已被占用，直接返回

            try
            {
                if (stationId != _findStationId)
                {
                    FindStationId = stationId;
                    //blChangeFindStationId = true;
                }

                if (patchId != _patchId)
                {
                    PatchId = patchId;
                    // blChangePatchId = true;
                }

                //if (blChangeFindStationId || blChangePatchId)
                {
                    StationPage.InitDefaulValue();
                    LoadStationItemList(true);
                }
            }
            catch { }
            finally
            {
                _semaphore.Release();
            }
        }

        public CfginiItem mConfigItem { get; set; }

        public PageModel StationPage { get; set; }

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



        public UCVpsGrid()
        {
            InitializeComponent();
            StationItemList = new BulkObservableCollection<VPatchStation>();
            dgStation.ItemsSource = StationItemList;

            mConfigItem = CfginiItem.GetConfigItem();

            StationPage = new PageModel
            {
                PageSize = mConfigItem.PageSize2, //mConfigItem.PatchPageSize,
                PageNumber = 1
            };

            //mConfigItem.OnPatchPageSizeChanged += MConfigItem_OnPatchPageSizeChanged;
            mConfigItem.OnPageSize2Changed += MConfigItem_OnPageSize2Changed;

            this.DataContext = this;
        }

        private void MConfigItem_OnPageSize2Changed(int pageSize2)
        {
            if (!_semaphore.Wait(0)) return; // 如果信号量已被占用，直接返回
            try
            {
                StationPage.InitDefaulValue(pageSize2);
                LoadStationItemList(true);
            }
            catch { }
            finally
            {
                _semaphore.Release();
            }
        }

        //private void MConfigItem_OnPatchPageSizeChanged(int pageSize)
        //{
        //    StationPage.InitDefaulValue(pageSize);
        //    LoadStationItemList(true);
        //}

        private async void LoadStationItemList(bool scrollTop)
        {
            StationItemList.Clear();

            if (FindStationId == null)
            {
                return;
            }

            try
            {
                var result = await Task.Run(() =>
                {
                    return DBPatch.GetPagedPatchStations(StationPage.PageNumber,StationPage.PageSize,FindStationId,PatchId);
                });

                //更新分页信息
                TotalRecords = result.Item1;
                StationPage.PageCount = result.Item2;
                List<VPatchStation> stationList = result.Item3;

                //在主线中更新数据
                //await Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                //{
                //int index = 0;
                //foreach (VPatchStation station in stationList)
                //{
                //    index++;
                //    station.Index = index + ((StationPage.PageNumber - 1) * StationPage.PageSize);
                //    StationItemList.Add(station);
                //}

                stationList = stationList.Select((station, i) =>
                {
                    station.Index = i + 1 + ((StationPage.PageNumber - 1) * StationPage.PageSize); // 计算索引
                    return station;
                }).ToList();
                StationItemList.AddRange(stationList);

                //SelectedStationItem = null;
                if (StationItemList.Count > 0 && scrollTop)
                {
                    //dgStation.ScrollIntoView(StationItemList[0]);                
                    await Dispatcher.BeginInvoke(new Action(() =>
                    {
                        var scrollViewer = GetDgStationScrollViewer(dgStation);
                        scrollViewer?.ScrollToTop();
                        //dgStation.ScrollIntoView(dgStation.Items[0]);
                    }));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(Application.Current.MainWindow,
                    $"F加载数据是发生错误：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }

            //if(StationItemList.Count > 0)
            //{
            //    SelectedStationItem = StationItemList[0];
            //}
            //else
            //{
            //    SelectedStationItem = null;
            //}            
        }


        public void NextPage()
        {
            if (!_semaphore.Wait(0)) return; // 如果信号量已被占用，直接返回
            try
            {
                if (StationPage.PageNumber < StationPage.PageCount)
                {
                    StationPage.PageNumber += 1;
                    LoadStationItemList(true);
                }
            }
            catch { }
            finally
            {
                _semaphore.Release();
            }
        }

        public void PrePage()
        {
            if (!_semaphore.Wait(0)) return; // 如果信号量已被占用，直接返回
            try
            {
                if (StationPage.PageNumber > 1)
                {
                    StationPage.PageNumber -= 1;
                    LoadStationItemList(true);
                }
            }
            catch { }
            finally
            {
                _semaphore.Release();
            }
        }

        public void FirstPage()
        {
            if (!_semaphore.Wait(0)) return; // 如果信号量已被占用，直接返回

            try
            {
                if (StationPage.PageNumber > 1)
                {
                    StationPage.PageNumber = 1;
                    LoadStationItemList(true);
                }
            }
            catch { }
            finally
            {
                _semaphore.Release();
            }
        }

        public void LastPage()
        {
            if (!_semaphore.Wait(0)) return; // 如果信号量已被占用，直接返回
            try
            {
                if (StationPage.PageNumber < StationPage.PageCount)
                {
                    StationPage.PageNumber = StationPage.PageCount;
                    LoadStationItemList(true);
                }
            }
            catch { }
            finally
            {
                _semaphore.Release();
            }
        }

        public void SpeciPage(int pageNumber)
        {
            if (!_semaphore.Wait(0)) return; // 如果信号量已被占用，直接返回

            try
            {
                if (pageNumber != StationPage.PageNumber &&
                    pageNumber > 0 && pageNumber <= StationPage.PageCount)
                {
                    StationPage.PageNumber = pageNumber;
                    LoadStationItemList(true);
                }
            }
            catch { }
            finally
            {
                _semaphore.Release();
            }
        }

        public async void RefreshItems()
        {
            try
            { 
                var result = await Task.Run(() =>
                {
                    return DBPatch.GetPagedPatchStations(StationPage.PageNumber, StationPage.PageSize, FindStationId, PatchId);
                });

                //更新分页信息
                //TotalRecords = result.Item1;
                //StationPage.PageCount = result.Item2;
                List<VPatchStation> stationList = result.Item3;

                foreach(var stationItem in StationItemList)
                {
                    int index = stationItem.Index;
                    var findItem = stationList.Find((a) => a.StationId == stationItem.StationId);
                    if(findItem!= null)
                    {
                        ObjectHelper.CopyMatchingFields(findItem, stationItem);
                        stationItem.Index = index;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(Application.Current.MainWindow,
                    $"a加载数据是发生错误：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private ScrollViewer _dgStaionScrollViewer;

        private ScrollViewer GetDgStationScrollViewer(DependencyObject obj)
        {
            if (_dgStaionScrollViewer != null)
            {
                return _dgStaionScrollViewer;
            }

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

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

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