using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
using ComPDFKitViewer.PdfViewer;
using PDF_Office.Model;
using System.Collections.ObjectModel;
using PDF_Office.Model.PageEdit;
using Prism.Commands;
using System.Windows;
using System.Windows.Media.Imaging;
using System.Windows.Controls.Primitives;
using System.Diagnostics;
using System.Windows.Controls;
using System.Windows.Threading;
using Prism.Events;
using PDF_Office.EventAggregators;
using System.Windows.Input;
using PDF_Office.Helper;
using Microsoft.Win32;
using ComPDFKit.PDFDocument;
using PDF_Office.CustomControl;

namespace PDF_Office.ViewModels.PageEdit
{
    public class PageEditContentViewModel : BindableBase, INavigationAware
    {

        private CPDFViewer PDFViewer;

        private ViewContentViewModel viewContentViewModel;

        private IDialogService dialogs;

        private IEventAggregator eventor;

        private string unicode = null;

        /// <summary>
        /// 项数据集合
        /// </summary>
        public ObservableCollection<PageEditItem> PageEditItems { get; set; }

        /// <summary>
        /// 页面范围的项集合
        /// </summary>
        public ObservableCollection<string> PageRangeItems { get; set; }

        #region 属性
        /// <summary>
        /// 是否是第一次加载
        /// </summary>
        private bool isFirstLoad = true;

        /// <summary>
        /// 记录多选项中最后一项的索引
        /// </summary>
        private int maxSelectedIndex = 0;

        private Visibility showTip = Visibility.Collapsed;
        /// <summary>
        /// 是否显示渐隐提示
        /// </summary>
        public Visibility ShowTip
        {
            get { return showTip; }
            set
            {
                SetProperty(ref showTip, value);
            }
        }

        private Visibility isLoading = Visibility.Collapsed;
        /// <summary>
        /// 是否正在处理中
        /// </summary>
        public Visibility IsLoading
        {
            get { return isLoading; }
            set
            {
                SetProperty(ref isLoading, value);
            }
        }


        private int listSelecedIndex;
        /// <summary>
        /// 缩略图选中项的索引
        /// </summary>
        public int ListSelectedIndex
        {
            get { return listSelecedIndex; }
            set
            {
                SetProperty(ref listSelecedIndex, value);
                //显示页面范围选择控件
                TbPageRangeVisibility = Visibility.Visible;
                TbPageRange = (ListSelectedIndex + 1).ToString();
                TxtPageInputVisibility = Visibility.Collapsed;
            }
        }

        private bool isMutiSelected;
        /// <summary>
        /// 是否有多选 用于判断倒序和替换功能
        /// </summary>
        public bool IsMutiSelected
        {
            get { return isMutiSelected; }
            set
            {
                SetProperty(ref isMutiSelected, value);
            }
        }


        private int comboxSelectIndex;
        /// <summary>
        /// 下拉框选项集合
        /// </summary>
        public int ComboxSelectIndex
        {
            get { return comboxSelectIndex; }
            set
            {
                SetProperty(ref comboxSelectIndex, value);
                //选中指定的页面范围
                SuitPageRange(comboxSelectIndex);
                //隐藏tb页面范围显示控件
                TbPageRangeVisibility = Visibility.Collapsed;

            }
        }

        private Visibility tbPageRangeVisibility = Visibility.Visible;
        /// <summary>
        /// 页面范围的文本显示
        /// </summary>
        public Visibility TbPageRangeVisibility
        {
            get { return tbPageRangeVisibility; }
            set
            {
                SetProperty(ref tbPageRangeVisibility, value);
                if (value == Visibility.Visible)
                {
                    comboxSelectIndex = -1;
                }
            }
        }

        private string tbPageRange;
        /// <summary>
        /// 页面范围显示的内容
        /// </summary>
        public string TbPageRange
        {
            get { return tbPageRange; }
            set
            {
                SetProperty(ref tbPageRange, value);
            }
        }


        private Visibility txtPageInputVisibility = Visibility.Collapsed;
        /// <summary>
        /// 页面自定义输入框的显示
        /// </summary>
        public Visibility TxtPageInputVisibility
        {
            get { return txtPageInputVisibility; }
            set
            {
                SetProperty(ref txtPageInputVisibility, value);
            }
        }

        /// <summary>
        /// 页面缩放状态，-1 为最小值，1为最大值
        /// </summary>
        private int zoomIndex = 0;

        public int ZoomIndex
        {
            get { return zoomIndex; }
            set
            {
                SetProperty(ref zoomIndex, value);
            }
        }

        #endregion

        #region 命令
        public DelegateCommand<object> SelectionChangedCommand { get; set; }

        /// <summary>
        /// 拦截键盘输入的事件
        /// </summary>
        public DelegateCommand<object> PreviewKeyDown { get; set; }

        /// <summary>
        /// 响应键盘回车事件
        /// </summary>
        public DelegateCommand<object> KeyDown { get; set; }

        /// <summary>
        /// 替换文件
        /// </summary>
        public DelegateCommand ReplaceCommand { get; set; }

        /// <summary>
        /// 插入文件命令
        /// </summary>
        public DelegateCommand<Object> InsertCommand { get; set; }

        /// <summary>
        /// 拆分文件
        /// </summary>
        public DelegateCommand SplitCommand { get; set; }

        /// <summary>
        /// 提取文件
        /// </summary>
        public DelegateCommand ExtractCommand { get; set; }

        /// <summary>
        /// 逆时针旋转
        /// </summary>
        public DelegateCommand LeftRotateCommand { get; set; }

        /// <summary>
        /// 顺时针旋转
        /// </summary>
        public DelegateCommand RightRotateCommand { get; set; }

        /// <summary>
        /// 删除
        /// </summary>
        public DelegateCommand DeleteCommand { get; set; }

        /// <summary>
        /// 倒序
        /// </summary>
        public DelegateCommand ReverseCommand { get; set; }

        /// <summary>
        /// 放大
        /// </summary>
        public DelegateCommand ZoomInCommand { get; set; }

        /// <summary>
        /// 缩小
        /// </summary>
        public DelegateCommand ZoomOutCommand { get; set; }
        #endregion

        public PageEditContentViewModel(IDialogService dialogService, IEventAggregator eventAggregator)
        {
            //变量初始化
            dialogs = dialogService;
            eventor = eventAggregator;
            unicode = App.mainWindowViewModel.SelectedItem.Unicode;
            PageEditItems = new ObservableCollection<PageEditItem>();
            PageRangeItems = new ObservableCollection<string>();

            //绑定命令
            SelectionChangedCommand = new DelegateCommand<object>(SelectionChangedEvent);
            PreviewKeyDown = new DelegateCommand<object>(PreviewKeyDownEvent);
            KeyDown = new DelegateCommand<object>(KeyDownEvent);

            SplitCommand = new DelegateCommand(SplitCommandEvent);
            InsertCommand = new DelegateCommand<object>(InsertCommandEvent);
            ReplaceCommand = new DelegateCommand(ReplaceCommandEvent, CanReplaceCommandExcute).ObservesProperty(() => IsMutiSelected);
            ExtractCommand = new DelegateCommand(ExtractCommandEvent, CanFileCommandExcute).ObservesProperty(() => ListSelectedIndex);
            DeleteCommand = new DelegateCommand(DeleteCommandEvent, CanFileCommandExcute).ObservesProperty(() => ListSelectedIndex);
            LeftRotateCommand = new DelegateCommand(LeftRotateCommandEvent, CanFileCommandExcute).ObservesProperty(() => ListSelectedIndex);
            RightRotateCommand = new DelegateCommand(RightRotateCommandEvent, CanFileCommandExcute).ObservesProperty(() => ListSelectedIndex);
            ReverseCommand = new DelegateCommand(ReverseCommandEvent, CanFileCommandExcute).ObservesProperty(() => ListSelectedIndex);
            ZoomInCommand = new DelegateCommand(ZoomInCommandEvent, CanZoomIn).ObservesProperty(() => ZoomIndex);
            ZoomOutCommand = new DelegateCommand(ZoomOutCommandEvent, CanZoomOut).ObservesProperty(() => ZoomIndex);

            //订阅页面刷新事件
            eventAggregator.GetEvent<PageEditRefreshEvent>().Subscribe(OnPageEditRefreshEvent, e => e.Unicode == unicode);

            RefreshPageRangeItem();
        }


        #region 事件
        /// <summary>
        /// 替换功能的逻辑
        /// </summary>
        private async void ReplaceCommandEvent()
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = false;
            dialog.Filter = PDF_Office.Properties.Resources.OpenDialogFilter;
            if ((bool)dialog.ShowDialog())
            {
                IsLoading = Visibility.Visible;
                await Task.Delay(200);
                int pageCount = PDFViewer.Document.PageCount;
                int insertIndex = listSelecedIndex;

                //从文件插入到指定位置
                var result = await InsertFromFile(listSelecedIndex+1,dialog.FileName);
                if(result)
                {
                    //插入成功后再删除原有页面
                    DoRemoveSelectedPages(new List<int>() { listSelecedIndex });
                }

                ReloadAfterOption(true, true, Tuple.Create(insertIndex-1, insertIndex + pageCount));
                IsLoading = Visibility.Collapsed;
            }
        }

        /// <summary>
        /// 拆分功能的逻辑
        /// </summary>
        private void SplitCommandEvent()
        {
            dialogs.ShowDialog(DialogNames.SplitDialog, null, null);
        }

        /// <summary>
        /// 提取功能的逻辑
        /// </summary>
        private void ExtractCommandEvent()
        {
            dialogs.ShowDialog(DialogNames.ExtractDialog,null,e=> { 
                if(e.Result==ButtonResult.OK&&e.Parameters!=null)
                {
                    var model = e.Parameters.GetValue<ExtractModel>(ParameterNames.DataModel);
                    DoExtractPages(model.IsEveryPageToFile,model.IsDeleteAfterExtract);
                }
            });
        }

        /// <summary>
        /// 插入功能的逻辑
        /// </summary>
        private async void InsertCommandEvent(object type)
        {
            if((string)type==null)
            {
                return;
            }
            //获取插入位置
            int insertIndex = 0;
            if(listSelecedIndex<0)
            {
                insertIndex = 0;
            }
            else
            {
                insertIndex = listSelecedIndex+1;
                if(isMutiSelected)
                {
                    insertIndex = maxSelectedIndex+1;
                }
            }
            IsLoading = Visibility.Visible;
            await Task.Delay(3);
            if((string)type==ParameterNames.InsertType_Blank)
            {
                //插入空白页面
                bool result;
                if (insertIndex == 0)
                {
                    result = PDFViewer.Document.InsertPage(insertIndex, PageEditItems[insertIndex].Size.Width, PageEditItems[insertIndex].Size.Height, null);
                }
                else
                {
                    result = PDFViewer.Document.InsertPage(insertIndex, PageEditItems[insertIndex-1].Size.Width, PageEditItems[insertIndex-1].Size.Height, null);
                }
                if(!result)
                {
                    IsLoading = Visibility.Collapsed;
                    ShowTip = Visibility.Visible;
                    return;
                }

                //UI层插入Item
                var item = GetNewPageEditItem(insertIndex);
                PageEditItems.Insert(insertIndex,item);
         

                ReloadAfterOption(true,true,Tuple.Create(insertIndex,insertIndex+1));
                await Task.Delay(10);
                ListSelectedIndex = insertIndex == 0 ? insertIndex : insertIndex;
            }
            else if((string)type == ParameterNames.InsertType_File)
            {
                OpenFileDialog dialog = new OpenFileDialog();
                dialog.Multiselect = false;
                dialog.Filter = PDF_Office.Properties.Resources.OpenDialogFilter;
                if ((bool)dialog.ShowDialog())
                {
                    //插入文件
                   var result = await InsertFromFile(insertIndex,dialog.FileName);
                    if(!result)
                    {
                        IsLoading = Visibility.Collapsed;
                        ShowTip = Visibility.Visible;
                        return;
                    }

                    ReloadAfterOption(true,true,Tuple.Create(0,PDFViewer.Document.PageCount));
                }
            }
            else
            {
                //插入自定义页面
                dialogs.ShowDialog(DialogNames.InsertDialog, null, null);
            }
            IsLoading = Visibility.Collapsed;
        }

        /// <summary>
        /// 删除选中页面
        /// </summary>
        private async void DeleteCommandEvent()
        {
            IsLoading = Visibility.Visible;
            await Task.Delay(3);
            DoRemoveSelectedPages();
            ReloadAfterOption(true, true, Tuple.Create(0,PDFViewer.Document.PageCount));
            IsLoading = Visibility.Collapsed;
        }

        /// <summary>
        /// 左旋转页面的逻辑
        /// </summary>
        private void LeftRotateCommandEvent()
        {
            RotateSelectedPages(false);
        }

        /// <summary>
        /// 右旋转页面的逻辑
        /// </summary>
        private void RightRotateCommandEvent()
        {
            RotateSelectedPages();
        }

        /// <summary>
        /// 页面倒序的逻辑
        /// </summary>
        private async void ReverseCommandEvent()
        {
            IsLoading = Visibility.Visible;
            await Task.Delay(3);
            List<int> pages = new List<int>();
            for (int i = 0; i <PageEditItems.Count; i++)
            {
                if (PageEditItems[i].Selected)
                {
                    pages.Add(i);
                }
            }
            pages.Sort();

            for (int i = 0; i < pages.Count; i++)
            {
                int preindex = pages[i];
                int laterIndex = pages[pages.Count - i - 1];//尾部的索引
                if (laterIndex <= preindex)//交换完成
                {
                    break;
                }
                var sourceitem = PageEditItems[preindex];
                var targetitem = PageEditItems[laterIndex];

                var result = PDFViewer.Document.ExchangePage(preindex, laterIndex);
                if(!result)
                {
                    ShowTip = Visibility.Visible;
                    IsLoading = Visibility.Collapsed;
                    return;
                }

                PageEditItems.Remove(sourceitem);
                PageEditItems.Remove(targetitem);
                PageEditItems.Insert(preindex, targetitem);
                PageEditItems.Insert(laterIndex, sourceitem);
            }

            await Task.Delay(20);
            for(int i=0;i<pages.Count;i++)
            {
                PageEditItems[i].Selected = true;
            }

            ReloadAfterOption(true,true,null);
            IsLoading = Visibility.Collapsed;
        }

        /// <summary>
        /// 是否可以执行文件操作命令  除插入、拆分外
        /// </summary>
        /// <returns></returns>
        private bool CanFileCommandExcute()
        {
            if (ListSelectedIndex < 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 校验是否可以替换
        /// </summary>
        /// <returns></returns>
        private bool CanReplaceCommandExcute()
        {
            return !IsMutiSelected;
        }

        /// <summary>
        /// 放大页面
        /// </summary>
        private void ZoomInCommandEvent()
        {
            for (int i = 0; i < PageEditItems.Count; i++)
            {
                PageEditItems[i].ItemSize = new Size(PageEditItems[i].ItemSize.Width * 2, PageEditItems[i].ItemSize.Height * 2);
            }
            ZoomIndex++;

            NotifyUIToRefresh();
        }

        /// <summary>
        /// 缩小页面
        /// </summary>
        private void ZoomOutCommandEvent()
        {
            for (int i = 0; i < PageEditItems.Count; i++)
            {
                PageEditItems[i].ItemSize = new Size(PageEditItems[i].ItemSize.Width / 2, PageEditItems[i].ItemSize.Height / 2);
            }
            ZoomIndex--;
            NotifyUIToRefresh();
        }

        private bool CanZoomIn()
        {
            if (ZoomIndex >= 1)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        private bool CanZoomOut()
        {
            if (ZoomIndex <= -1)
            {
                return false;
            }
            else
            {
                return true;
            }
        }


        /// <summary>
        /// 响应UI发送刷新图片的事件
        /// </summary>
        /// <param name="e"></param>
        private void OnPageEditRefreshEvent(PageEditRefreshEventArgs e)
        {
            //UI发送事件过来通知刷新图片时
            //调整逻辑,前后预加载5页
            RefreshItemImage(e.PageRange.Item1 - 2, e.PageRange.Item2 + 2);
        }

        /// <summary>
        /// 选项改变事件  
        /// 虚拟化的时候不会触发选中事件
        /// </summary>
        /// <param name="e"></param>
        private void SelectionChangedEvent(object e)
        {
            var args = e as SelectionChangedEventArgs;
            var listbox = args.OriginalSource as ListBox;
            if (TbPageRangeVisibility == Visibility.Visible && args != null)
            {
                List<int> pagelist = new List<int>();
                for (int i = 0; i < listbox.SelectedItems.Count; i++)
                {
                    if (!pagelist.Contains((listbox.SelectedItems[i] as PageEditItem).PageNumber))
                    {
                        pagelist.Add((listbox.SelectedItems[i] as PageEditItem).PageNumber);
                    }
                }

                //手动取消其他项的选中状态
                for (int j = 0; j < PageEditItems.Count; j++)
                {
                    if (!pagelist.Contains(PageEditItems[j].PageNumber))
                    {
                        PageEditItems[j].Selected = false;
                    }
                }

                ////根据选中的范围 适配全部页面范围、奇数页面范围等
                //if(pagelist.Count==PageEditItems.Count)
                //{
                //    ComboxSelectIndex = 0;
                //    return;
                //}

                string pageparm = CommonHelper.GetPageParmFromList(pagelist);
                TbPageRange = pageparm;


            }
            if (listbox.SelectedItem != null)
            {
                listbox.ScrollIntoView(listbox.SelectedItem);
            }

            //判断是否有选中多项
            if (listbox.SelectedItems.Count > 1)
            {
                IsMutiSelected = true;
                maxSelectedIndex = listbox.Items.IndexOf(listbox.SelectedItems[listbox.SelectedItems.Count-1]);
            }
            else
            {
                IsMutiSelected = false;
            }
        }

        /// <summary>
        /// 限制文本框输入内容
        /// </summary>
        /// <param name="e"></param>
        private void PreviewKeyDownEvent(object e)
        {
            var args = e as KeyEventArgs;
            if (args == null)
            {
                return;
            }

            if (args.Key != Key.Enter && args.Key != Key.Back && args.Key != Key.OemComma && args.Key != Key.Subtract && !((args.Key >= Key.D0 && args.Key <= Key.D9) || (args.Key >= Key.NumPad0 && args.Key <= Key.NumPad9)))
            {
                args.Handled = true;
            }
        }

        /// <summary>
        /// 响应回车确认事件
        /// </summary>
        /// <param name="e"></param>
        private void KeyDownEvent(object e)
        {
            var args = e as KeyEventArgs;
            if (args == null)
            {
                return;
            }
            if (args.Key == Key.Enter)
            {
                List<int> TargetPageIndexs = new List<int>();
                var result = CommonHelper.GetPagesInRange(ref TargetPageIndexs, (args.OriginalSource as TextBox).Text, PDFViewer.Document.PageCount, new char[] { ',', '，' }, new char[] { '-' });
                if (!result)
                {
                    AlertsMessage alertsMessage = new AlertsMessage();
                    alertsMessage.ShowDialog("","请输入有效范围","OK");
                    return;
                }

                //选中输入的页面范围
                for (int i = 0; i < PageEditItems.Count; i++)
                {
                    if (TargetPageIndexs.Contains(PageEditItems[i].PageNumber - 1))
                    {
                        PageEditItems[i].Selected = true;
                    }
                    else
                    {
                        PageEditItems[i].Selected = false;
                    }
                }
            }
        }

        #endregion

        #region 方法

        /// <summary>
        /// 通知UI刷新页面范围
        /// </summary>vb nmjvcx
        private void NotifyUIToRefresh()
        {
            //通知UI刷新页面范围
            eventor.GetEvent<PageEditNotifyEvent>().Publish(new PageEditNotifyEventArgs() { Unicode = unicode });
        }

        /// <summary>
        /// 删除选中项的方法 不带Reload操作
        /// 方便其他逻辑中调用
        /// </summary>
        private void DoRemoveSelectedPages(List<int> pageList = null)
        {
            List<int> indexList = new List<int>();
            if (pageList == null || pageList.Count < 0)
            {
                for (int i = 0; i < PageEditItems.Count; i++)
                {
                    if (PageEditItems[i].Selected)
                    {
                        indexList.Add(i);
                    }
                }
            }
            else
            {
                indexList = pageList;
            }
            
            if(indexList.Count>0&& indexList.Count==PDFViewer.Document.PageCount)
            {
                AlertsMessage alertsMessage = new AlertsMessage();
                alertsMessage.ShowDialog("","不能删除所有页面","OK");
                return;
            }

            var result = PDFViewer.Document.RemovePages(indexList.ToArray());
            if (!result)
            {
                ShowTip = Visibility.Visible;
                return;
            }

            //文档层操作成功后再删除UI层
            for (int i = indexList.Count - 1; i >= 0; i--)
            {
                PageEditItems.RemoveAt(indexList[i]);
            }
        }

        /// <summary>
        /// 提取选中页面的方法
        /// </summary>
        /// <param name="isEveryPageToFile">是否每页生成一个文件</param>
        /// <param name="isDeleteAfterExtract">是否提取后删除页面</param>
        private async void DoExtractPages(bool isEveryPageToFile,bool isDeleteAfterExtract)
        {
            System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (string.IsNullOrEmpty(dialog.SelectedPath))
                {
                    AlertsMessage alertsMessage = new AlertsMessage();
                    alertsMessage.ShowDialog("","","OK");//补充提示文案
                    return;
                }
            }
            else
                return;

            string selectedfile = "";
            IsLoading = Visibility.Visible;
            await Task.Delay(3);
            List<int> pagenums = new List<int>();
            for(int i=0;i<PageEditItems.Count;i++)
            {
                if(PageEditItems[i].Selected)
                {
                    pagenums.Add(PageEditItems[i].PageNumber);
                }
            }

            if (isEveryPageToFile)
            {
                //每页生成的单独的文件
                for (int i = 0; i < pagenums.Count; i++)
                {
                    string filename = PDFViewer.Document.FileName + " " + pagenums[i] + ".pdf";
                    string path = System.IO.Path.Combine(dialog.SelectedPath, filename);
                    path = CommonHelper.CreateFilePath(path);
                    selectedfile = path;
                    CPDFDocument savedoc = CPDFDocument.CreateDocument();
                    bool result = savedoc.ImportPages(PDFViewer.Document, pagenums[i].ToString());
                    if (!result)
                    {
                        savedoc.Release();
                        continue;
                    }
                    result = savedoc.WriteToFilePath(path);
                    if (!result)
                    {
                        savedoc.Release();
                        continue;
                    }
                    savedoc.Release();//释放内存
                }
            }
            else//全部生成一个文件
            {
                string filename = PDFViewer.Document.FileName + " " + CommonHelper.GetPageParmFromList(pagenums) + ".pdf";
                string path = System.IO.Path.Combine(dialog.SelectedPath, filename);
                path = CommonHelper.CreateFilePath(path);
                selectedfile = path;
                CPDFDocument savedoc = CPDFDocument.CreateDocument();
                string range = String.Join(",", pagenums);
                bool result = savedoc.ImportPages(PDFViewer.Document, range);
                if (!result)
                {
                    ShowTip = Visibility.Visible;
                    IsLoading = Visibility.Collapsed;
                    return;
                }
                result = savedoc.WriteToFilePath(path);
                if (!result)
                {
                    ShowTip = Visibility.Visible;
                }
                savedoc.Release();//释放内存
            }

            if(isDeleteAfterExtract)
            {
                DoRemoveSelectedPages();
                ReloadAfterOption(true,true,Tuple.Create(0,PDFViewer.Document.PageCount));
            }

            CommonHelper.ShowFileBrowser(selectedfile);
            IsLoading = Visibility.Collapsed;
        }

        /// <summary>
        /// 将文件插入到指定位置
        /// </summary>
        /// <param name="insertIndex"></param>
        private async Task<bool> InsertFromFile(int insertIndex,string filePath)
        {
            CPDFDocument doc = CPDFDocument.InitWithFilePath(filePath);
            if (doc == null)
            {
                showTip = Visibility.Visible;
                return false;
            }
            if (doc.IsLocked)
            {
                DialogParameters value = new DialogParameters();
                value.Add(ParameterNames.PDFDocument, doc);
                bool result = true;
                dialogs.ShowDialog(DialogNames.VerifyPassWordDialog, value,e=>
                {
                    if (e.Result != ButtonResult.OK)
                    {
                        result = false;
                    }
                });
                if(!result)
                {
                    return false;
                }
            }

           int pageCount = doc.PageCount;

            //插入整个新文档
            //文档层插入
            await Task.Run(() =>
            {
                var result = PDFViewer.Document.ImportPagesAtIndex(doc, "1-" + pageCount, insertIndex);
                if (!result)
                {
                    ShowTip = Visibility.Visible;
                    return false;
                }
                    //插入成功后释放临时Document对象
                    doc.Release();
                return true;
            });

            //UI层插入
            for (int i = 0; i < pageCount; i++)
            {
                var item = GetNewPageEditItem(i);
                PageEditItems.Insert(insertIndex + i, item);
            }

            //加一点延时才能显示选中效果
            await Task.Delay(400);

            for (int i = 0; i < pageCount; i++)
            {
                PageEditItems[insertIndex + i].Selected = true;
            }
            return true;
        }

        /// <summary>
        /// 根据索引创建新的Item
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        private PageEditItem GetNewPageEditItem(int index)
        {
            PageEditItem item = new PageEditItem();
            if (PDFViewer.Document.PageAtIndex(index).Rotation % 2 != 0)
            {
                ///标记为横向页面
                item.isVertical = false;
            }
            item.PageNumber = index + 1;
            var pagesize = PDFViewer.Document.GetPageSize(index);
            item.Size = pagesize;
            item.PageSize = $"{pagesize.Width}mm*{pagesize.Height} mm";
            return item;
        }

        /// <summary>
        /// 进行文件操作后刷新PDFView
        /// 清除undo 栈
        /// 重加载Document
        /// 设置保存状态
        /// </summary>
        /// <param name="needRefreshPageNum">是否需要刷新页码</param>
        /// <param name="needClearUndoHistory">是否需要清空注释Undo栈</param>
        /// <param name="pageRange">需要刷新的页面范围图片</param>
        private void ReloadAfterOption(bool needRefreshPageNum = false, bool needClearUndoHistory = true, Tuple<int, int> pageRange = null)
        {
            if (needRefreshPageNum)
            {
                RefreshPageNum();
            }
            if (needClearUndoHistory)
            {
                PDFViewer.UndoManager.ClearHistory();
            }
            if (pageRange != null)
            {
                if (pageRange.Item2 - pageRange.Item1 > 30)
                {
                    //范围较大时，通知UI获取更准确的刷新范围
                    eventor.GetEvent<PageEditNotifyEvent>().Publish(new PageEditNotifyEventArgs() { Unicode = unicode });
                }
                else
                {
                    RefreshItemImage(pageRange.Item1, pageRange.Item2);
                }
            }
            PDFViewer.UndoManager.CanSave = true;
            PDFViewer.ReloadDocument();
        }
        /// <summary>
        /// 旋转所有选中页面
        /// </summary>
        /// <param name="rightRotate"></param>
        private async void RotateSelectedPages(bool rightRotate = true)
        {
            IsLoading = Visibility.Visible;
            await Task.Delay(2);
            for (int i = 0; i < PageEditItems.Count; i++)
            {
                if (PageEditItems[i].Selected)
                {
                    //逆时针旋转传 - 1  顺时针旋转传1
                    PDFViewer.Document.RotatePage(i, rightRotate ? 1 : -1);
                    PDFViewer.Document.ReleasePages(i);

                    //重新拿图
                    PageEditItems[i].isVertical = !PageEditItems[i].isVertical;
                    PageEditItems[i].IsGetImage = false;
                }
            }
            ReloadAfterOption(false, true, Tuple.Create(0, PageEditItems.Count));
            IsLoading = Visibility.Collapsed;
        }

        /// <summary>
        /// 刷新页码
        /// </summary>
        private void RefreshPageNum()
        {
            for (int i = 0; i < PageEditItems.Count; i++)
            {
                PageEditItems[i].PageNumber = i + 1;
            }
        }

        /// <summary>
        /// 刷新页面范围下拉框
        /// </summary>
        private void RefreshPageRangeItem()
        {
            PageRangeItems.Clear();
            PageRangeItems.Add("所有页面");
            PageRangeItems.Add("奇数页");
            PageRangeItems.Add("偶数页");
            PageRangeItems.Add("横向页面");
            PageRangeItems.Add("纵向页面");
            PageRangeItems.Add("自定义");
        }


        /// <summary>
        /// 选中目标页面范围的页面
        /// </summary>
        /// <param name="index">页面范围选中项索引</param>
        private void SuitPageRange(int index)
        {
            switch (index)
            {
                case 0:
                    for (int i = 0; i < PageEditItems.Count; i++)
                    {
                        PageEditItems[i].Selected = true;
                    }
                    break;

                case 1:
                    //奇数页
                    for (int i = 0; i < PageEditItems.Count; i++)
                    {
                        if (i % 2 == 0)
                        {
                            PageEditItems[i].Selected = true;
                        }
                        else
                        {
                            PageEditItems[i].Selected = false;
                        }
                    }
                    break;
                case 2:
                    //偶数页
                    for (int i = 0; i < PageEditItems.Count; i++)
                    {
                        if (i % 2 == 0)
                        {
                            PageEditItems[i].Selected = false;
                        }
                        else
                        {
                            PageEditItems[i].Selected = true;
                        }
                    }
                    break;
                case 3://横向页面
                    for (int i = 0; i < PageEditItems.Count; i++)
                    {
                        if (PDFViewer.Document.PageAtIndex(i).Rotation % 2 == 0)
                        {
                            PageEditItems[i].Selected = false;
                        }
                        else
                        {
                            PageEditItems[i].Selected = true;
                        }
                    }
                    break;
                case 4://纵向页面
                    for (int i = 0; i < PageEditItems.Count; i++)
                    {
                        if (PDFViewer.Document.PageAtIndex(i).Rotation % 2 == 0)
                        {
                            PageEditItems[i].Selected = true;
                        }
                        else
                        {
                            PageEditItems[i].Selected = false;
                        }
                    }
                    break;
                case 5://自定义
                    //取消所有选中
                    ListSelectedIndex = -1;
                    TxtPageInputVisibility = Visibility.Visible;
                    break;
                default:
                    break;
            }
        }


        /// <summary>
        /// 是否显示页面尺寸
        /// </summary>
        /// <param name="show">是或否</param>
        private void ShowPageSize(bool show = true)
        {
            for (int i = 0; i < PageEditItems.Count; i++)
            {
                PageEditItems[i].ShowPageSize = show;
            }
        }


        /// <summary>
        /// 从PDFView获取所有Items集合
        /// </summary>
        private void GetSourceItems(bool isFirstLoad)
        {
            if (isFirstLoad)
            {
                PageEditItems.Clear();
                for (int i = 0; i < PDFViewer.Document.PageCount; i++)
                {
                    var item = GetNewPageEditItem(i);
                    PageEditItems.Add(item);
                }
            }
            else
            {
                //后续进来仅刷新图片即可
                for (int i = 0; i < PageEditItems.Count; i++)
                {
                    PageEditItems[i].IsGetImage = false;
                }
            }
        }

        /// <summary>
        /// 刷新书签列表
        /// </summary>
        public void RefreshBookMarkList()
        {
            if (PDFViewer != null)
            {
                var booklist = PDFViewer.Document.GetBookmarkList();
                if (booklist == null)
                {
                    return;
                }
                //获取所有书签的Index集合
                List<int> marks = new List<int>();
                for (int i = 0; i < booklist.Count; i++)
                {
                    marks.Add(booklist[i].PageIndex);
                }

                //不能只遍历marks集合，考虑书签集合元素删除的情况
                for (int k = 0; k < PageEditItems.Count; k++)
                {
                    if (marks.Contains(k))
                        PageEditItems[k].HaveBookMark = true;
                    else
                        PageEditItems[k].HaveBookMark = false;
                }
            }
        }

        /// <summary>
        /// 刷新指定范围的图片
        /// </summary>
        /// <param name="startIndex"></param>
        /// <param name="endIndex"></param>
        private async void RefreshItemImage(int startIndex, int endIndex)
        {
            for (int i = startIndex; i <= endIndex; i++)
            {
                if (i <= PDFViewer.Document.PageCount - 1 && i >= 0 && PageEditItems.Count > 0)
                {
                    //宽高为样式中图片控件宽高
                    if (PageEditItems[i].isVertical)
                    {
                        await PDFViewer.GetThumbnail(i, 208, 294);
                    }
                    else
                    {
                        //获取横图
                        await PDFViewer.GetThumbnail(i, 294, 208);
                    }
                }
            }
        }

        /// <summary>
        /// 从底层库获取对应页面的图片
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="thumb"></param>
        /// <param name="w"></param>
        /// <param name="h"></param>
        private void PDFViewer_OnThumbnailGenerated(int pageIndex, byte[] thumb, int w, int h)
        {
            try
            {
                if (PageEditItems.Count >= pageIndex + 1 && !PageEditItems[pageIndex].IsGetImage)
                {
                    PixelFormat fmt = PixelFormats.Bgra32;
                    BitmapSource bps = BitmapSource.Create(w, h, 96.0, 96.0, fmt, null, thumb, (w * fmt.BitsPerPixel + 7) / 8);
                    PageEditItems[pageIndex].Image = bps;
                    PageEditItems[pageIndex].IsGetImage = true;
                }
            }
            catch
            {

            }
        }
        #endregion

        #region Navigate
        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {


        }

        /// <summary>
        /// 从其他页面导航过来的时候会触发
        /// 考虑只有在页面编辑的时候会进行页面的删减,可以尝试逻辑优化:仅第一次进入页面编辑时重新刷新页面
        /// </summary>
        /// <param name="navigationContext"></param>
        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            navigationContext.Parameters.TryGetValue<ViewContentViewModel>(ParameterNames.ViewContentViewModel, out viewContentViewModel);
            navigationContext.Parameters.TryGetValue<CPDFViewer>(ParameterNames.PDFViewer, out PDFViewer);
            if (PDFViewer != null)
            {
                if (isFirstLoad)
                {
                    PDFViewer.OnThumbnailGenerated += PDFViewer_OnThumbnailGenerated;
                    ZoomIndex = 0;

                }

                GetSourceItems(isFirstLoad);

                ListSelectedIndex = PDFViewer.CurrentIndex;

                RefreshBookMarkList();
                isFirstLoad = false;
            }
        }
        #endregion
    }
}
