using ComPDFKit.PDFDocument;
using Microsoft.Office.Interop.Word;
using PDF_Master.EventAggregators;
using PDF_Master.Helper;
using PDF_Master.ViewModels.BOTA;
using Prism.Events;
using System;
using System.Collections.Generic;
using System.Diagnostics;
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.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using static Dropbox.Api.Sharing.ListFileMembersIndividualResult;

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

        /// <summary>
        /// 上一个ListBoxItem,为选中状态做准备
        /// </summary>
        public ListBoxItem histotyListBoxItem = null;

        private bool isAdd = false;

        private string unicode = "";

        private bool isCleanSelectAll = false;

        public BookmarkContent(IEventAggregator eventAggregator)
        {
            InitializeComponent();
            viewModel = this.DataContext as BookmarkContentViewModel;
            unicode = App.mainWindowViewModel.SelectedItem.Unicode;
            //Windows:BOTA列表,移除点击阅读页取消选中逻辑
            //eventAggregator.GetEvent<CleanSelectAllEvent>().Subscribe(CleanSelectAll, e => e.Unicode == unicode);
        }

        private void CleanSelectAll(CleanSelectAllArgs obj)
        {
            isCleanSelectAll = true;
            BookMarkListView.SelectedIndex = -1;
            foreach (var item in BookMarkListView.Items)
            {
                ListBoxItem listItem = (ListBoxItem)(BookMarkListView.ItemContainerGenerator.ContainerFromItem(item));
                if (listItem != null)
                {
                    TextBlock textBlock = CommonHelper.FindVisualChild<TextBlock>(listItem);
                    //TextBox text = CommonHelper.FindVisualChild<TextBox>(listItem);
                    if (textBlock.Visibility == Visibility.Collapsed)
                    {
                        textBlock.Visibility = Visibility.Visible;
                    }
                }
            }

            //BookMarkListView.SelectedItems.Clear();
        }

        /// <summary>
        ///ListViewItem,鼠标左键点击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ListViewItem_MouseButtonDown(object sender, MouseButtonEventArgs e)
        {
            object[] objects = new object[] { sender, e };
            TextBlock textBlock = null;
            ListBoxItem listBoxItem = (sender as ListBoxItem);
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                if (e.ClickCount >= 2)
                {
                    histotyListBoxItem = listBoxItem;
                    if (e.OriginalSource is TextBlock)
                    {
                        textBlock = (TextBlock)e.OriginalSource;

                        if (textBlock != null)
                        {
                            TextBox textBox = CommonHelper.FindVisualChild<TextBox>(listBoxItem);

                            SetSelectedStatus(listBoxItem, textBox, textBlock);
                        }
                    }
                }
                else if (e.ClickCount == 1)
                {
                    isRename = false;
                    CleanHistotyListBoxItem(listBoxItem, textBlock);

                    viewModel.ListViewItemMouseDownCommand.Execute(sender);
                }
            }
            else if (e.RightButton == MouseButtonState.Pressed)
            {
                CleanHistotyListBoxItem(listBoxItem, textBlock);
            }
        }

        private void CleanHistotyListBoxItem(ListBoxItem listBoxItem, TextBlock textBlock)
        {
            if (histotyListBoxItem != listBoxItem)
            {
                if (histotyListBoxItem != null)
                {
                    histotyListBoxItem.IsSelected = false;
                    textBlock = CommonHelper.FindVisualChild<TextBlock>(histotyListBoxItem);
                    textBlock.Visibility = Visibility.Visible;
                    textBlock.Focusable = true;
                }
            }
        }

        private bool isSelects = false;

        private void BookMarkListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            MenuItem rename = ContextMenuBook.Items[0] as MenuItem;
            MenuItem editPageIndex = ContextMenuBook.Items[1] as MenuItem;
            MenuItem del = ContextMenuBook.Items[2] as MenuItem;
            var a1 = (sender as ListBox).SelectedItems.Count;
            if (a1 >= 1)
            {
                isSelects = true;
                ContextMenuBook.Visibility = Visibility.Visible;

                if (a1 > 1)
                {
                    rename.IsEnabled = false;
                    editPageIndex.IsEnabled = false;
                }
                if (a1 == 1)
                {
                    isSelects = false;
                    CPDFBookmark bookmark = null;
                    if (BookMarkListView.SelectedItem != null)
                    {
                        bookmark = (CPDFBookmark)BookMarkListView.SelectedItem;
                        if (viewModel.PDFViewer.CurrentIndex == bookmark.PageIndex)
                        {
                            editPageIndex.IsEnabled = false;
                            return;
                        }
                        rename.IsEnabled = true;
                        editPageIndex.IsEnabled = true;
                    }
                }
            }
            else
            {
                ContextMenuBook.Visibility = Visibility.Collapsed;
                isSelects = false;
            }
        }

        /// <summary>
        /// ListViewItem双击时选中状态
        /// </summary>
        /// <param name="listBoxItem"></param>
        /// <param name="textBox"></param>
        /// <param name="textBlock"></param>
        private void SetSelectedStatus(ListBoxItem listBoxItem, TextBox textBox, TextBlock textBlock)
        {
            if (listBoxItem == null || textBox == null || textBlock == null)
            {
                return;
            }
            listBoxItem.IsSelected = true;
            listBoxItem.Focus();
            textBlock.Visibility = Visibility.Collapsed;
            isRename = true;
            textBox.Dispatcher.BeginInvoke(new Action(() =>
                                {
                                    textBox.Focus();
                                    textBox.SelectAll();
                                    //listBoxItem.IsSelected = true;
                                }));
        }

        /// <summary>
        /// ListViewItem失去焦点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ListViewItem_LostFocus(object sender, RoutedEventArgs e)
        {
            ListBoxItem listItem = sender as ListBoxItem;
            if (listItem != null)
            {
                BookMarkListView.ItemContainerGenerator.StatusChanged -= ItemContainerGenerator_StatusChanged;
                viewModel.LostFocusCommand.Execute(listItem);

                TextBlock textBlock = CommonHelper.FindVisualChild<TextBlock>(listItem);
                TextBox text = CommonHelper.FindVisualChild<TextBox>(listItem);

                if (textBlock.Visibility != Visibility.Visible)
                {
                    if (isAdd == false || isRename == false)
                    {
                        listItem.IsSelected = false;
                        if (isRename)
                        {
                            isRename = false;
                            listItem.IsSelected = true;
                        }
                        if (listItem.IsSelected == false)
                        {
                            textBlock.Visibility = Visibility.Visible;
                        }
                    }
                    else
                    {
                        if (isCleanSelectAll == false)
                        {
                            listItem.IsSelected = true;
                            isAdd = false;
                        }
                    }
                }
                else
                {
                    if (isCleanSelectAll == false)
                    {
                        //点击空白
                        //textBlock.Text = text.Text;
                        listItem.IsSelected = true;
                    }
                }
            }
        }

        private bool isRename = false;

        /// <summary>
        /// 右键菜单-重命名
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuItemRename_Click(object sender, RoutedEventArgs e)
        {
            if (sender is MenuItem)
            {
                MenuItem menuItem = (MenuItem)sender;
                CPDFBookmark bookmark = BookMarkListView.SelectedItem as CPDFBookmark;
                if (bookmark != null)
                {
                    BookMarkListView.ItemContainerGenerator.StatusChanged -= ItemContainerGenerator_StatusChanged;
                    isRename = true;
                    ListBoxItem listBoxItem = (ListBoxItem)(BookMarkListView.ItemContainerGenerator.ContainerFromItem(bookmark));
                    histotyListBoxItem = listBoxItem;

                    TextBox textBox = CommonHelper.FindVisualChild<TextBox>(listBoxItem);
                    TextBlock textBlock = CommonHelper.FindVisualChild<TextBlock>(listBoxItem);
                    SetSelectedStatus(listBoxItem, textBox, textBlock);
                }
            }
        }

        /// <summary>
        /// BookMarkListView,鼠标点击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BookMarkListView_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                var pos = e.GetPosition(BookMarkListView);

                var result = VisualTreeHelper.HitTest(BookMarkListView, pos);
                if (result != null)
                {
                    //获取当前鼠标指针下的容器
                    var listBoxItem = CommonHelper.FindVisualParent<ListBoxItem>(result.VisualHit);
                    if (listBoxItem == null)
                    {
                        if (BookMarkListView.SelectedItem != null)
                        {
                            ListBoxItem item = (ListBoxItem)(BookMarkListView.ItemContainerGenerator.ContainerFromItem(BookMarkListView.SelectedItem));
                            item.IsSelected = false;
                            TextBlock box = CommonHelper.FindVisualChild<TextBlock>(item);
                            box.Visibility = Visibility.Visible;
                            BookMarkListView.SelectedItems.Clear();
                        }
                        if (histotyListBoxItem != null)
                        {
                            var pos1 = e.GetPosition(histotyListBoxItem);
                            var result1 = VisualTreeHelper.HitTest(BookMarkListView, pos1);
                            if (result1 == null)
                            {
                                histotyListBoxItem.IsSelected = false;
                                TextBlock textBlock = CommonHelper.FindVisualChild<TextBlock>(histotyListBoxItem);
                                textBlock.Visibility = Visibility.Visible;
                                textBlock.Focusable = true;
                            }
                        }
                    }
                    else
                    {
                        TextBox textBox = CommonHelper.FindVisualChild<TextBox>(listBoxItem);
                        TextBlock textBlock = CommonHelper.FindVisualChild<TextBlock>(listBoxItem);
                        if (textBox.IsFocused == false)
                        {
                            listBoxItem.Focus();
                        }
                    }
                }
                //BookMarkListView.Focus();
            }
        }

        /// <summary>
        /// 右键菜单-删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuItemDeleteCommand_Click(object sender, RoutedEventArgs e)
        {
            List<int> pagelist = new List<int>();
            for (int i = 0; i < BookMarkListView.SelectedItems.Count; i++)
            {
                CPDFBookmark item = BookMarkListView.SelectedItems[i] as CPDFBookmark;
                pagelist.Add(BookMarkListView.Items.IndexOf(item));
            }
            pagelist.Sort();
            for (int i = 0; i < pagelist.Count; i++)
            {
                CPDFBookmark data = BookMarkListView.Items[pagelist[pagelist.Count - i - 1]] as CPDFBookmark;
                if (data != null)
                {
                    viewModel.DeleteCommand.Execute(data);
                }
            }
        }

        public void BtnAddBookmark_Click(object sender, RoutedEventArgs e)
        {
            isAdd = true;
            isRename = false;
            viewModel.AddBookmarkCommand.Execute(BookMarkListView);
            if (viewModel.IsHasBookmark == false)
            {
                BookMarkListView.ScrollIntoView(viewModel.AddCPDFBookmark);
                ListBoxItem myListBoxItem = (ListBoxItem)(BookMarkListView.ItemContainerGenerator.ContainerFromItem(viewModel.AddCPDFBookmark));
                if (myListBoxItem == null)
                {
                    BookMarkListView.ItemContainerGenerator.StatusChanged -= ItemContainerGenerator_StatusChanged;
                    BookMarkListView.ItemContainerGenerator.StatusChanged += ItemContainerGenerator_StatusChanged;
                }
                else
                {
                    TextBox textBox = CommonHelper.FindVisualChild<TextBox>(myListBoxItem);
                    TextBlock textBlock = CommonHelper.FindVisualChild<TextBlock>(myListBoxItem);
                    histotyListBoxItem = myListBoxItem;
                    SetSelectedStatus(myListBoxItem, textBox, textBlock);
                }
            }
        }

        private void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)
        {
            ItemContainerGenerator itemContainer = sender as ItemContainerGenerator;
            if (itemContainer.Status == GeneratorStatus.ContainersGenerated)
            {
                BookMarkListView.ScrollIntoView(viewModel.AddCPDFBookmark);
                ListBoxItem myListBoxItem = (ListBoxItem)(BookMarkListView.ItemContainerGenerator.ContainerFromItem(viewModel.AddCPDFBookmark));
                if (myListBoxItem != null)
                {
                    if (myListBoxItem.RenderSize.Width < 0 && myListBoxItem.RenderSize.Height < 0)
                    {
                        BookMarkListView.UpdateLayout();
                        myListBoxItem.UpdateLayout();
                        BookMarkListView.ScrollIntoView(viewModel.AddCPDFBookmark);
                    }
                    TextBox textBox = CommonHelper.FindVisualChild<TextBox>(myListBoxItem);
                    TextBlock textBlock = CommonHelper.FindVisualChild<TextBlock>(myListBoxItem);
                    SetSelectedStatus(myListBoxItem, textBox, textBlock);
                }
            }
        }

        private void BookMarkListView_KeyDown(object sender, KeyEventArgs e)
        {
            if (BookMarkListView.SelectedItems == null)
            {
                return;
            }
            if (e.Key == Key.Escape)
            {
                //Windows:BOTA列表,移除Esc取消选中逻辑
                //BookMarkListView.SelectedItems.Clear();
            }
            //if (e.Key == Key.Delete)
            //{
            //    if (BookMarkListView.SelectedItems.Count > 0)
            //    {
            //        //全选删除
            //        if (BookMarkListView.SelectedItems.Count == BookMarkListView.Items.Count)
            //        {
            //        }
            //    }
            //}
        }

        private void ContextMenu_Loaded(object sender, RoutedEventArgs e)
        {
            //ContextMenu contextMenu = sender as ContextMenu;
            if (sender is ContextMenu contextMenu)
            {
                Trace.WriteLine($"{BookMarkListView.SelectedItems.Count}");
                MenuItem rename = contextMenu.Items[0] as MenuItem;
                MenuItem editPageIndex = contextMenu.Items[1] as MenuItem;
                MenuItem del = contextMenu.Items[2] as MenuItem;
                rename.IsEnabled = true;
                editPageIndex.IsEnabled = true;
                if (BookMarkListView.SelectedItems.Count > 1)
                {
                    rename.IsEnabled = false;
                    editPageIndex.IsEnabled = false;
                    //isSelects = false;
                }
                else
                {
                    Trace.WriteLine($"{BookMarkListView.SelectedItems.Count}");
                    CPDFBookmark bookmark = null;
                    if (BookMarkListView.SelectedItem != null)
                    {
                        bookmark = (CPDFBookmark)BookMarkListView.SelectedItem;
                        if (viewModel.PDFViewer.CurrentIndex == bookmark.PageIndex)
                        {
                            editPageIndex.IsEnabled = false;
                            return;
                        }
                        rename.IsEnabled = true;
                        editPageIndex.IsEnabled = true;
                    }
                }
            }
        }

        private void MenuChangeItem_Click(object sender, RoutedEventArgs e)
        {
            if (isSelects == false)
            {
                if (BookMarkListView.SelectedItem != null)
                {
                    CPDFBookmark bookmark = (CPDFBookmark)BookMarkListView.SelectedItem;
                    if (bookmark != null && sender is MenuItem editPageIndex)
                    {
                        editPageIndex.CommandParameter = bookmark;
                        editPageIndex.Command = viewModel.EditPageIndexCommand;
                    }
                }
            }
        }

        private void UserControl_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Delete)
            {
                if (BookMarkListView.SelectedItems.Count != 0)
                {
                    MenuItemDeleteCommand_Click(sender, e);

                    TxtTitle.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        TxtTitle.Focus();
                    }));
                }
            }
        }
    }
}