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.IO;
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.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace MeterVision.Patch
{
    /// <summary>
    /// UCCompGrid.xaml 的交互逻辑
    /// </summary>
    public partial class UCCompGrid : UserControl, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

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

        public ObservableCollection<CompDetailItem> CompDetailItemList { get; set; }


        private CompDetailItem _selectedCompDetailItem;
        public CompDetailItem SelectedCompDetailItem
        {
            get => _selectedCompDetailItem;
            set
            {
                if(_selectedCompDetailItem != value)
                {
                    _selectedCompDetailItem = value;
                    OnPropertyChanged(nameof(SelectedCompDetailItem));
                }
            }
        }

        private CompItem _curCompItem;
        public CompItem CurCompItem
        {
            get => _curCompItem;
            private set
            {
                if(_curCompItem != value)
                {
                    _curCompItem = value;
                }
            }
        }

        private CompFindType _selectedCompFindType;
        public CompFindType SelectedCompFindTpe
        {
            get => _selectedCompFindType;
            private set
            {
                if(_selectedCompFindType != value)
                {
                    _selectedCompFindType = value;
                }
            }
        }

        //改变CompItem或FindType
        public void ChangeCompItemOrFindType(CompItem curCompItem,CompFindType compFindType)
        {
            bool blCompItemChanged = false;
            bool blCompFindTypeChanged = false;

            //判断数据是否发生变化
            if(curCompItem != _curCompItem)
            {
                CurCompItem = curCompItem;
                blCompItemChanged = true;
            }

            if(compFindType != _selectedCompFindType)
            {
                SelectedCompFindTpe = compFindType;
                blCompFindTypeChanged = true;
            }

            if(blCompItemChanged || blCompFindTypeChanged)
            {
                CompDetailPage.InitDefaulValue();
                LoadCompDetailItemList(true);
            }
        }

        public CfginiItem mConfigItem { get; set; }

        public PageModel CompDetailPage { get; set; }

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

        public UCCompGrid()
        {
            InitializeComponent();
            CompDetailItemList = new ObservableCollection<CompDetailItem>();
            dgCompDetail.ItemsSource = CompDetailItemList;
            mConfigItem = CfginiItem.GetConfigItem();

            CompDetailPage = new PageModel
            {
                PageSize = mConfigItem.PatchPageSize,
                PageNumber = 1
            };

            mConfigItem.OnPatchPageSizeChanged += MConfigItem_OnPatchPageSizeChanged;
            this.DataContext = this;
        }

        private void MConfigItem_OnPatchPageSizeChanged(int pageSize)
        {
            CompDetailPage.InitDefaulValue(pageSize);
            LoadCompDetailItemList(true);
        }

        private async void LoadCompDetailItemList(bool scrollTop)
        {
            CompDetailItemList.Clear();
            if (CurCompItem != null)
            {
                try
                {
                    var result = await Task.Run(() =>
                    {
                        //数据库查询
                        CompFindModel findModel = new CompFindModel(CompDetailPage.PageNumber, CompDetailPage.PageSize,
                            CurCompItem.CompId, SelectedCompFindTpe);

                        return DBComp.GetPagedCompDetails(findModel);
                    });

                    //更新分页信息
                    TotalRecords = result.Item1;
                    CompDetailPage.PageCount = result.Item2;
                    List<VCompDetail> compDetails = result.Item3;

                    //更新数据需要在主线中进行
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        int index = 0;
                        foreach (VCompDetail compDetail in compDetails)
                        {
                            index++;
                            CompDetailItem item = new CompDetailItem(compDetail);
                            item.Index = index + ((CompDetailPage.PageNumber - 1) * CompDetailPage.PageSize);
                            CompDetailItemList.Add(item);
                        }//foreach

                        SelectedCompDetailItem = null;
                        if (CompDetailItemList.Count > 0 && scrollTop)
                        {
                            dgCompDetail.ScrollIntoView(dgCompDetail.Items[0]);
                        }
                    });
                }
                catch (Exception ex)
                {
                    MessageBox.Show(Application.Current.MainWindow,
                        $"加载数据时发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }

            SelectedCompDetailItem = null;
        }

        private void MiViewLog_Click(object sender, RoutedEventArgs e)
        {
            if (SelectedCompDetailItem != null)
            {
                ShowLogViewer(SelectedCompDetailItem);
            }
        }

        private void Image_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {


        }


        private void SrcImage_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var image = sender as Image;
            if (image == null) return;

            var dataContext = image.DataContext as CompDetailItem;
            if (dataContext == null) return;

            if (!File.Exists(dataContext.Detail1.SrcImage)) return;

            var dialog = new imgWindow(dataContext.Detail1.SrcImage)
            {
                Owner = Application.Current.MainWindow
            };
            dialog.Show();

        }


        private void DstImage1_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var image = sender as Image;
            if (image == null) return;

            var dataContext = image.DataContext as CompDetailItem;
            if (dataContext == null) return;

            if (!File.Exists(dataContext.Detail1.DstImage)) return;

            var dialog = new imgWindow(dataContext.Detail1.DstImage)
            {
                Owner = Application.Current.MainWindow
            };
            dialog.Show();
        }

        private void DstImage2_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var image = sender as Image;
            if (image == null) return;

            var dataContext = image.DataContext as CompDetailItem;
            if (dataContext == null) return;

            if (!File.Exists(dataContext.Detail2.DstImage)) return;

            var dialog = new imgWindow(dataContext.Detail2.DstImage)
            {
                Owner = Application.Current.MainWindow
            };
            dialog.Show();
        }

        public void NextPage()
        {
            if (CompDetailPage.PageNumber < CompDetailPage.PageCount)
            {
                CompDetailPage.PageNumber += 1;
                LoadCompDetailItemList(true);
            }
        }
        public void PrePage()
        {
            if (CompDetailPage.PageNumber > 1)
            {
                CompDetailPage.PageNumber -= 1;
                LoadCompDetailItemList(true);
            }
        }

        public void FirstPage()
        {
            if (CompDetailPage.PageNumber > 1)
            {
                CompDetailPage.PageNumber = 1;
                LoadCompDetailItemList(true);
            }
        }

        public void LastPage()
        {
            if (CompDetailPage.PageNumber < CompDetailPage.PageCount)
            {
                CompDetailPage.PageNumber = CompDetailPage.PageCount;
                LoadCompDetailItemList(true);
            }
        }

        public void SpeciPage(int pageNumber)
        {
            if (pageNumber != CompDetailPage.PageNumber &&
                pageNumber > 0 && pageNumber <= CompDetailPage.PageCount)
            {
                CompDetailPage.PageNumber = pageNumber;
                LoadCompDetailItemList(true);
            }
        }

        public static T FindAncestor<T>(DependencyObject dependencyObject) where T : DependencyObject
        {
            var parent = VisualTreeHelper.GetParent(dependencyObject);

            if (parent == null) return null;

            var parentT = parent as T;
            return parentT ?? FindAncestor<T>(parent);
        }

        private void BtnLogViewer_Click(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            if (button == null) return;

            DataGridRow row = FindAncestor<DataGridRow>(button);
            if (row == null) return;

            //获取当前行绑定的数据项
            CompDetailItem selectedItem = row.Item as CompDetailItem;

            ShowLogViewer(selectedItem);
        }

        private void ShowLogViewer(CompDetailItem selectedItem)
        {
            //if (selectedItem.LogPath != null && File.Exists(selectedItem.LogPath))
            {
                //LogViewerWindow dialog = new LogViewerWindow(selectedItem.DstImage, selectedItem.LogPath)
                var dialog = new CompLogViewer(selectedItem)
                {
                    Owner = Application.Current.MainWindow,
                    WindowStartupLocation = WindowStartupLocation.CenterOwner
                };
                //dialog.ShowDialog();
                dialog.Show();
            }
        }
        //-------------------------------------------------------
    }
}
