using Microsoft.Win32;
using PDF_Office.CustomControl;
using PDF_Office.Helper;
using PDF_Office.Properties;
using PDF_Office.Views;
using PDFSettings.Settings;
using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using winform = System.Windows.Forms;

namespace PDF_Office.ViewModels.HomePanel.RecentFiles
{
    public class RecentFilesContentViewModel: BindableBase
    {
        #region 属性

        private ObservableCollection<OpenFileInfo> _recentFilesGroup = new ObservableCollection<OpenFileInfo>();
        /// <summary>
        /// 最近列表:文件集合
        /// </summary>
        public ObservableCollection<OpenFileInfo> RecentFilesGroup
        {
            get { return _recentFilesGroup; }
            set
            {
                SetProperty(ref _recentFilesGroup, value);
            }
        }

        private bool _isEmpty = false;
        /// <summary>
        /// 最近列表是否为空
        /// </summary>
        public bool IsEmpty
        {
            get { return _isEmpty; }
            set
            {
                SetProperty(ref _isEmpty, value);
            }
        }


        private bool _isListMode = false;
        /// <summary>
        /// 是否为列表模式
        /// </summary>
        public bool IsListMode
        {
            get { return _isListMode; }
            set
            {
                SetProperty(ref _isListMode, value);
            }
        }

        #endregion

        public DelegateCommand<object> RemoveFileItemCommand { get; set; }
        public DelegateCommand<object> RemoveFilesFromContainerCommand { get; set; }
        public DelegateCommand<object> OpenRecentFilesCommand { get; set; }
        public DelegateCommand<object> OpenFilesCommand { get; set; }

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

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

        public event EventHandler<bool> RecentFilesSelectionHandler;
        public RecentFilesContentViewModel()
        {
            InitVariables();
            InitCommands();
            InitEvents();
        }

        #region 初始化
        private void InitVariables()
        {
            RecentFilesGroup = new ObservableCollection<OpenFileInfo>(Settings.Default.RecentOpenFiles);
            RecentFileGroupIsEmpty();

            int mode = Settings.Default.AppProperties.RecentFileListMode;
            if (mode == 0)
                IsListMode = false;
            else
                IsListMode = true;
        }

        private void InitCommands()
        {
            RemoveFilesFromContainerCommand = new DelegateCommand<object>(RemoveFilesFromContainer_Command);
            RemoveFileItemCommand = new DelegateCommand<object>(RemoveFileItem_Command);
            OpenRecentFilesCommand = new DelegateCommand<object>(OpenRecentFiles_Command);
            ListModeCheckedCommand = new DelegateCommand<object>(ListMode_Checked);
            OpenFilesCommand = new DelegateCommand<object>(OpenFiles_Command);
            ExplorerFileCommand = new DelegateCommand<object>(ExplorerFile_Command);
        }

        private void InitEvents()
        {
            RecentFilesGroup.CollectionChanged -= RecentFilesGroup_CollectionChanged;
            RecentFilesGroup.CollectionChanged += RecentFilesGroup_CollectionChanged;
        }

        private void RecentFilesGroup_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            RecentFileGroupIsEmpty();
        }

        private void RecentFileGroupIsEmpty()
        {
            if (RecentFilesGroup.Count == 0)
            {
                IsEmpty = true;
            }
            else
            {
                IsEmpty = false;
            }
        }

        #endregion

        /// <summary>
        /// 最近列表:文件列表模式选中事件
        /// </summary>
        /// <param name="obj"></param>
        private void ListMode_Checked(object obj)
        {
            if (obj is string)
            {
                var tag = obj as string;
                if (tag == "ListMode")
                {
                    IsListMode = true;
                    Settings.Default.AppProperties.RecentFileListMode = 1;
                }
                else
                {
                    IsListMode = false;
                    Settings.Default.AppProperties.RecentFileListMode = 0;
                }
                Settings.Default.Save();
                RecentFilesSelectionHandler?.Invoke(null, IsListMode);
            }
        }

        /// <summary>
        /// 移除文件记录:单个文件
        /// </summary>
        /// <param name="obj"></param>
        private void RemoveFileItem_Command(object obj)
        {
            var openFileInfo = obj as OpenFileInfo;
            if (openFileInfo != null)
            {
                SettingHelper.RemoveRecentOpenFile(openFileInfo.FilePath);
                RecentFilesGroup.Remove(openFileInfo);
            }
        }

        /// <summary>
        /// 删除按钮触发事件:选中的文件
        /// </summary>
        /// <param name="obj">选中的文档</param>
        private void RemoveFilesFromContainer_Command(object obj)
        {
            System.Collections.IList items = (System.Collections.IList)obj;
            if (items == null || items.Cast<OpenFileInfo>() == null)
                return;

            var collection = items.Cast<OpenFileInfo>();
            var openFileInfo = collection.ToList();
            if(openFileInfo != null)
            {
                string msg = "";
                int SelectedItemsType = 0;

                if (openFileInfo.Count == RecentFilesGroup.Count || openFileInfo.Count == 0)
                {
                    if(openFileInfo.Count == 1 && RecentFilesGroup.Count == 1)
                        msg = "ClearFile";
                    else
                        msg = "AllClearFiles";

                    SelectedItemsType = 0;
                }
                else if(openFileInfo.Count == 1)
                {
                    msg = "ClearFile";
                    SelectedItemsType = 1;
                }
                else
                {
                    msg = "ClearSelectedFiles";
                    SelectedItemsType = 2;
                }

                winform.DialogResult result = MessageBoxEx.Show(msg, "", winform.MessageBoxButtons.OKCancel, winform.MessageBoxIcon.Question);
                if (result == winform.DialogResult.OK)
                {
                    RemoveRecentFilesFrom(SelectedItemsType, openFileInfo);
                }


            }
        }

        /// <summary>
        ///  删除最近文件的操作
        /// </summary>
        /// <param name="selectedItemsType">0:全部文件;1:一个文件;2:多个文件</param>
        /// <param name="openFileInfo">选中的文件</param>
        private void RemoveRecentFilesFrom(int selectedItemsType, List<OpenFileInfo> openFileInfo)
        {
            if (selectedItemsType == 0)
            {
                SettingHelper.RemoveAllRecentOpenFiles();
                   RecentFilesGroup.Clear();
            }
            else if (selectedItemsType == 1)
            {
                var file = openFileInfo[0] as OpenFileInfo;
                SettingHelper.RemoveRecentOpenFile(file.FilePath);
                  RecentFilesGroup.Remove(file);
            }
            else
            {
                foreach (var item in openFileInfo)
                {
                    SettingHelper.RemoveRecentOpenFile(item.FilePath);
                     RecentFilesGroup.Remove(item);
                }
            }
        }

        /// <summary>
        /// 空状态时,点击文件浏览器弹窗,打开文件
        /// </summary>
        private void OpenFiles_Command(object obj)
        {
            var dlg = new OpenFileDialog();
            dlg.Multiselect = true;
            dlg.Filter = Properties.Resources.OpenDialogFilter;

            if (dlg.ShowDialog() == true)
            {
                LoadPdfViewer(dlg.FileNames);
            }
        }

        /// <summary>
        /// 打开文件路径
        /// </summary>
        private void ExplorerFile_Command(object obj)
        {
            try
            {
                var fileInfo = obj as OpenFileInfo;
                if (fileInfo != null)
                {
                    if (string.IsNullOrEmpty(fileInfo.FilePath) == false)
                    {
                        if (!File.Exists(fileInfo.FilePath))
                        {
                            MessageBoxEx.Show("文件不存在");
                            SettingHelper.RemoveRecentOpenFile(fileInfo.FilePath);
                            RecentFilesGroup.Remove(fileInfo);
                        }
                        else
                        {
                            Process.Start("explorer", "/select,\"" + fileInfo.FilePath + "\"");
                        }
                    }
                }
            }
            catch (Exception ex)
            {

            }
            
        }

        /// <summary>
        /// 从最近列表里,打开文档
        /// </summary>
        /// <param name="obj"></param>
        private void OpenRecentFiles_Command(object obj)
        {
            var fileInfo = obj as OpenFileInfo;
            if (fileInfo != null)
            {
                if (File.Exists(fileInfo.FilePath))
                {
                    string[] filePath = new string[1];
                    filePath[0] = fileInfo.FilePath;
                    LoadPdfViewer(filePath);
                }
                else
                {
                    SettingHelper.RemoveRecentOpenFile(fileInfo.FilePath);
                    RecentFilesGroup.Remove(fileInfo);
                }

            }

        }

        /// <summary>
        /// 打开文档
        /// </summary>
        /// <param name="filePaths"></param>
        public void LoadPdfViewer(string[] filePaths)
        {
            var content = App.mainWindowViewModel.SelectedItem.DataContext as MainContentViewModel;
            if (filePaths.Count() == 1)
            {
                if (App.OpenedFileList.Contains(filePaths[0]))
                {
                    App.mainWindowViewModel.SelectItem(filePaths[0]);
                }
                else
                {
                    content.OpenFile(filePaths[0]);
                }
                ToolMethod.SetFileThumbImg(filePaths[0]);
            }
            else
            {
                var fileList = filePaths.ToList().Where(x => !App.OpenedFileList.Exists(y => y == x)).ToList();
                if (fileList.Count <= 0)
                    return;

                content.OpenFile(filePaths[0]);
                for (int i = 1; i < fileList.Count(); i++)
                {
                    if (!App.OpenedFileList.Contains(fileList[i]))
                    {
                        App.mainWindowViewModel.AddTabItem(fileList[i]);
                    }
                    ToolMethod.SetFileThumbImg(fileList[i]);
                }
            }

            Settings.Default.Save();
        }

    }
}