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;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Forms;
using DataTable = System.Data.DataTable;
using DialogResult = Prism.Services.Dialogs.DialogResult;
using Task = System.Threading.Tasks.Task;

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

        private CPDFDocument tempDocument;

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

        private int fileNamesIndex = 0;

        private IntPtr compressingIntpr = IntPtr.Zero;

        private CPDFDocument.GetPageIndexDelegate indexDelegate = null;

        HomePageCompressDialogModel homePageCompressDialogModel=new HomePageCompressDialogModel();

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

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

        private string setCompressGridIsEnabled = "True";
        public string SetCompressGridIsEnabled
        {
            get
            {
                return setCompressGridIsEnabled;
            }
            set
            {
                SetProperty(ref setCompressGridIsEnabled, 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 ADDPDFCommand { get; set; }

        public DelegateCommand RemovePDFFileCommand { get; set; }

        public DelegateCommand ADDPDFFilesCommand { get; set; }

        public DelegateCommand CompressCommand { get; set; }

        public DelegateCommand<string> RadioButtonCommand{ get; set; }
        #endregion

        public HomePageCompressDialogViewModel()
        {
            PDFDataTable.Columns.Add("FileName");
            PDFDataTable.Columns.Add("FileSize");
            PDFDataTable.Columns.Add("FileState");
            ADDPDFCommand = new DelegateCommand(addpicture);
            ADDPDFFilesCommand = new DelegateCommand(addpicturefiles);
            RemovePDFFileCommand = new DelegateCommand(removepdffile);
            CompressCommand = new DelegateCommand(compress);
            RadioButtonCommand = new DelegateCommand<string>(RadioButton);
        }
        #region 逻辑函数
        private void RadioButton(string sender) {
            if (sender != "") {

                switch (sender) {
                    case "LargeQualityRadioBtn":
                        homePageCompressDialogModel.CompressQuality = HomePageCompressDialogModel.EnumQualityLevel.StatusLarge;
                        break;
                    case "StandardQualityRadioBtn":
                        homePageCompressDialogModel.CompressQuality = HomePageCompressDialogModel.EnumQualityLevel.StatusStandard;
                        break;
                    case "LittleQualityRadioBtn":
                        homePageCompressDialogModel.CompressQuality = HomePageCompressDialogModel.EnumQualityLevel.StatusLittle;
                        break;
                    case "MicroQualityRadioBtn":
                        homePageCompressDialogModel.CompressQuality = HomePageCompressDialogModel.EnumQualityLevel.StatusMicro;
                        break;
                        default:
                        homePageCompressDialogModel.CompressQuality = HomePageCompressDialogModel.EnumQualityLevel.StatusDefault;
                        break;

                }
            }
        }

        private int GetIndex(int pageindex)
        {
            PDFDataTable.Rows[fileNamesIndex]["FileState"]="已经压缩"+pageindex.ToString()+"页";
            return 0;
        }

        private async void compress() {
            CompressGridIsEnabled = "False";
            //GC.KeepAlive(indexDelegate);
            fileNamesIndex = 0;
            foreach (var filename in fileNames)
            {
                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";
                indexDelegate += GetIndex;
                compressingIntpr = document.CompressFile_Init(((float)homePageCompressDialogModel.CompressQuality), indexDelegate);
                tempDocument = document;
                await Task.Run<bool>(() => { return document.CompressFile_Start(compressingIntpr, filename+"compress.pdf"); });
                PDFDataTable.Rows[fileNamesIndex]["FileState"] = "完成";
                fileNamesIndex++;
                document.Release();
            }
            CompressGridIsEnabled = "True";
            MessageBoxEx.Show("已完成");
            
        }
        #endregion

        #region 批量处理逻辑函数
        /// <summary>
        /// 添加PDF文件
        /// </summary>
        private void addpicture()
        {
            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);
                SetCompressGridIsEnabled = "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 addpicturefiles()
        {
            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("待确定");
                SetCompressGridIsEnabled = "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)
            {
                SetCompressGridIsEnabled = "False";
                AddFileVisibility = Visibility.Visible;
            }
            updateListview("待确定");
        }


        public void PDFFileCount()
        {
            if (fileNames.Count == 0)
            {
                SetCompressGridIsEnabled = "False";
                AddFileVisibility = Visibility.Visible;
            }
            else
            {
                SetCompressGridIsEnabled = "True";
                AddFileVisibility = Visibility.Collapsed;
            }
        }
        #endregion

        #region 构架行为
        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)
        {
            if(tempDocument!=null)
            tempDocument.CompressFile_Cancel(compressingIntpr);
        }
        #endregion
    }
}
