using ComPDFKitViewer;
using ComPDFKitViewer.AnnotEvent;
using ComPDFKitViewer.PdfViewer;
using Microsoft.Office.Interop.Word;
using PDF_Master.CustomControl;
using PDF_Master.EventAggregators;
using PDF_Master.Helper;
using PDF_Master.Model;
using PDF_Master.Model.BOTA;
using PDF_Master.ViewModels.BOTA;
using PDF_Master.Views;
using PDF_Master.Views.BOTA;
using PDFSettings.Settings;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
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.Forms;

namespace PDF_Master.ViewModels.PropertyPanel.ViewModular
{
    public class ViewModularContentViewModel : BindableBase, INavigationAware
    {
        #region 文案

        private string T_title;

        public string T_Title
        {
            get { return T_title; }
            set
            {
                SetProperty(ref T_title, value);
            }
        }

        private string T_modeTitle;

        public string T_ModeTitle
        {
            get { return T_modeTitle; }
            set
            {
                SetProperty(ref T_modeTitle, value);
            }
        }

        private string T_single;

        public string T_Single
        {
            get { return T_single; }
            set
            {
                SetProperty(ref T_single, value);
            }
        }

        private string T_two;

        public string T_Two
        {
            get { return T_two; }
            set
            {
                SetProperty(ref T_two, value);
            }
        }

        private string T_book;

        public string T_Book
        {
            get { return T_book; }
            set
            {
                SetProperty(ref T_book, value);
            }
        }

        private string T_read;

        public string T_Read
        {
            get { return T_read; }
            set
            {
                SetProperty(ref T_read, value);
            }
        }

        private string T_full;

        public string T_Full
        {
            get { return T_full; }
            set
            {
                SetProperty(ref T_full, value);
            }
        }

        private string T_continuousScroll;

        public string T_ContinuousScroll
        {
            get { return T_continuousScroll; }
            set
            {
                SetProperty(ref T_continuousScroll, value);
            }
        }

        private string T_pageBreak;

        public string T_PageBreak
        {
            get { return T_pageBreak; }
            set
            {
                SetProperty(ref T_pageBreak, value);
            }
        }

        private string T_rotateTitle;

        public string T_RotateTitle
        {
            get { return T_rotateTitle; }
            set
            {
                SetProperty(ref T_rotateTitle, value);
            }
        }

        private void InitString()
        {
            T_Title = App.MainPageLoader.GetString("ViewProperties_Title");
            T_ModeTitle = App.MainPageLoader.GetString("ViewProperties_Mode");
            T_Single = App.MainPageLoader.GetString("ViewProperties_Single");
            T_Two = App.MainPageLoader.GetString("ViewProperties_Two");
            T_Book = App.MainPageLoader.GetString("ViewProperties_Book");
            T_Read = App.MainPageLoader.GetString("ViewProperties_Read");
            T_Full = App.MainPageLoader.GetString("ViewProperties_Full");
            T_ContinuousScroll = App.MainPageLoader.GetString("ViewProperties_ContinuousScroll");
            T_PageBreak = App.MainPageLoader.GetString("ViewProperties_PageBreak");
            T_RotateTitle = App.MainPageLoader.GetString("ViewProperties_RotateTitle");
        }

        #endregion 文案

        private IRegionManager region;

        private IDialogService dialogs;

        //记录 单页 双页  书本模式
        private ViewMode viewmode = ViewMode.Single;

        public CPDFViewer PDFViewer { get; set; }
        public CPDFViewer SplitScreenPDFViewer { get; set; }
        public BottomToolContentViewModel BottomToolContentViewModel { get; set; }
        public ViewContentViewModel ViewContentViewModel { get; set; }
        public string SplitScreenViewRegionName { get; set; }
        public string ThemesContentName { get; set; }
        private Visibility splitScreenViewVisible = Visibility.Collapsed;
        public OpenFileInfo OpenFileInfo = null;

        private IEventAggregator events;

        /// <summary>
        /// 用于区分事件的唯一码
        /// </summary>
        private string unicode;

        /// <summary>
        /// 控制Content的显示 用于显示分屏的模块
        /// </summary>
        public Visibility SplitScreenViewVisible
        {
            get { return splitScreenViewVisible; }
            set
            {
                SetProperty(ref splitScreenViewVisible, value);
            }
        }

        private bool isContinue = true;

        public bool IsContinue
        {
            get { return isContinue; }
            set
            {
                SetProperty(ref isContinue, value);
                if (value)
                {
                    SetModeView();
                }
            }
        }

        private bool isPagesBreak = true;

        public bool IsPagesBreak
        {
            get { return isPagesBreak; }
            set
            {
                SetProperty(ref isPagesBreak, value);
            }
        }

        private bool isSingleView;

        public bool IsSingleView
        {
            get { return isSingleView; }
            set
            {
                SetProperty(ref isSingleView, value);
                if (value)
                {
                    SetModeView();
                }
            }
        }

        private bool isTwoPageView;

        public bool IsTwoPageView
        {
            get { return isTwoPageView; }
            set
            {
                SetProperty(ref isTwoPageView, value);
                if (value)
                {
                    SetModeView();
                }
            }
        }

        private bool isBookModeView;

        public bool IsBookModeView
        {
            get { return isBookModeView; }
            set
            {
                SetProperty(ref isBookModeView, value);
                if (value)
                {
                    SetModeView();
                }
            }
        }

        private bool rBtnFullScreenIsChecked = false;

        public bool IsFullScreen
        {
            get { return rBtnFullScreenIsChecked; }
            set
            {
                SetProperty(ref rBtnFullScreenIsChecked, value);
            }
        }

        public DelegateCommand<object> SplitScreenCommand { get; set; }
        public DelegateCommand<object> DisableCommand { get; set; }

        public DelegateCommand SetViewModeCommand { get; set; }
        public DelegateCommand<object> ContinueCommand { get; set; }
        public DelegateCommand<object> PagesBreakCommand { get; set; }

        public DelegateCommand<object> RotateCommand { get; set; }

        public DelegateCommand OpenFullCommand { get; set; }

        public ViewModularContentViewModel(IRegionManager regionManager, IDialogService dialogService, IEventAggregator eventAggregator)
        {
            InitString();
            region = regionManager;
            dialogs = dialogService;
            events = eventAggregator;
            unicode = App.mainWindowViewModel.SelectedItem.Unicode;
            //未显示时无法注册上Region名称,所以需要短暂显示
            //SplitScreenViewVisible = Visibility.Visible;
            //SplitScreenViewRegionName = RegionNames.SplitScreenViewRegionName;
            ThemesContentName = RegionNames.ThemesContentName;
            //SplitScreenViewVisible = Visibility.Collapsed;

            SplitScreenCommand = new DelegateCommand<object>(SplitScreenEvent);
            DisableCommand = new DelegateCommand<object>(DisableEvent);
            SetViewModeCommand = new DelegateCommand(SetModeView);
            ContinueCommand = new DelegateCommand<object>(ContinueEvent);
            PagesBreakCommand = new DelegateCommand<object>(PagesBreakEvent);
            RotateCommand = new DelegateCommand<object>(RotateEvent);
            OpenFullCommand = new DelegateCommand(OpenFullWindow);

            //在构造函数中使用Region需要借助Dispatcher 确保UI已经加载完成,加载BOTA区域
            System.Windows.Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send, new Action(() =>
            {
                NavigationParameters parameters = new NavigationParameters();
                parameters.Add(ParameterNames.PDFViewer, PDFViewer);
                parameters.Add(ParameterNames.ViewModularContentViewModel, this);
                region.RequestNavigate(RegionNames.ThemesContentName, "ThemesContent", parameters);
            }
            ));
        }

        /// <summary>
        /// 进入全屏模式
        /// </summary>
        private void OpenFullWindow()
        {
            DialogParameters parameters = new DialogParameters();
            //因为全屏模式可能需要设置特定的页面模式,所以只传文件路径,新建一个PDFview对象
            parameters.Add(ParameterNames.FilePath, PDFViewer.Document.FilePath);
            parameters.Add(ParameterNames.PassWord, PDFViewer.Tag == null ? "" : PDFViewer.Tag.ToString());
            dialogs.ShowDialog(DialogNames.FullScreenDialog, parameters, e =>
            {
                if (e.Result == ButtonResult.Cancel)
                {
                    //TODO:弹窗提示打开全屏模式失败
                    AlertsMessage alertsMessage = new AlertsMessage();
                    alertsMessage.ShowDialog("", App.MainPageLoader.GetString("OperationFailWarning"), App.ServiceLoader.GetString("Text_ok"));
                    return;
                }
                else if (e.Result == ButtonResult.OK)
                {
                    IsFullScreen = false;
                    IsSingleView = true;
                }
            });
        }

        /// <summary>
        /// 旋转
        /// </summary>
        /// <param name="obj"></param>
        private void RotateEvent(object obj)
        {
            bool right = Convert.ToBoolean(obj);

            PDFViewer.RotatePage(PageRotate.Rotate90, right, PDFViewer.CurrentIndex);
            if (SplitScreenPDFViewer != null)
            {
                SplitScreenPDFViewer.RotatePage(PageRotate.Rotate90, right, SplitScreenPDFViewer.CurrentIndex);
            }
            PDFViewer.UndoManager.CanSave = true;

            events.GetEvent<ViewContentEvent>().Publish(new ViewContentEventArgs() { type = right ? EventType.RightRotate : EventType.LeftRotate, Unicode = unicode });

            //后续需要添加,缩略图旋转改变

            if (ViewContentViewModel.OpenBOTA == true)
            {
                UpdateTabItemAnnotation();
            }
        }

        private void UpdateTabItemAnnotation()
        {
            bool isTabItemAnnotation = IsBOTATabItemShow(out BOTAContentViewModel bOTAContentViewModel, out BOTAContent bOTAContent, "TabItemAnnotation");

            if (isTabItemAnnotation == true && bOTAContent.TabItemAnnotation.IsSelected == true)
            {
                AnnotationContentViewModel viewModel = GetAnnotationContentViewModel(bOTAContentViewModel, out AnnotationContent annotation);

                if (viewModel != null)
                {
                    if (viewModel.AnnotationListItems.Count > 0)
                    {
                        var list = viewModel.AnnotationListItems.Where(q => q.AnnotHandlerEventArgs is FreehandAnnotArgs).ToList();
                        if (list.Count() > 0)
                        {
                            for (int i = 0; i < list.Count(); i++)
                            {
                                var item = list[i];
                                viewModel.UpdateModifiedAnnot(item.PageIndex, item.AnnotIndex);
                            }
                        }
                    }
                }
            }
        }

        private AnnotationContentViewModel GetAnnotationContentViewModel(BOTAContentViewModel bOTAContentViewModel, out AnnotationContent annotation)
        {
            AnnotationContentViewModel viewModel = null;
            annotation = null;
            if (bOTAContentViewModel != null)
            {
                if (region.Regions.ContainsRegionWithName(bOTAContentViewModel.BOTAContentRegionName))
                {
                    var views = region.Regions[bOTAContentViewModel.BOTAContentRegionName].Views;
                    foreach (var item in views)
                    {
                        if (item is AnnotationContent annotation1)
                        {
                            annotation = annotation1;
                            viewModel = annotation1.DataContext as AnnotationContentViewModel;
                            break;
                        }
                    }
                }
            }
            return viewModel;
        }

        private bool IsBOTATabItemShow(out BOTAContentViewModel bOTAContentViewModel, out BOTAContent bOTAContent, string tabItemText)
        {
            bool isTabItem = false;
            bOTAContentViewModel = null;
            bOTAContent = null;
            if (region.Regions.ContainsRegionWithName(ViewContentViewModel.BOTARegionName))
            {
                var views = region.Regions[ViewContentViewModel.BOTARegionName].Views;
                var model = views.FirstOrDefault(q => q is BOTAContent);
                if (model is BOTAContent bOTAContent1)
                {
                    bOTAContent = bOTAContent1;
                    bOTAContentViewModel = bOTAContent.DataContext as BOTAContentViewModel;
                    if (bOTAContentViewModel.CurrentBar == tabItemText)
                    {
                        isTabItem = true;
                    }
                }
            }
            return isTabItem;
        }

        /// <summary>
        /// 分页符
        /// </summary>
        /// <param name="obj"></param>
        private void PagesBreakEvent(object obj)
        {
            if (IsPagesBreak)
            {
                PDFViewer.SetPageSpacing(8);
                IsPagesBreak = true;
            }
            else
            {
                PDFViewer.SetPageSpacing(0);
                IsPagesBreak = false;
            }
            SaveMode(IsPagesBreak);
        }

        /// <summary>
        /// 设置显示模式
        /// </summary>
        private void SetModeView()
        {
            if (PDFViewer != null)
            {
                SetUpModeView(PDFViewer);
            }
            //if (App.SplitScreenPDFViewer != null)
            //{
            //    SetUpModeView(App.SplitScreenPDFViewer);
            //    SaveMode(App.SplitScreenPDFViewer.ModeView);
            //}
            SaveMode(PDFViewer.ModeView);
        }

        private void SetUpModeView(CPDFViewer pDFViewer)
        {
            if (IsContinue)
            {
                if (IsSingleView)
                {
                    pDFViewer.ChangeViewMode(ViewMode.SingleContinuous);
                    //App.SplitScreenViewMode = ViewMode.SingleContinuous;
                }
                else if (IsTwoPageView)
                {
                    pDFViewer.ChangeViewMode(ViewMode.DoubleContinuous);
                    //App.SplitScreenViewMode = ViewMode.DoubleContinuous;
                }
                else
                {
                    pDFViewer.ChangeViewMode(ViewMode.BookContinuous);
                    //App.SplitScreenViewMode = ViewMode.BookContinuous;
                }
            }
            else
            {
                if (IsSingleView)
                {
                    pDFViewer.ChangeViewMode(ViewMode.Single);
                    //App.SplitScreenViewMode = ViewMode.Single;
                }
                else if (IsTwoPageView)
                {
                    pDFViewer.ChangeViewMode(ViewMode.Double);
                    //App.SplitScreenViewMode = ViewMode.Double;
                }
                else
                {
                    pDFViewer.ChangeViewMode(ViewMode.Book);
                    //App.SplitScreenViewMode = ViewMode.Book;
                }
            }
        }

        /// <summary>
        /// 连续滚动
        /// </summary>
        /// <param name="obj"></param>
        private void ContinueEvent(object obj)
        {
            SetModeView();
        }

        /// <summary>
        /// 保存模式到本地
        /// </summary>
        /// <param name="modeView"></param>
        private void SaveMode(object modeView)
        {
            OpenFileInfo fileInfo = SettingHelper.GetFileInfo(PDFViewer.Document.FilePath);
            if (fileInfo != null)
            {
                if (modeView is ComPDFKitViewer.SplitMode)
                {
                    fileInfo.LastSplitMode = PDFViewer.Mode;
                }
                else if (modeView is ViewMode)
                {
                    fileInfo.LastViewMode = PDFViewer.ModeView;
                }
                else if (modeView is bool)
                {
                    fileInfo.LastPageSpace = (bool)modeView;
                }
                SettingHelper.SetFileInfo(fileInfo);
            }
        }

        /// <summary>
        /// 分屏视图-单屏
        /// </summary>
        /// <param name="obj"></param>
        private void DisableEvent(object obj)
        {
            ViewContentViewModel.EnterSplitMode(EventAggregators.SplitMode.Single);
            OpenFileInfo.LastSplitMode = ComPDFKitViewer.SplitMode.None;
        }

        /// <summary>
        /// 分屏视图-垂直
        /// </summary>
        /// <param name="obj"></param>
        private void SplitScreenEvent(object obj)
        {
            if (obj is System.Windows.Controls.RadioButton radioButton)
            {
                IsContinue = true;
                IsPagesBreak = true;

                switch (radioButton.Tag.ToString())
                {
                    case "VerticalSplit":
                        ViewContentViewModel.EnterSplitMode(EventAggregators.SplitMode.Vertical);
                        OpenFileInfo.LastSplitMode = ComPDFKitViewer.SplitMode.Vertical;
                        break;

                    case "HorizontalSplit":
                        ViewContentViewModel.EnterSplitMode(EventAggregators.SplitMode.Horizontal);
                        OpenFileInfo.LastSplitMode = ComPDFKitViewer.SplitMode.Horizontal;
                        break;
                }
            }
        }

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

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
            if (BottomToolContentViewModel != null)
            {
                IsSingleView = BottomToolContentViewModel.IsSingleView;
                IsTwoPageView = BottomToolContentViewModel.IsDoubleView;
                IsBookModeView = BottomToolContentViewModel.IsBookMode;
                IsContinue = BottomToolContentViewModel.IsContinue;
            }
        }

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            CPDFViewer pdfview = navigationContext.Parameters[ParameterNames.PDFViewer] as CPDFViewer;
            BottomToolContentViewModel btnTool = navigationContext.Parameters["BottomToolContentViewModel"] as BottomToolContentViewModel;
            if (pdfview != null && btnTool != null)
            {
                BottomToolContentViewModel = btnTool;
                PDFViewer = pdfview;
                ViewContentViewModel = BottomToolContentViewModel.ViewContentViewModel;
                OpenFileInfo = BottomToolContentViewModel.OpenFileInfo;
            }
            else
            {
                return;
            }

            IsSingleView = BottomToolContentViewModel.IsSingleView;
            IsTwoPageView = BottomToolContentViewModel.IsDoubleView;
            IsBookModeView = BottomToolContentViewModel.IsBookMode;
            IsContinue = BottomToolContentViewModel.IsContinue;
            PDFViewer.InfoChanged -= PDFViewer_InfoChanged;
            PDFViewer.InfoChanged += PDFViewer_InfoChanged;
        }

        /// <summary>
        /// 和底部工具栏联动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PDFViewer_InfoChanged(object sender, KeyValuePair<string, object> e)
        {
            if (e.Key == "ViewMode")
            {
                GetModeView((ViewMode)e.Value);
            }
        }

        private void GetModeView(ViewMode mode)
        {
            if ((int)mode % 2 == 0)
            {
                if (!IsContinue)
                {
                    IsContinue = true;
                }
            }
            else
            {
                if (IsContinue)
                {
                    IsContinue = false;
                }
            }

            if ((int)mode <= 2)
            {
                if (!isSingleView)
                {
                    IsSingleView = true;
                }
            }
            else if ((int)mode <= 4)
            {
                if (!isTwoPageView)
                {
                    IsTwoPageView = true;
                }
            }
            else
            {
                if (!isBookModeView)
                {
                    IsBookModeView = true;
                }
            }
        }
    }
}