using ComPDFKit.PDFDocument;
using PDF_Office.CustomControl;
using PDF_Office.Helper;
using PDF_Office.Model.BOTA;
using PDF_Office.ViewModels.BOTA;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace PDF_Office.Views.BOTA
{
    /// <summary>
    /// OutLineControl.xaml 的交互逻辑
    /// </summary>
    public partial class OutLineControl : UserControl
    {
        /// <summary>
        /// 当前显示了线段的Item
        /// </summary>
        private TreeViewItem Treeviewitem = null;
        /// <summary>
        /// 需要重命名的Item的DataContext
        /// </summary>
        private OutlineNode ReNameOutlineNode = null;
        bool IsReName = false;
        public OutLineControl()
        {
            InitializeComponent();
        }

        private void BtnMore_Click(object sender, RoutedEventArgs e)
        {
            MenuMore.Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom;
            MenuMore.PlacementTarget = BtnMore;
            MenuMore.IsOpen = true;
        }
        private void OutlineView_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed && !IsReName)
            {
                var pos = e.GetPosition(OutlineView);
                HitTestResult result = VisualTreeHelper.HitTest(OutlineView, pos);
                if (result == null)
                {
                    return;
                }
                var treeViewItem = CommonHelper.FindVisualParent<TreeViewItem>(result.VisualHit);
                if (treeViewItem == null)
                {
                    return;
                }
                DataObject dataObj = new DataObject(treeViewItem);
                DragDrop.DoDragDrop(OutlineView, dataObj, DragDropEffects.Move);
                return;
            }
        }

        /// <summary>
        /// 拖拽判断区域以及显示什么线
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Grid_DragOver(object sender, DragEventArgs e)
        {
            (DataContext as OutLineControlViewModel).IsOnDrop = true;
            TreeViewItem sourceitem = e.Data.GetData(typeof(TreeViewItem)) as TreeViewItem;
            if (sourceitem == null)
            {
                return;
            }
            Point pos = e.GetPosition(OutlineView);
            HitTestResult result = VisualTreeHelper.HitTest(OutlineView, pos);
            if (result != null)
            {
                TreeViewItem treeviewitem = CommonHelper.FindVisualParent<TreeViewItem>(result.VisualHit);
                if (treeviewitem != null)
                {
                    //控制最顶端的线
                    if (pos.Y <= 9)
                    {
                        if (Treeviewitem == null)
                        {
                            Treeviewitem = treeviewitem;
                        }
                        (DataContext as OutLineControlViewModel).IsInsertHead = true;
                        (Treeviewitem.DataContext as OutlineNode).IsInsertCurrentLayer = false;
                        (Treeviewitem.DataContext as OutlineNode).IsInsertNextLayer = false;
                    }
                    else
                    {
                        (DataContext as OutLineControlViewModel).IsInsertHead = false;

                        if (Treeviewitem == null)
                        {
                            Treeviewitem = treeviewitem;
                        }
                        else if (!Treeviewitem.Equals(treeviewitem))
                        {
                            (Treeviewitem.DataContext as OutlineNode).IsInsertCurrentLayer = false;
                            (Treeviewitem.DataContext as OutlineNode).IsInsertNextLayer = false;
                            Treeviewitem = treeviewitem;
                        }
                        else
                        {
                            (Treeviewitem.DataContext as OutlineNode).IsInsertCurrentLayer = false;
                            (Treeviewitem.DataContext as OutlineNode).IsInsertNextLayer = false;
                        }
                        if (Treeviewitem.Equals(sourceitem))
                        {
                            return;
                        }

                        //鼠标位于上半部分显示实线，下半部分显示虚线
                        Point p = treeviewitem.TranslatePoint(new Point(0, 0), OutlineView);
                        if (pos.Y < p.Y + 16)
                        {
                            (treeviewitem.DataContext as OutlineNode).IsInsertCurrentLayer = true;
                        }
                        else
                        {
                            (treeviewitem.DataContext as OutlineNode).IsInsertNextLayer = true;
                        }
                    }
                }
            }
        }

        private void Grid_DragLeave(object sender, DragEventArgs e)
        {
            HiddenaAllLine();
        }

        private void OutlineView_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            TextBlock text = e.OriginalSource as TextBlock;
            if (text == null || text.Name == "PageIndex")
            {
                return;
            }
            TreeView tree = sender as TreeView;
            if (tree == null)
            {
                return;
            }

            OutlineNode viewitem = tree.SelectedItem as OutlineNode;
            if (viewitem == null)
            {
                return;
            }
            ReNameOutlineNode = viewitem;
            ReNameOutlineNode.IsReName = Visibility.Collapsed;
            e.Handled = true;
        }

        private void OutlineView_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            (DataContext as OutLineControlViewModel).IsInsertHead = false;
            if (Treeviewitem != null)
            {
                (Treeviewitem.DataContext as OutlineNode).IsInsertCurrentLayer = false;
                (Treeviewitem.DataContext as OutlineNode).IsInsertNextLayer = false;
                Treeviewitem = null;
            }
        }

        private void OutlineView_Drop(object sender, DragEventArgs e)
        {
            TreeViewItem souredata = e.Data.GetData(typeof(TreeViewItem)) as TreeViewItem;
            OutlineNode soureoutlineNode = souredata.DataContext as OutlineNode;
            Point pos = e.GetPosition(OutlineView);
            HitTestResult result = VisualTreeHelper.HitTest(OutlineView, pos);
            if (result == null)
            {
                HiddenaAllLine();
                return;
            }
            TreeViewItem targetitem = CommonHelper.FindVisualParent<TreeViewItem>(result.VisualHit);
            if (targetitem == null)
            {
                HiddenaAllLine();
                return;
            }
            OutlineNode targetoutlineNode = targetitem.DataContext as OutlineNode;
            if (soureoutlineNode.Equals(targetoutlineNode))
            {
                HiddenaAllLine();
                return;
            }
           (DataContext as OutLineControlViewModel).MoveOutLine(targetoutlineNode, soureoutlineNode);

            HiddenaAllLine();
            (DataContext as OutLineControlViewModel).Updata(true);
        }

        /// <summary>
        /// 清理线条显示，以及相关缓存对象
        /// </summary>
        private void HiddenaAllLine()
        {
            (DataContext as OutLineControlViewModel).IsOnDrop = false;
            (DataContext as OutLineControlViewModel).IsInsertHead = false;
            if (Treeviewitem != null)
            {
                (Treeviewitem.DataContext as OutlineNode).IsInsertCurrentLayer = false;
                (Treeviewitem.DataContext as OutlineNode).IsInsertNextLayer = false;
                Treeviewitem = null;
            }
        }

        private void ReName_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            TextBox ReNameText = sender as TextBox;
            if (ReNameText == null)
            {
                return;
            }
            if (ReNameText.Visibility == Visibility.Visible)
            {
                if (ReNameOutlineNode != null)
                {
                    ReNameText.Text = ReNameOutlineNode.Outline.Title;
                }
                ReNameText.Focus();
                ReNameText.SelectAll();
                IsReName = true;
            }
        }

        private void RenameGrid_LostFocus(object sender, RoutedEventArgs e)
        {
            TextBox newdto = e.OriginalSource as TextBox;
            if (newdto == null)
            {
                IsReName = false;
                return;
            }
            string newtitle = string.IsNullOrEmpty(newdto.Text) ? "" : newdto.Text;
            Grid senderdto = sender as Grid;
            if (senderdto == null)
            {
                IsReName = false;
                return;
            }
            senderdto.Visibility = Visibility.Collapsed;
            if (ReNameOutlineNode != null)
            {
                CPDFOutline result = ReNameOutlineNode.Outline;
                if (result != null)
                {
                    if (newtitle == result.Title)
                    {
                        IsReName = false;
                        return;
                    }
                    (DataContext as OutLineControlViewModel).SetTitle(result, newtitle);
                }
                (DataContext as OutLineControlViewModel).Updata(false);
            }
            IsReName = false;
        }

        private void ToolTip_Opened(object sender, RoutedEventArgs e)
        {
            CustomImageControl imageControl = CommonHelper.FindVisualChild<CustomImageControl>(sender as ToolTip);

            OutlineNode outline = imageControl.DataContext as OutlineNode;
            if (outline == null || string.IsNullOrEmpty(outline.PageIndex))
            {
                return;
            }
            //开始绘制
            DrawingContext drawDc = imageControl.OpenDraw();
            WriteableBitmap imageData = (DataContext as OutLineControlViewModel).LoadPreview(outline);
            if (imageData == null)
            {
                imageControl.CloseDraw();
                return;
            }
            drawDc.DrawImage(imageData, new Rect(0, 0, imageControl.Width, imageControl.Height));
            imageControl.CloseDraw();
        }

        private void ToolTip_Closed(object sender, RoutedEventArgs e)
        {
            CustomImageControl imageControl = CommonHelper.FindVisualChild<CustomImageControl>(sender as ToolTip);
            //清空绘制上下文数据
            imageControl.OpenDraw();
            imageControl.CloseDraw();
        }

        private void TreeViewItem_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (e.ClickCount == 1)
            {
                TreeViewItem content = sender as TreeViewItem;
                if (content == null)
                    return;
                Point p = e.GetPosition(OutlineView);
                HitTestResult result = VisualTreeHelper.HitTest(OutlineView, p);
                if (result != null)
                {
                    //点击部位为箭头时，不跳转
                    ToggleButton button = CommonHelper.FindVisualParent<ToggleButton>(result.VisualHit);
                    if (button != null)
                        return;
                    Button btn = CommonHelper.FindVisualParent<Button>(result.VisualHit);
                    if (btn != null)
                        return;
                    (DataContext as OutLineControlViewModel).GoToPage(content);
                }
            }
        }

        private void MenuCollapseAll_Click(object sender, RoutedEventArgs e)
        {
            (DataContext as OutLineControlViewModel).CollapseAll(OutlineView.ItemsSource as ObservableCollection<OutlineNode>);
        }

        private void MenuExpandAll_Click(object sender, RoutedEventArgs e)
        {
            (DataContext as OutLineControlViewModel).ExpandAll(OutlineView.ItemsSource as ObservableCollection<OutlineNode>);
        }

        private void MenuDeleteAll_Click(object sender, RoutedEventArgs e)
        {
            (DataContext as OutLineControlViewModel).DeleteAll();
        }

        private void DowngradeMenu_Click(object sender, RoutedEventArgs e)
        {
            (DataContext as OutLineControlViewModel).Downgrade((sender as MenuItem).DataContext as OutlineNode);
        }

        private void UpgradeMenu_Click(object sender, RoutedEventArgs e)
        {
            (DataContext as OutLineControlViewModel).Upgrade((sender as MenuItem).DataContext as OutlineNode);
        }

        private void DeleteMenu_Click(object sender, RoutedEventArgs e)
        {
            (DataContext as OutLineControlViewModel).RemoveOutline((sender as MenuItem).DataContext as OutlineNode);
        }

        private void RenameMenu_Click(object sender, RoutedEventArgs e)
        {
            ReNameOutlineNode = (sender as MenuItem).DataContext as OutlineNode;
            ReNameOutlineNode.IsReName = Visibility.Collapsed;
        }

        private void ChangeDestinationMenu_Click(object sender, RoutedEventArgs e)
        {
            AlertsMessage alertsMessage = new AlertsMessage();
            alertsMessage.ShowDialog("提示", "确定要将选定大纲的目标位置设置为当前位置吗？", "Cancel", "OK");
            if (alertsMessage.result == ContentResult.Ok)
            {
                (DataContext as OutLineControlViewModel).ChangeOutLineDestination((sender as MenuItem).DataContext as OutlineNode);
            }
        }

        private void BtnAdd_Click(object sender, RoutedEventArgs e)
        {
            int ItemIndex = (DataContext as OutLineControlViewModel).AddOutLine(OutlineView.SelectedItem as OutlineNode);
            OutlineView.UpdateLayout();
            OutlineNode node = (DataContext as OutLineControlViewModel).FindOutlineFromList((DataContext as OutLineControlViewModel).Outlinelist, OutlineView.SelectedItem as OutlineNode, ItemIndex);
            node.IsSelected = true;
            ReNameOutlineNode = node;
            node.IsReName = Visibility.Collapsed;
        }

        private void AddMenu_Click(object sender, RoutedEventArgs e)
        {
            ((sender as MenuItem).DataContext as OutlineNode).IsSelected = true;
            int ItemIndex = (DataContext as OutLineControlViewModel).AddOutLine((sender as MenuItem).DataContext as OutlineNode);
            OutlineView.UpdateLayout();
            OutlineNode node = (DataContext as OutLineControlViewModel).FindOutlineFromList((DataContext as OutLineControlViewModel).Outlinelist, OutlineView.SelectedItem as OutlineNode, ItemIndex);
            node.IsSelected = true;
            ReNameOutlineNode = node;
            node.IsReName = Visibility.Collapsed;
        }

        private void AddParentMenu_Click(object sender, RoutedEventArgs e)
        {
            ((sender as MenuItem).DataContext as OutlineNode).IsSelected = true;
            int ItemIndex = (DataContext as OutLineControlViewModel).InsertParentOutline((sender as MenuItem).DataContext as OutlineNode);
            OutlineView.UpdateLayout();
            OutlineNode node = (DataContext as OutLineControlViewModel).FindOutlineFromList((DataContext as OutLineControlViewModel).Outlinelist, (OutlineView.SelectedItem as OutlineNode).Parent, ItemIndex);
            node.IsSelected = true;
            ReNameOutlineNode = node;
            node.IsReName = Visibility.Collapsed;
        }

        private void AddChlidMenu_Click(object sender, RoutedEventArgs e)
        {
            ((sender as MenuItem).DataContext as OutlineNode).IsExpanded = true;
            ((sender as MenuItem).DataContext as OutlineNode).IsSelected = true;
            int ItemIndex = (DataContext as OutLineControlViewModel).InsertChlidOutline((sender as MenuItem).DataContext as OutlineNode);
            OutlineView.UpdateLayout();
            OutlineNode node = (DataContext as OutLineControlViewModel).FindOutlineFromList((DataContext as OutLineControlViewModel).Outlinelist, (OutlineView.SelectedItem as OutlineNode).Chlidlist[ItemIndex], ItemIndex);
            node.IsSelected = true;
            ReNameOutlineNode = node;
            node.IsReName = Visibility.Collapsed;
        }
    }
}
