using ComPDFKitViewer.AnnotEvent;
using PDF_Office.DataConvert;
using PDF_Office.Helper;
using PDF_Office.Model.BOTA;
using PDF_Office.ViewModels.BOTA;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
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 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_Office.Views.BOTA
{
    /// <summary>
    /// AnnotationContent.xaml 的交互逻辑
    /// </summary>
    public partial class AnnotationContent : UserControl
    {
        private AnnotationContentViewModel viewModel;

        public AnnotationContent()
        {
            InitializeComponent();
            viewModel = this.DataContext as AnnotationContentViewModel;
            if (AnnotationList.Items.Count < 0)
            {
                MenuExpandAll.IsEnabled = false;
            }
        }

        private void ListBoxItem_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ClickCount == 1)
            {
                if (Mouse.LeftButton == e.ButtonState)
                {
                    viewModel.ListBoxItemPreviewMouseLeftButtonDown.Execute(sender);
                }
                else 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 export = myListBoxItem.ContextMenu.Items[1] as MenuItem;
                        if (AnnotationList.SelectedItems.Count > 1)
                        {
                            export.IsEnabled = false;
                            copyText.IsEnabled = false;
                        }
                        else
                        {
                            viewModel.ListBoxItemPreviewMouseLeftButtonDown.Execute(sender);
                            if (myListBoxItem.DataContext is AnnotationHandlerEventArgs annotation)
                            {
                                if (annotation.EventType == AnnotArgsType.AnnotFreeText)
                                {
                                    copyText.IsEnabled = true;
                                }
                                else
                                {
                                    copyText.IsEnabled = false;
                                }
                            }
                            export.IsEnabled = true;
                            export.Command = viewModel.ExportCommentsCommand;
                        }
                    }
                }
            }
            //else if (e.ClickCount == 2)
            //{
            //    viewModel.DoubleClikCommand.Execute(sender);
            //}
        }

        private void AnnotationList_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            //AnnotationList.ContextMenu.IsEnabled = false;
        }

        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;
                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 (AnnotationList.SelectedItems.Count == 1)
            {
                if (AnnotationList.SelectedItem is AnnotationHandlerEventArgs annotation)
                {
                    if (annotation.EventType == AnnotArgsType.AnnotFreeText)
                    {
                        StringBuilder Copystr = new StringBuilder();
                        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>();
            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);
            }
        }

        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;
        }
    }
}