using PDF_Office.CustomControl;
using PDF_Office.Helper;
using PDF_Office.Model.PDFTool;
using PDF_Office.ViewModels.HomePanel;
using System;
using System.Collections.Generic;
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.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace PDF_Office.Views.HomePanel.PDFTools
{
   
    /// <summary>
    /// ToolbarPage.xaml 的交互逻辑
    /// </summary>
    public partial class PDFToolsContent : UserControl
    {
        private ListItemQuickTool sourceListItem = null;
        private ListItemQuickTool targetListItem = null;
        private ListItemQuickTool quickSourceListItem = null;

        private List<ToolItem> quickTools = null;
        private List<ToolItem> allTools = null;
        private List<ToolItem> moreTools = null;
        PDFTools PDFtools;

        private string fileName = string.Empty;
        private BitmapSource bitmapSource = null;
        private bool isMoreCuts = false;
        private bool isMove = false;

        private Point wrpnlPoint;
        private Point mousePoint;

        public PDFToolsContent()
        {
            InitializeComponent();
            PDFtools = new PDFTools();


            #region ListBox

            SetListBox();

            #endregion ListBox

        }

        /// <summary>
        /// 获取与窗口相对的鼠标位置。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnRendering(object sender, EventArgs e)
        {
            mousePoint = Mouse.GetPosition(this);
            Console.WriteLine($"鼠标坐标：{mousePoint.X}:{mousePoint.Y}");
        }

        private void SetListBox()
        {
            quickTools = PDFtools.QuickTools;
            allTools = PDFtools.AllTools;

            ListShortCuts.ItemsSource = quickTools;
            //对比两个集合，取差值
            moreTools = allTools.Except(quickTools).ToList();

            ListMoreCuts.ItemsSource = moreTools;

        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
        }

        private void ListBoxMoreCuts_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            var pos = e.GetPosition(ListMoreCuts);

            if (e.LeftButton == MouseButtonState.Pressed)
            {
                ListMoreCuts.AllowDrop = true;

                HitTestResult result = VisualTreeHelper.HitTest(ListMoreCuts, pos);
                if (result == null)
                {
                    sourceImage.Visibility = Visibility.Hidden;
                    return;
                }
                sourceListItem = (ListItemQuickTool)CommonHelper.FindVisualParent<ListBoxItem>(result.VisualHit);
                if (sourceListItem == null || sourceListItem.Content != ListMoreCuts.SelectedItem)
                {
                    return;
                }
                //获取控件相对于另一控件的坐标
                wrpnlPoint = sourceListItem.TranslatePoint(new Point(), this);

                System.Windows.DataObject dataObj = new System.Windows.DataObject(sourceListItem.Content as ToolItem);

                if (dataObj != null)
                {
                    //控件截图
                    IsMoreToolbars();

                    if (string.IsNullOrEmpty(fileName))
                    {
                        sourceImage.Visibility = Visibility.Hidden;
                        return;
                    }
                    //图片解码
                    ImageDecoding();

                    isMoreCuts = true;
                    DragDrop.DoDragDrop(ListMoreCuts, dataObj, System.Windows.DragDropEffects.Move);
                }
            }
            else
            {
                moveImage.Visibility = Visibility.Hidden;
                sourceImage.Visibility = Visibility.Hidden;
            }
        }

        private void ImageDecoding()
        {
            Stream imageStreamSource = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
            PngBitmapDecoder decoder = new PngBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
            bitmapSource = decoder.Frames[0];
        }

        private void IsMoreToolbars()
        {
            var source = sourceListItem.Content as ToolItem;
            if (moreTools == null && moreTools.Count != 0) return;
            List<ToolItem> toolModule = moreTools.FindAll(item => item.Title == source.Title);
            if (toolModule.Count > 0)
            {
                // 判断文件夹是否存在，不存在则创建
                DirectoryInfo folder = new DirectoryInfo(System.IO.Path.Combine(System.IO.Path.GetTempPath(), "Asource"));
                if (!folder.Exists)
                {
                    folder.Create();
                }
                fileName = System.IO.Path.Combine(folder.FullName, $"{source.Title}.png");

                SaveToPng(sourceListItem, fileName);
            }
        }

        private void ListBoxShortCuts_Drop(object sender, DragEventArgs e)
        {
            var pos = e.GetPosition(ListShortCuts);

            var result = VisualTreeHelper.HitTest(ListShortCuts, pos);
            if (result == null)
            {
                WorkingWithAnimation(pos);
                return;
            }

            //查找目标数据
            targetListItem = (ListItemQuickTool)CommonHelper.FindVisualParent<ListBoxItem>(result.VisualHit);
            if (targetListItem == null)
            {
                WorkingWithAnimation(pos);
                return;
            }
            var targetAToolModule = targetListItem.Content as ToolItem;
            ToolItem target = quickTools.Find(c => c.Title == targetAToolModule.Title);

            //查找元数据
            var sourceAToolModule = e.Data.GetData(typeof(ToolItem)) as ToolItem;
            if (sourceAToolModule == null)
            {
                sourceImage.Visibility = Visibility.Hidden;
                // target.SetValue(AToolModule.IsFilePickedProperty, false);
                return;
            }

            if (ReferenceEquals(targetAToolModule, sourceAToolModule))
            {
                sourceImage.Visibility = Visibility.Hidden;
                // target.SetValue(AToolModule.IsFilePickedProperty, false);
                return;
            }
            if (targetAToolModule == null && sourceAToolModule == null)
            {
                sourceImage.Visibility = Visibility.Hidden;
                // target.SetValue(AToolModule.IsFilePickedProperty, false);
                return;
            }

            ModuleExchange(sourceAToolModule, targetAToolModule);
        }

        private void ModuleExchange(ToolItem sourceAToolModule, ToolItem targetAToolModule)
        {
            if (moreTools == null) return;
            ToolItem source = moreTools.Find(c => c.Title == sourceAToolModule.Title);

            int targetIndex = quickTools.FindIndex(item => item.Title == targetAToolModule.Title);
            if (targetIndex < 0) return;
            if (!isMoreCuts)
            {
                ListMoreCuts.AllowDrop = false;
                sourceImage.Visibility = Visibility.Hidden;
                source = quickTools.Find(c => c.Title == sourceAToolModule.Title);
                if (source == null) return;
                int sourceIndex = quickTools.FindIndex(item => item.Title == sourceAToolModule.Title);
                if (sourceIndex < 0) return;
                var temp = quickTools[sourceIndex];
                quickTools[sourceIndex] = quickTools[targetIndex];
                quickTools[targetIndex] = temp;
                ListShortCuts.Items.Refresh();
                ListBoxCutsWidthChanged(ListShortCuts);
            }
            else
            {
                if (target == null) return;
                if (source == null) return;
                moreTools.Remove(source);
                moreTools.Insert(0, target);

                quickTools.Remove(target);
                quickTools.Insert(targetIndex, source);

                ListMoreCuts.Items.Refresh();
                ListShortCuts.Items.Refresh();

                sourceImage.Visibility = Visibility.Hidden;
                targetListItem.IsOverModular = false;
                ListBoxCutsWidthChanged(ListShortCuts);
                ListBoxCutsWidthChanged(ListMoreCuts);
            }
        }

        private void WorkingWithAnimation(Point pos)
        {
            sourceImage.Visibility = Visibility.Hidden;

            if (!isMoreCuts || !isMove)
            {
                moveImage.Visibility = Visibility.Hidden;
            }
            else
            {
                if (sourceListItem == null) return;
                moveImage.Visibility = Visibility.Visible;

                Point point = sourceListItem.TransformToAncestor(this).Transform(new Point(0, 0));

                ImageMoveTo(new Point(pos.X - 80, pos.Y), new Point(wrpnlPoint.X + 40, wrpnlPoint.Y), moveImage, 200);
            }
        }

        /// <summary>
        /// 图片移动动画
        /// </summary>
        /// <param name="curPoint">初始位置</param>
        /// <param name="deskPoint">控件要移动到的位置</param>
        /// <param name="ell">你要移动的空间</param>
        /// <param name="space">设置移动的时间片（关系到控件移动的速度）</param>
        private void ImageMoveTo(Point curPoint, Point deskPoint, Image ell, double space)
        {
            Storyboard storyboard = new Storyboard();   //创建Storyboard对象

            double lxspeed = space, lyspeed = space; //设置X方向 / Y方向 移动时间片

            //创建X轴方向动画

            DoubleAnimation dox = new DoubleAnimation(
              curPoint.X,
              deskPoint.X,
              new Duration(TimeSpan.FromMilliseconds(lxspeed))
            );

            //创建Y轴方向动画

            DoubleAnimation doy = new DoubleAnimation(
             curPoint.Y,
              deskPoint.Y,
              new Duration(TimeSpan.FromMilliseconds(lyspeed))
            );
            Storyboard.SetTarget(dox, ell);
            Storyboard.SetTarget(doy, ell);

            Storyboard.SetTargetProperty(dox, new PropertyPath("(UIElement.RenderTransform).(TranslateTransform.X)"));
            Storyboard.SetTargetProperty(doy, new PropertyPath("(UIElement.RenderTransform).(TranslateTransform.Y)"));

            storyboard.Children.Add(dox);
            storyboard.Children.Add(doy);

            storyboard.Completed += Storyboard_Completed;
            //动画播放
            storyboard.Begin();
        }

        private void Storyboard_Completed(object sender, EventArgs e)
        {
            moveImage.Visibility = Visibility.Hidden;
        }

        /// <summary>
        /// 控件截图
        /// </summary>
        /// <param name="visual">控件</param>
        /// <param name="fileName">文件路径 C:\Users\oyxh\AppData\Local\Temp\</param>
        private void SaveToPng(FrameworkElement visual, string fileName)
        {
            DrawingVisual drawingVisual = new DrawingVisual();
            using (DrawingContext context = drawingVisual.RenderOpen())
            {
                VisualBrush brush = new VisualBrush(sourceListItem) { Stretch = Stretch.None };
                context.DrawRectangle(brush, null, new Rect(0, 0, sourceListItem.ActualWidth, sourceListItem.ActualHeight));
                context.Close();
            }

            RenderTargetBitmap targetBitmap = new RenderTargetBitmap((int)sourceListItem.ActualWidth, (int)sourceListItem.ActualHeight, 96d, 96d, PixelFormats.Default);
            targetBitmap.Render(drawingVisual);

            FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
            PngBitmapEncoder encoder = new PngBitmapEncoder();
            encoder.Interlace = PngInterlaceOption.On;
            encoder.Frames.Add(BitmapFrame.Create(targetBitmap));
            encoder.Save(stream);
            stream.Close();
        }

        private ToolItem target;

        private void ListBoxShortCuts_DragOver(object sender, DragEventArgs e)
        {
            var pos = e.GetPosition(ListShortCuts);
            Console.WriteLine($"pos:{pos.X}  {pos.Y} this.Grid.ActualHeight1 {this.Grid.ActualHeight}");
            if (pos.Y < 0)
            {
                isMove = false;
                sourceImage.Visibility = Visibility.Hidden;
                sourceListItem = null;
                return;
            }
            if (pos.Y >= this.Grid.ActualHeight - 50)
            {
                isMove = false;
                sourceImage.Visibility = Visibility.Hidden;
                sourceListItem = null;
                return;
            }
            if (pos.X < 10)
            {
                isMove = false;
                sourceListItem = null;
                sourceImage.Visibility = Visibility.Hidden;
                return;
            }
            if (pos.X >= this.Grid.ActualWidth - 10)
            {
                isMove = false;
                sourceListItem = null;
                sourceImage.Visibility = Visibility.Hidden;
                return;
            }

            if (!isMoreCuts)
            {
                var sourceAToolModule = e.Data.GetData(typeof(ToolItem)) as ToolItem;
                if (sourceAToolModule == null) return;
                int sourceIndex = quickTools.FindIndex(item => item.Title == sourceAToolModule.Title);
                //根据index找listbox对应的item
                sourceListItem = (ListItemQuickTool)(ListShortCuts.ItemContainerGenerator.ContainerFromIndex(sourceIndex) as FrameworkElement);
                if (sourceListItem == null)
                {
                    return;
                }
                ListMoreCuts.AllowDrop = false;
                sourceImage.Visibility = Visibility.Hidden;
            }
            else
            {
                var sourceAToolModule = e.Data.GetData(typeof(ToolItem)) as ToolItem;
                if (sourceAToolModule == null) return;
                int sourceIndex = moreTools.FindIndex(item => item.Title == sourceAToolModule.Title);
                //根据index找listbox对应的item
                sourceListItem = (ListItemQuickTool)(ListMoreCuts.ItemContainerGenerator.ContainerFromIndex(sourceIndex) as FrameworkElement);
                if (sourceListItem == null)
                {
                    return;
                }
                isMove = true;
                //图片绑定
                ImageBinding(pos);
            }
            var result = VisualTreeHelper.HitTest(ListShortCuts, pos);
            if (result == null)
            {
                return;
            }

            //查找目标数据
            targetListItem = (ListItemQuickTool)CommonHelper.FindVisualParent<ListBoxItem>(result.VisualHit);

            if (targetListItem == null)
            {
                //sourceImage.Visibility = Visibility.Hidden;
                return;
            }
            var targetAToolModule = targetListItem.Content as ToolItem;
            if (targetAToolModule == null) return;
            target = quickTools.Find(c => c.Title == targetAToolModule.Title);
        }

        /// <summary>
        ///图片绑定
        /// </summary>
        private void ImageBinding(System.Windows.Point pos)
        {
            sourceImage.Visibility = Visibility.Visible;
            sourceImage.Source = bitmapSource;
            sourceImage.Margin = new Thickness(pos.X - 80, pos.Y, 0, 0);

            moveImage.Source = sourceImage.Source;
        }

        private void ListBoxShortCuts_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                ListMoreCuts.AllowDrop = false;
                var pos = e.GetPosition(ListShortCuts);
                HitTestResult result = VisualTreeHelper.HitTest(ListShortCuts, pos);
                if (result == null)
                {
                    return;
                }
                quickSourceListItem = (ListItemQuickTool)CommonHelper.FindVisualParent<ListBoxItem>(result.VisualHit);
                if (quickSourceListItem == null || quickSourceListItem.Content != ListShortCuts.SelectedItem)
                {
                    return;
                }
                System.Windows.DataObject dataObj = new System.Windows.DataObject(quickSourceListItem.Content as ToolItem);

                if (dataObj != null)
                {
                    isMoreCuts = false;
                    DragDrop.DoDragDrop(ListShortCuts, dataObj, System.Windows.DragDropEffects.Move);
                }
            }
            else
            {
                sourceImage.Visibility = Visibility.Hidden;
                //moveImage.Visibility = Visibility.Hidden;
            }
        }

        private void sourceImage_Drop(object sender, DragEventArgs e)
        {
            ListBoxShortCuts_Drop(sender, e);
        }

        private void sourceImage_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            ListBoxMoreCuts_PreviewMouseMove(sender, e);
        }

        private void sourceImage_DragOver(object sender, DragEventArgs e)
        {
            ListBoxShortCuts_DragOver(sender, e);
        }

        private void Label_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            ListBoxMoreCuts_PreviewMouseMove(sender, e);
        }

        private void ListBoxMoreCuts_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            //获取当前控件元素相对鼠标点击的位置（只有点击在当前A控件，会触发事件并返回相对A控件的鼠标位置）。
            Point pp = Mouse.GetPosition(e.Source as FrameworkElement);//WPF方法
            sourceImage.Visibility = Visibility.Hidden;
            if (pp.X < 0 || pp.Y < 0)
            {
                moveImage.Visibility = Visibility.Hidden;
            }
        }

        /// <summary>
        /// 扩展收缩UI
        /// </summary>
        /// <param name="IsShowConciseContent">是否收缩</param>
        private void ShowToolsUI(ListBoxEx list,bool IsShowConciseContent)
        {
            foreach (var item in list.Items)
            {

                var listBoxItem = list.ItemContainerGenerator.ContainerFromItem(item) as ListBoxItem;
                if (listBoxItem != null)
                {

                    var viewItem = listBoxItem.ContentTemplate;
                    var myContentPresenter = CommonHelper.FindVisualChild<ContentPresenter>(listBoxItem);
                    var obj = viewItem.FindName("data", myContentPresenter);

                    var checkNum = obj as PDFToolItem;

                    if (checkNum != null)
                    {
                        checkNum.IsShowConciseContent = IsShowConciseContent;
                    }

                }
            }

        }


        private void ListBoxShortCuts_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            ListBoxCutsWidthChanged(ListShortCuts);
        }

        private void ListBoxMoreCuts_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            ListBoxCutsWidthChanged(ListMoreCuts);
        }

        private void ListBoxCutsWidthChanged(ListBoxEx list)
        {
            //3x + 4y = containerWidth;
            //3x = y;
            //x为间距，y为item；
            double containerWidth = list.ActualWidth - 20;
            int widthItem = (int)containerWidth / 5;
            double margin = widthItem / 3;
            int i = 0;
            foreach (var item in list.Items)
            {
                i++;
                var listBoxItem = list.ItemContainerGenerator.ContainerFromItem(item) as ListBoxItem;
                if (listBoxItem != null)
                {
                    if (i % 4 != 0)
                    {
                        listBoxItem.Margin = new Thickness(0, 0, margin, 0);
                    }
                    else
                    {
                        listBoxItem.Margin = new Thickness(0, 0, 0, 0);
                    }
                    listBoxItem.Width = widthItem;
                }
            }
        }

        private void BtnTools_Click(object sender, RoutedEventArgs e)
        {

        }

        bool isExtend = false;
        private void BtnMore_Click(object sender, RoutedEventArgs e)
        {
            if(isExtend)
            {
                isExtend = false;
                ShowToolsUI(ListShortCuts, false);
                ShowToolsUI(ListMoreCuts, false);
            }
            else
            {
                isExtend = true;
                ShowToolsUI(ListShortCuts, true);
                ShowToolsUI(ListMoreCuts, true);
            }
           
           

        }


        //自适应流式布局，以防改需求备用
        //private void ListBoxMoreCutsWidthChanged()
        //{
        //    double containerWidth = ListBoxShortCuts.ActualWidth;
        //    int Rowcount = (int)containerWidth / 240;
        //    double EndRow = containerWidth % 240.0;
        //    Rowcount = EndRow >= 140 ? ++Rowcount : Rowcount;

        //    int i = 0;
        //    foreach (var item in ListBoxMoreCuts.Items)
        //    {
        //        i++;
        //        var listBoxItem = ListBoxMoreCuts.ItemContainerGenerator.ContainerFromItem(item) as ListBoxItem;
        //        if (listBoxItem != null)
        //        {
        //            if (i % Rowcount != 0)
        //            {
        //                listBoxItem.Margin = new Thickness(0, 0, 100, 0);

        //            }
        //            else
        //            {
        //                listBoxItem.Margin = new Thickness(0, 0, 0, 0);
        //            }
        //        }
        //    }
        //}


    }

}
