using ComPDFKit.PDFDocument;
using PDF_Office.CustomControl;
using PDF_Office.Model;
using PDF_Office.Model.Dialog.HomePageToolsDialogs.HomePageBatchProcessing;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Forms;
using DialogResult = Prism.Services.Dialogs.DialogResult;

namespace PDF_Office.ViewModels.Dialog.HomePageToolsDialogs.HomePageBatchProcessing
{
    public class HomePageSetPasswordDialogViewModel : BindableBase, INavigationAware
    {
        #region 参数和属性
        private List<string> fileNames;

        private int fileNamesIndex = 0;

        private HomePageSetPasswordDialogModel setPasswordDialogModel = new HomePageSetPasswordDialogModel();

        public List<int> fileNamesView = new List<int>();

        private bool _canOpen;
        public bool CanOpen
        {
            get { return _canOpen; }
            set
            {
                _canOpen = value;
                RaisePropertyChanged("isChecked");
            }
        }

        private bool _canEdit;
        public bool CanEdit
        {
            get { return _canEdit; }
            set
            {
                _canEdit = value;
                RaisePropertyChanged("isChecked");
            }
        }

        private string _changeMod = "0";
        ///<value>
        ///"0"为ChangeMod.None;
        ///"1"为ChangeMod.ChangePage;
        ///"2"为ChangeMod.FormAndSignature;
        ///"3"为ChangeMod.AnnotAndFormAndSignature;
        ///"4"为ChangeMod.ExceptAbstrat;
        ///</value>
        public string ChangeMod
        {
            get { return _changeMod; }
            set
            {
                _changeMod = value;
            }
        }

        private string _printMod = "0";
        ///<value>
        ///"0"为PrintMod.None;
        ///"1"为PrintMod.LowDpi;
        ///"2"为PrintMod.HighDpi;
        ///</value>
        public string PrintMod
        {
            get { return _printMod; }
            set
            {
                _printMod = value;
            }
        }

        private string safetyGridIsEnabled = "True";
        public string SafetyGridIsEnabled
        {
            get
            {
                return safetyGridIsEnabled;
            }
            set
            {
                SetProperty(ref safetyGridIsEnabled, value);
            }
        }

        private string setSafetyGridIsEnabled = "True";
        public string SetSafetyGridIsEnabled
        {
            get
            {
                return setSafetyGridIsEnabled;
            }
            set
            {
                SetProperty(ref setSafetyGridIsEnabled, value);
            }
        }

        private string _isEnableConfirm = "False";
        public string IsEnabledConfirm
        {
            get { return _isEnableConfirm; }
            set
            {
                SetProperty(ref _isEnableConfirm, value);
            }
        }

        private DataTable pdfDataTable = new DataTable();
        public DataTable PDFDataTable
        {
            get { return pdfDataTable; }
            set
            {
                SetProperty(ref pdfDataTable, value);
            }
        }

        private string removeIsEnable = "False";
        public string RemoveIsEnable
        {
            get { return removeIsEnable; }
            set
            {
                SetProperty(ref removeIsEnable, value);
            }
        }

        private string selectFileName = "False";
        public string SelectFileName
        {
            get { return selectFileName; }
            set
            {
                SetProperty(ref selectFileName, value);
            }
        }

        private Visibility addFileVisibility = Visibility.Hidden;
        public Visibility AddFileVisibility
        {
            get { return addFileVisibility; }
            set
            {
                SetProperty(ref addFileVisibility, value);
                RaisePropertyChanged();

            }
        }
        #endregion

        #region 委托声明

        public DelegateCommand DelegateSetOpenCommand { get; set; }

        public DelegateCommand DelegateSetEditCommand { get; set; }

        public DelegateCommand DelegateCanOpenTextChangedCommand { get; set; }

        public DelegateCommand DelegateCanEditTextChangedCommand { get; set; }

        public DelegateCommand DelegateConfirmEncryptCommand { get; set; }

        public DelegateCommand DelegateCancelEncryptCommand { get; set; }

        public DelegateCommand ADDPDFCommand { get; set; }

        public DelegateCommand RemovePDFFileCommand { get; set; }

        public DelegateCommand ADDPDFFilesCommand { get; set; }
        #endregion

        public HomePageSetPasswordDialogViewModel()
        {
            PDFDataTable.Columns.Add("FileName");
            PDFDataTable.Columns.Add("FileSize");
            PDFDataTable.Columns.Add("FileState");
            HomePageSetPasswordDialogModel.PasswordForOpen = "";
            HomePageSetPasswordDialogModel.PasswordForEdit = "";
            DelegateConfirmEncryptCommand = new DelegateCommand(ConfirmEncrypt);
            DelegateSetOpenCommand = new DelegateCommand(SetCanOpen);
            DelegateSetEditCommand = new DelegateCommand(SetCanEdit);
            DelegateCanOpenTextChangedCommand = new DelegateCommand(CanOpenTextChanged);
            DelegateCanEditTextChangedCommand = new DelegateCommand(CanEditTextChanged);
            ADDPDFCommand = new DelegateCommand(addpdf);
            ADDPDFFilesCommand = new DelegateCommand(addpdffiles);
            RemovePDFFileCommand = new DelegateCommand(removepdffile);
        }

        #region 检查和初始化
        private void CheckCanConfirmEncrypt()
        {
            if (setPasswordDialogModel.CanOpen)
            {
                if (HomePageSetPasswordDialogModel.PasswordForOpen.Length > 0)
                {
                    IsEnabledConfirm = "True";
                    return;
                }
            }
            if (setPasswordDialogModel.CanEdit)
            {
                if (HomePageSetPasswordDialogModel.PasswordForEdit.Length > 0)
                {
                    IsEnabledConfirm = "True";
                    return;
                }
            }
            IsEnabledConfirm = "False";
        }

        private void InitPermissionsDictionary(ref Dictionary<string, HomePageSetPasswordDialogModel.PrintMod> GetPrintMod, ref Dictionary<string, HomePageSetPasswordDialogModel.ChangeMod> GetChangeMod)
        {
            GetPrintMod.Add("0", HomePageSetPasswordDialogModel.PrintMod.None);
            GetPrintMod.Add("1", HomePageSetPasswordDialogModel.PrintMod.LowDpi);
            GetPrintMod.Add("2", HomePageSetPasswordDialogModel.PrintMod.HighDpi);

            GetChangeMod.Add("0", HomePageSetPasswordDialogModel.ChangeMod.None);
            GetChangeMod.Add("1", HomePageSetPasswordDialogModel.ChangeMod.ChangePage);
            GetChangeMod.Add("2", HomePageSetPasswordDialogModel.ChangeMod.FormAndSignature);
            GetChangeMod.Add("3", HomePageSetPasswordDialogModel.ChangeMod.AnnotAndFormAndSignature);
            GetChangeMod.Add("4", HomePageSetPasswordDialogModel.ChangeMod.ExceptAbstrat);
        }
        #endregion
        #region 逻辑函数
        public void SetCanOpen()
        {
            setPasswordDialogModel.CanOpen = CanOpen;
            CheckCanConfirmEncrypt();
        }

        public void SetCanEdit()
        {
            setPasswordDialogModel.CanEdit = CanEdit;
            CheckCanConfirmEncrypt();
        }

        public void CanOpenTextChanged()
        {
            CheckCanConfirmEncrypt();
        }

        public void CanEditTextChanged()
        {
            CheckCanConfirmEncrypt();
        }

        public void ConfirmEncrypt()
        {
            SafetyGridIsEnabled = "False";
            string openPassword = "";
            string editPassword = "";
            CPDFPermissionsInfo permissionsInfo = new CPDFPermissionsInfo();
            if (setPasswordDialogModel.CanOpen)
            {
                if (!string.IsNullOrEmpty(HomePageSetPasswordDialogModel.PasswordForOpen))
                {
                    openPassword = HomePageSetPasswordDialogModel.PasswordForOpen;
                }
            }
            if (setPasswordDialogModel.CanEdit)
            {
                if (!string.IsNullOrEmpty(HomePageSetPasswordDialogModel.PasswordForEdit))
                {
                    editPassword = HomePageSetPasswordDialogModel.PasswordForEdit;
                    Dictionary<string, HomePageSetPasswordDialogModel.PrintMod> GetPrintMod = new Dictionary<string, HomePageSetPasswordDialogModel.PrintMod>();
                    Dictionary<string, HomePageSetPasswordDialogModel.ChangeMod> GetChangeMod = new Dictionary<string, HomePageSetPasswordDialogModel.ChangeMod>(); ;
                    InitPermissionsDictionary(ref GetPrintMod, ref GetChangeMod);
                    permissionsInfo = setPasswordDialogModel.CreatePermissionsInfo(GetPrintMod[PrintMod], GetChangeMod[ChangeMod]);
                }
            }
            fileNamesIndex = 0;
            foreach (var filename in fileNames)
            {
                PDFDataTable.Rows[fileNamesIndex]["FileState"] = "待完成";
                CPDFDocument document = CPDFDocument.InitWithFilePath(filename);
                if (document == null)
                {
                    PDFDataTable.Rows[fileNamesIndex]["FileState"] = "文件出错";
                    continue;
                }
                FileInfo fileinfo = new FileInfo(filename);
                string file_size = (((float)fileinfo.Length) / 1024).ToString() + " K";
                if (document == null)
                {
                    return;
                }
                document.Encrypt(openPassword, editPassword, permissionsInfo);
                document.WriteToFilePath(filename + "SetPassword");

                PDFDataTable.Rows[fileNamesIndex]["FileState"] = "完成";
                fileNamesIndex++;
                document.Release();
            }
            SafetyGridIsEnabled = "True";
            MessageBoxEx.Show("已完成");
        }
        #endregion

        #region 批量处理逻辑函数
        /// <summary>
        /// 添加PDF文件
        /// </summary>
        private void addpdf()
        {
            System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog();
            dlg.Multiselect = true;
            dlg.Filter = "PDF|*.pdf;*.PDF;";
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                fileNames.AddRange(dlg.FileNames.ToList());
                RemoveExcess(ref fileNames);
                SetSafetyGridIsEnabled = "True";
                AddFileVisibility = Visibility.Collapsed;
                updateListview("待确定");
            }
        }

        /// <summary>
        /// 删除重复的文件
        /// </summary>
        public void RemoveExcess(ref List<string> Filenames)
        {
            List<string> filenames = new List<string>();
            foreach (var fileName in Filenames)
            {
                if (!filenames.Contains(fileName))
                {
                    filenames.Add(fileName);
                }
            }
            Filenames.Clear();
            Filenames = filenames;
        }

        /// <summary>
        /// 添加PDF文件夹
        /// </summary>
        private void addpdffiles()
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择文件路径";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {

                string foldPath = dialog.SelectedPath;
                var apps = System.IO.Directory.GetFiles(foldPath);
                foreach (string app in apps)
                {
                    var fi = new FileInfo(app);
                    if (fi.Extension == ".pdf" || fi.Extension == ".PDF")
                    {
                        fileNames.Add(app);
                    }
                }
                RemoveExcess(ref fileNames);
                updateListview("待确定");
                SetSafetyGridIsEnabled = "True";
                AddFileVisibility = Visibility.Collapsed;
            }
        }

        /// <summary>
        /// 更新listview显示
        /// state 状态显示字符串
        /// </summary>
        public void updateListview(string state)
        {
            DataTable pdfdatatable = new DataTable();
            pdfdatatable.Columns.Add("FileName");
            pdfdatatable.Columns.Add("FileSize");
            pdfdatatable.Columns.Add("FileState");
            foreach (var fileName in fileNames)
            {
                string file_all = fileName;
                FileInfo f = new FileInfo(file_all);
                string file_size = (((float)f.Length) / 1024).ToString() + " K";
                pdfdatatable.Rows.Add(f.Name, file_size, state);
            }
            PDFDataTable = pdfdatatable;
            HomePageBatchProcessingDialogModel.FilePaths = fileNames;

        }

        

        /// <summary>
        /// 逆序int类型集合
        /// </summary>
        public void Reverseorder(ref List<int> Numbers)
        {
            Numbers = Numbers.OrderBy(a => a).ToList();
            Numbers.Reverse();
        }

        /// <summary>
        /// 打开文件PDF
        /// </summary>
        public void openfiledialog()
        {

            foreach (int filenamesview in fileNamesView)
            {
                System.Diagnostics.Process.Start(fileNames[filenamesview]);
            }
        }

        /// <summary>
        /// 删除文件PDF
        /// </summary>
        public void removepdffile()
        {
            Reverseorder(ref fileNamesView);
            foreach (int filenamesview in fileNamesView)
            {
                //Trace.WriteLine(filenamesview);
                fileNames.Remove(fileNames[filenamesview]);
            }
            if (fileNames.Count < 1)
            {
                SetSafetyGridIsEnabled = "False";
                AddFileVisibility = Visibility.Visible;
            }
            updateListview("待确定");
        }

        public void PDFFileCount()
        {
            if (fileNames.Count == 0)
            {
                SetSafetyGridIsEnabled = "False";
                AddFileVisibility = Visibility.Visible;
            }
            else
            {
                SetSafetyGridIsEnabled = "True";
                AddFileVisibility = Visibility.Collapsed;
            }
        }
        #endregion
        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            List<string> filepath = new List<string>();
            navigationContext.Parameters.TryGetValue<List<string>>(ParameterNames.FilePath, out filepath);
            if (filepath != null)
            {

                fileNames = filepath;
                PDFFileCount();
                updateListview("待确定");
            }
        }

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

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
        }
    }
}
