using ComPDFKit.PDFAnnotation;
using ComPDFKit.PDFPage;
using ComPDFKitViewer;
using ComPDFKitViewer.AnnotEvent;
using ImTools;
using PDF_Master.DataConvert;
using PDF_Master.EventAggregators;
using PDF_Master.Helper;
using PDF_Master.Model.BOTA;
using PDF_Master.ViewModels;
using PDF_Master.ViewModels.BOTA;
using Prism.Events;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices.Expando;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Annotations;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
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 Dropbox.Api.Paper.ListPaperDocsSortBy;
using static Dropbox.Api.TeamLog.PaperDownloadFormat;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
using ListBox = System.Windows.Controls.ListBox;
using MenuItem = System.Windows.Controls.MenuItem;
using UserControl = System.Windows.Controls.UserControl;

namespace PDF_Master.Views.BOTA
{
    /// <summary>
    /// AnnotationContent.xaml 的交互逻辑
    /// </summary>
    public partial class AnnotationContent : UserControl
    {
        private AnnotationContentViewModel viewModel;

        private string unicode;

        public AnnotationContent(IEventAggregator eventAggregator)
        {
            InitializeComponent();
            unicode = App.mainWindowViewModel.SelectedItem.Unicode;
            viewModel = this.DataContext as AnnotationContentViewModel;
            if (AnnotationList.Items.Count < 0)
            {
                MenuExpandAll.IsEnabled = false;
            }

            eventAggregator.GetEvent<CleanSelectAllEvent>().Subscribe(CleanSelectAll, e => e.Unicode == unicode);
            eventAggregator.GetEvent<RefreshAnnotationEvent>().Subscribe(ExpandGroupHeader, e => e.Unicode == unicode);
        }

        private async void ExpandGroupHeader(RefreshAnnotationArgs obj)
        {
            if (obj.IsAll)
            {
                try
                {
                    foreach (var item in AnnotationList.Items)
                    {
                        var groups = AnnotationList.Items.Groups;
                        for (int i = 0; i < groups.Count; i++)
                        {
                            var group = groups[i] as CollectionViewGroup;
                            if (group.Items.Contains(item))
                            {
                                await Task.Delay(2);
                                var scroller = GetScrollHost(AnnotationList);
                                var stackpanel = CommonHelper.FindVisualChild<StackPanel>(scroller);
                                var groupItem = VisualTreeHelper.GetChild(stackpanel, i) as GroupItem;
                                var g = CommonHelper.FindVisualChild<Expander>(groupItem);
                                if (g != null)
                                {
                                    g.IsExpanded = true;
                                }
                                else
                                {
                                    await Task.Delay(5);
                                    g = CommonHelper.FindVisualChild<Expander>(groupItem);
                                    if (g != null)
                                    {
                                        g.IsExpanded = true;
                                    }
                                }
                            }
                        }
                    }
                }
                catch { }
            }
            else
            {
                if (obj.annotHandlerArgs != null)
                {
                    try
                    {
                        var groups = AnnotationList.Items.Groups;
                        if (groups != null && groups.Count > 0)
                        {
                            for (int i = 0; i < groups.Count; i++)
                            {
                                var l = groups[i] as CollectionViewGroup;
                                if (l.Items.Contains(obj.annotHandlerArgs))
                                {
                                    await Task.Delay(5);
                                    var scroller = GetScrollHost(AnnotationList);
                                    var stackpanel = CommonHelper.FindVisualChild<StackPanel>(scroller);
                                    var groupItem = VisualTreeHelper.GetChild(stackpanel, i) as GroupItem;
                                    var g = CommonHelper.FindVisualChild<Expander>(groupItem);
                                    if (g != null)
                                    {
                                        g.IsExpanded = true;
                                    }
                                    else
                                    {
                                        await Task.Delay(5);
                                        g = CommonHelper.FindVisualChild<Expander>(groupItem);
                                        if (g != null)
                                        {
                                            g.IsExpanded = true;
                                        }
                                    }
                                }
                                else
                                {
                                }
                            }
                        }

                        if (obj.IsSelect && obj.annotHandlerArgs != null)
                        {
                            if (viewModel.ViewContentViewModel.IsMultiSelected == false)
                            {
                                if (AnnotationList.SelectedItems.IndexOf(obj.annotHandlerArgs) == -1)
                                {
                                    viewModel.IsModified = false;
                                    AnnotationList.SelectedItem = obj.annotHandlerArgs;
                                }
                            }
                        }
                        if (obj.IsDel)
                        {
                            viewModel.IsModified = true;
                        }
                        await Task.Delay(2);//不加延时 会有不滚动的现象
                        AnnotationList.ScrollIntoView(obj.annotHandlerArgs);
                    }
                    catch { }
                }
            }
        }

        private void CleanSelectAll(CleanSelectAllArgs obj)
        {
            AnnotationList.SelectedIndex = -1;
        }

        private void ListBoxItem_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ClickCount == 1)
            {
                //if (Mouse.LeftButton == e.ButtonState)
                //{
                //    viewModel.ListBoxItemPreviewMouseLeftButtonDown.Execute(sender);
                //}
                if (Mouse.RightButton == e.ButtonState)
                {
                    var pos = e.GetPosition(AnnotationList);

                    var result = VisualTreeHelper.HitTest(AnnotationList, pos);
                    if (result != null)
                    {
                        ListBoxItem myListBoxItem = sender as System.Windows.Controls.ListBoxItem;
                        MenuItem copyText = myListBoxItem.ContextMenu.Items[0] as MenuItem;
                        MenuItem import = myListBoxItem.ContextMenu.Items[1] as MenuItem;
                        MenuItem export = myListBoxItem.ContextMenu.Items[2] as MenuItem;
                        if (AnnotationList.SelectedItems.Count > 1)
                        {
                            import.IsEnabled = false;
                            export.IsEnabled = true;
                            export.Command = viewModel.ExportCommentsCommand;
                            copyText.IsEnabled = false;
                        }
                        else
                        {
                            //直接右键菜单不需要选中Viewer中注释
                            //viewModel.ListBoxItemPreviewMouseLeftButtonDown.Execute(sender);
                            if (myListBoxItem.DataContext is AnnotationHandlerEventArgs annotation)
                            {
                                //文本、高亮、下划线、删除线、便签
                                if (annotation.EventType == AnnotArgsType.AnnotFreeText ||
                                annotation.EventType == AnnotArgsType.AnnotHighlight ||
                                annotation.EventType == AnnotArgsType.AnnotUnderline ||
                                annotation.EventType == AnnotArgsType.AnnotStrikeout ||
                                annotation.EventType == AnnotArgsType.AnnotSticky)
                                {
                                    copyText.IsEnabled = true;
                                }
                                else
                                {
                                    copyText.IsEnabled = false;
                                }
                            }
                            import.IsEnabled = true;
                            import.Command = viewModel.ImportCommentsCommand;
                            export.IsEnabled = true;
                            export.Command = viewModel.ExportCommentsCommand;
                        }
                    }
                    //拦截响应选中事件
                    e.Handled = true;
                }
            }
        }

        private void ListBoxItem_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (Mouse.LeftButton == e.ButtonState)
            {
                viewModel.AddNotesCommand.Execute(sender);
            }
        }

        private async void MenuExpandAll_Click(object sender, RoutedEventArgs e)
        {
            SetAllExpander(true);
            await Task.Delay(1);
            for (int i = 0; i < AnnotationList.Items.Count; i++)
            {
                ListBoxItem item = AnnotationList.ItemContainerGenerator.ContainerFromIndex(i) as ListBoxItem;

                if (item != null)
                {
                    ToggleButton button = GetExpandButton(item);
                    if (button != null && button.Visibility == Visibility.Visible)
                    {
                        button.IsChecked = true;
                    }
                }
            }
        }

        private void MenuCollapseAll_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < AnnotationList.Items.Count; i++)
            {
                ListBoxItem item = AnnotationList.ItemContainerGenerator.ContainerFromIndex(i) as ListBoxItem;
                ToggleButton button = GetExpandButton(item);
                if (button != null && button.Visibility == Visibility.Visible)
                {
                    button.IsChecked = false;
                }
            }
            SetAllExpander(false);
        }

        private void SetAllExpander(bool isexpand)
        {
            AnnotationList.Dispatcher.Invoke(() =>
              {
                  //开启虚拟化之后 全部展开和折叠会有问题
                  var scroller = GetScrollHost(AnnotationList);
                  var stackpanel = CommonHelper.FindVisualChild<StackPanel>(scroller);
                  int count = VisualTreeHelper.GetChildrenCount(stackpanel);
                  for (int i = 0; i < count; i++)
                  {
                      var item = VisualTreeHelper.GetChild(stackpanel, i) as GroupItem;
                      var g = CommonHelper.FindVisualChild<Expander>(item);
                      if (g != null)
                          g.IsExpanded = isexpand;
                  }
              });
        }

        private ScrollViewer GetScrollHost(ListBox listBox)
        {
            if (VisualTreeHelper.GetChildrenCount(listBox) > 0)
            {
                int s = VisualTreeHelper.GetChildrenCount(listBox);

                Border border = VisualTreeHelper.GetChild(listBox, 0) as Border;
                if (border != null)
                {
                    return VisualTreeHelper.GetChild(border, 0) as ScrollViewer;
                }
            }
            return null;
        }

        private ToggleButton GetExpandButton(ListBoxItem item)
        {
            if (item == null) return null;
            Border border = VisualTreeHelper.GetChild(item, 0) as Border;
            var btn = CommonHelper.FindVisualChild<ToggleButton>(border);
            return btn;
        }

        private void MenuTimeRightSort_Click(object sender, RoutedEventArgs e)
        {
            ICollectionView v = CollectionViewSource.GetDefaultView(AnnotationList.ItemsSource);
            CreateTimeToDate createTimeToDate = new CreateTimeToDate();
            v.GroupDescriptions.Clear();
            v.GroupDescriptions.Add(new PropertyGroupDescription(nameof(AnnotHandlerEventArgs.CreateTime), createTimeToDate));

            v.SortDescriptions.Clear();
            v.SortDescriptions.Add(new SortDescription(nameof(AnnotHandlerEventArgs.CreateTime), ListSortDirection.Ascending));
            v.SortDescriptions.Add(new SortDescription(nameof(AnnotHandlerEventArgs.AnnotIndex), ListSortDirection.Ascending));
        }

        private void MenuTimeBackSort_Click(object sender, RoutedEventArgs e)
        {
            ICollectionView v = CollectionViewSource.GetDefaultView(AnnotationList.ItemsSource);
            CreateTimeToDate createTimeToDate = new CreateTimeToDate();
            v.GroupDescriptions.Clear();
            v.GroupDescriptions.Add(new PropertyGroupDescription(nameof(AnnotHandlerEventArgs.CreateTime), createTimeToDate));
            v.SortDescriptions.Clear();
            v.SortDescriptions.Add(new SortDescription(nameof(AnnotHandlerEventArgs.CreateTime), ListSortDirection.Descending));
            v.SortDescriptions.Add(new SortDescription(nameof(AnnotHandlerEventArgs.AnnotIndex), ListSortDirection.Descending));
        }

        private void MenuPageSort_Click(object sender, RoutedEventArgs e)
        {
            ICollectionView v = CollectionViewSource.GetDefaultView(AnnotationList.ItemsSource);
            v.GroupDescriptions.Clear();
            v.GroupDescriptions.Add(new PropertyGroupDescription(nameof(AnnotHandlerEventArgs.PageIndex)));

            v.SortDescriptions.Clear();
            v.SortDescriptions.Add(new SortDescription(nameof(AnnotHandlerEventArgs.PageIndex), ListSortDirection.Ascending));
            v.SortDescriptions.Add(new SortDescription(nameof(AnnotHandlerEventArgs.AnnotIndex), ListSortDirection.Ascending));
        }

        private void MenuItemCopyText_Click(object sender, RoutedEventArgs e)
        {
            //没有权限解密时,拦截复制文本操作
            if (!viewModel.ViewContentViewModel.CheckPermissionBeforeOption())
            {
                return;
            }
            if (AnnotationList.SelectedItems.Count == 1)
            {
                if (AnnotationList.SelectedItem is AnnotationHandlerEventArgs annotation)
                {
                    //文本、高亮、下划线、删除线、便签
                    if (annotation.EventType == AnnotArgsType.AnnotFreeText ||
                    annotation.EventType == AnnotArgsType.AnnotHighlight ||
                    annotation.EventType == AnnotArgsType.AnnotUnderline ||
                    annotation.EventType == AnnotArgsType.AnnotStrikeout ||
                    annotation.EventType == AnnotArgsType.AnnotSticky)
                    {
                        StringBuilder Copystr = new StringBuilder();
                        if (annotation.MarkupContent != null)
                        {
                            Copystr.Append(annotation.MarkupContent);
                            Copystr.Append(Environment.NewLine);
                        }
                        if (annotation.Content != null)
                        {
                            Copystr.Append(annotation.Content);
                        }

                        System.Windows.Clipboard.SetText(Copystr.ToString());
                        //CustomControl.MessageBoxEx.Show("数据复制成功");
                    }
                }
            }
        }

        private void MenuItemDelete_Click(object sender, RoutedEventArgs e)
        {
            List<int> pagelist = new List<int>();
            if (AnnotationList.SelectedItems.Count > 1)
            {
                //for (int i = 0; i < AnnotationList.SelectedItems.Count; i++)
                //{
                //    AnnotationHandlerEventArgs annotation = AnnotationList.SelectedItems[i] as AnnotationHandlerEventArgs;
                //    pagelist.Add(AnnotationList.Items.IndexOf(annotation));
                //}
                //pagelist.Sort();
                //for (int i = 0; i < pagelist.Count; i++)
                //{
                //    AnnotationHandlerEventArgs annotation = AnnotationList.Items[pagelist[pagelist.Count - i - 1]] as AnnotationHandlerEventArgs;
                //    if (annotation == null)
                //    {
                //        continue;
                //    }

                //    viewModel.DeleteCommand.Execute(annotation);
                //}

                Dictionary<int, List<int>> selectedItemDics = new Dictionary<int, List<int>>();
                List<AnnotationHandlerEventArgs> eventArgs = new List<AnnotationHandlerEventArgs>();
                foreach (var item in AnnotationList.SelectedItems)
                {
                    if (item is AnnotationHandlerEventArgs annotation)
                    {
                        if (eventArgs.Contains(annotation) == false)
                        {
                            eventArgs.Add(annotation);
                        }
                    }
                }
                var result = eventArgs.GroupBy(d => d.PageIndex);
                foreach (var item in result)
                {
                    if (selectedItemDics.ContainsKey(item.Key) == false)
                    {
                        var ai = item.Select(w => w.AnnotIndex).ToList();
                        selectedItemDics.Add(item.Key, ai);
                    }
                }
                viewModel.DeleteCommand.Execute(selectedItemDics);
            }
            else
            {
                AnnotationHandlerEventArgs annotation = (AnnotationHandlerEventArgs)(sender as MenuItem).DataContext;
                if (annotation == null)
                {
                    return;
                }

                viewModel.DeleteCommand.Execute(annotation);
            }
        }

        private void BtnMore_Initialized(object sender, EventArgs e)
        {
            BtnMore.ContextMenu = null;
        }

        private void BtnMore_Click(object sender, RoutedEventArgs e)
        {
            MenuMore.PlacementTarget = BtnMore;
            MenuMore.IsOpen = true;
        }

        private void AnnotationList_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (AnnotationList.SelectedItems.Count > 1)
            {
                viewModel.ListBoxItemPreviewMouseLeftButtonDown.Execute(AnnotationList.SelectedItems);
            }
            else if (AnnotationList.SelectedItems.Count == 1)
            {
                viewModel.ListBoxItemPreviewMouseLeftButtonDown.Execute(AnnotationList.SelectedItem);
            }
        }

        private void AnnotationList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //var a = AnnotationList.SelectedItems.Count;
            var a1 = (sender as ListBox).SelectedItems.Count;
            //var a2 = (e.OriginalSource as ListBox).SelectedItems.Count;
            //var a3 = (e.Source as ListBox).SelectedItems.Count;
            //Trace.WriteLine("a:" + a + "   a1:" + a1 + "  a2:" + a2 + "  a3:" + a3);
            //AnnotationList.ScrollIntoView(AnnotationList.Items[0]);
            if (a1 == 1)
            {
                //if(viewModel.ViewContentViewModel.IsPropertyOpen==false)
                if (viewModel.IsModified)
                {
                    viewModel.ListBoxItemPreviewMouseLeftButtonDown.Execute((sender as ListBox).SelectedItems[0]);
                }
                viewModel.IsModified = true;
            }
            else if (a1 > 1)
            {
                #region 阅读视图 多选

                Dictionary<int, List<int>> selectedItemDics = new Dictionary<int, List<int>>();
                List<AnnotationHandlerEventArgs> eventArgs = new List<AnnotationHandlerEventArgs>();
                foreach (var item in (sender as ListBox).SelectedItems)
                {
                    if (item is AnnotationHandlerEventArgs annotation)
                    {
                        if (eventArgs.Contains(annotation) == false)
                        {
                            eventArgs.Add(annotation);
                        }
                    }
                }
                var result = eventArgs.GroupBy(d => d.PageIndex);
                foreach (var item in result)
                {
                    if (selectedItemDics.ContainsKey(item.Key) == false)
                    {
                        var ai = item.Select(w => w.AnnotIndex).ToList();
                        selectedItemDics.Add(item.Key, ai);
                    }
                }

                #endregion 阅读视图 多选

                viewModel.ListBoxItemPreviewMouseLeftButtonDown.Execute(selectedItemDics);
            }
        }

        private void AnnotationList_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (AnnotationList.SelectedItems == null)
            {
                return;
            }
            if (e.Key == Key.Escape)
            {
                AnnotationList.SelectedItems.Clear();
            }
        }

        private void Grid_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var pos = e.GetPosition(this);
            var result = VisualTreeHelper.HitTest(this, pos);
            if (result != null)
            {
                //点击按钮和listboxitem时 不清空多选 其余区域取消多选
                var item = CommonHelper.FindVisualParent<ListBoxItem>(result.VisualHit);
                if (item != null)
                {
                    return;
                }
                var btn = CommonHelper.FindVisualParent<System.Windows.Controls.Button>(result.VisualHit);
                if (btn != null)
                {
                    return;
                }
            }
        }

        private void ListBox_MouseDown(object sender, MouseButtonEventArgs e)
        {
            AnnotationList.SelectedIndex = -1;
        }

        private void ContextMenu_Loaded(object sender, RoutedEventArgs e)
        {
            var menu = sender as System.Windows.Controls.ContextMenu;
            if (menu != null)
            {
                (menu.Items[0] as MenuItem).Header = viewModel.T_CopyText;
                (menu.Items[1] as MenuItem).Header = viewModel.T_Import;
                (menu.Items[2] as MenuItem).Header = viewModel.T_Export;
                (menu.Items[3] as MenuItem).Header = viewModel.T_Delete;
                if (AnnotationList.SelectedItems.Count > 1)
                {
                    (menu.Items[3] as MenuItem).Header = viewModel.T_DeleteAll;
                }
            }
        }
    }
}