using ComPDFKit.PDFDocument;
using ComPDFKit_Conversion.Converter;
using Microsoft.Office.Interop.Word;
using PDF_Office.CustomControl;
using PDF_Office.Helper;
using PDF_Office.Model;
using PDF_Office.Model.Dialog.ConverterDialogs;
using PDF_Office.Model.Dialog.HomePageToolsDialogs.HomePageBatchProcessing;
using PDF_Office.Model.Dialog.HomePageToolsDialogs.HomePageBatchProcessing.HomePageConverter;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Forms;
using DataTable = System.Data.DataTable;

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

        public HomePageConverterCSVModel ConverterCSVModel = new HomePageConverterCSVModel();
        public HomePageConverterExcelModel ConverterExcelModel = new HomePageConverterExcelModel();
        public HomePageConverterHTMLModel ConverterHTMLModel = new HomePageConverterHTMLModel();
        public HomePageConverterImgModel ConverterImgModel = new HomePageConverterImgModel();
        public HomePageConverterPPTModel ConverterPPTModel = new HomePageConverterPPTModel();
        public HomePageConverterRTFModel ConverterRTFModel = new HomePageConverterRTFModel();
        public HomePageConverterTextModel ConverterTextModel = new HomePageConverterTextModel();
        public HomePageConverterWordModel ConverterWordModel = new HomePageConverterWordModel();

        private CPDFDocument tempDocument;

        public string PageNumber = "";

        public IRegionManager ConverterRegion;

        public int ConverterTypeIndex=0;

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

        private int fileNamesIndex = 0;

        public List<string> ConverterTypeFamily { set; get; } = new List<string>();

        private void SetImageTypeOrigin()
        {
            this.ConverterTypeFamily.Add("Word");
            this.ConverterTypeFamily.Add("Excel");
            this.ConverterTypeFamily.Add("PPT");
            this.ConverterTypeFamily.Add("RTF");
            this.ConverterTypeFamily.Add("HTML");
            this.ConverterTypeFamily.Add("Text");
            this.ConverterTypeFamily.Add("CSV");
            this.ConverterTypeFamily.Add("Img");
        }

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

        private string setConverterGridIsEnabled = "True";
        public string SetConverterGridIsEnabled
        {
            get
            {
                return setConverterGridIsEnabled;
            }
            set
            {
                SetProperty(ref setConverterGridIsEnabled, 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 string converterRegionName;
        public string ConverterRegionName
        {
            get
            {
                return converterRegionName;
            }
            set
            {
                SetProperty(ref converterRegionName, value);
            }
        }

        private Visibility converterVisible = Visibility.Collapsed;
        public Visibility ConverterVisible
        {
            get { return converterVisible; }
            set { SetProperty(ref converterVisible, 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 ConvertCommand { get; set; }

        public DelegateCommand ADDPDFFilesCommand { get; set; }
        #endregion

        public HomePageConverterDialogViewModel(IRegionManager converterRegion)
        {

            SetImageTypeOrigin();
            PDFDataTable.Columns.Add("FileName");
            PDFDataTable.Columns.Add("FileSize");
            PDFDataTable.Columns.Add("FileState");
            ADDPDFCommand = new DelegateCommand(addpicture);
            ADDPDFFilesCommand = new DelegateCommand(addpicturefiles);
            RemovePDFFileCommand = new DelegateCommand(removepdffile);
            ConvertCommand = new DelegateCommand(convert);
            ConverterRegion = converterRegion;
            ConverterRegionName=Guid.NewGuid().ToString();
        }
        #region 逻辑函数
        private void SetProgress(int pageIndex)
        {
            PDFDataTable.Rows[fileNamesIndex]["FileState"] = "已经转换" + pageIndex.ToString() + "页";
            pageIndex.ToString();
        }

        private async void convert()
        {

            bool result = false;
            OnProgress GetProgress = null;
            GetProgress += SetProgress;
            fileNamesIndex = 0;
            ConverterGridIsEnabled = "False";
            foreach (var filename in fileNames)
            {
                FileInfo fileinfo = new FileInfo(filename);
                string OutputPath = fileinfo.DirectoryName;
                char[] enumerationSeparator = new char[] { ',' };
                char[] rangeSeparator = new char[] { '-' };
                List<int> PageIndexLists=new List<int>();
                CPDFDocument document = CPDFDocument.InitWithFilePath(filename);
                if (document == null)
                {
                    PDFDataTable.Rows[fileNamesIndex]["FileState"] = "文件出错";
                    continue;
                }
                if (!CommonHelper.GetPagesInRange(ref PageIndexLists, "1-" + document.PageCount.ToString(),document.PageCount, enumerationSeparator, rangeSeparator))
                { //TODO
                    Trace.WriteLine("输入不对");
                    MessageBoxEx.Show("输入不对");
                    return;
                }
                switch (ConverterTypeIndex)
                {
                    case 0:
                        if (ConverterWordModel != null)
                        {
                            PageNumber = ConverterWordModel.PageIndexLists.Count().ToString();
                            result = await ConverterHelper.WordConvert(filename, OutputPath, GetProgress, PageIndexLists, ConverterWordModel.Pawssword);
                        }
                        break;

                    case 1:
                        if (ConverterExcelModel != null)
                        {
                            PageNumber = ConverterExcelModel.PageIndexLists.Count().ToString();
                            result = await ConverterHelper.ExcelConvert(filename, OutputPath, GetProgress, PageIndexLists, ConverterExcelModel.Pawssword, ConverterExcelModel.excelOption);
                        }
                        break;
                    case 2:

                        if (ConverterPPTModel != null)
                        {
                            PageNumber = ConverterPPTModel.PageIndexLists.Count().ToString();
                            result = await ConverterHelper.PPTConvert(filename, OutputPath, GetProgress, PageIndexLists, ConverterPPTModel.Pawssword);
                        }
                        break;
                    case 3:

                        if (ConverterRTFModel != null)
                        {
                            PageNumber = ConverterRTFModel.PageIndexLists.Count().ToString();
                        }
                        break;
                    case 4:

                        if (ConverterHTMLModel != null)
                        {
                            PageNumber = ConverterHTMLModel.PageIndexLists.Count().ToString();
                        }
                        break;
                    case 5:

                        if (ConverterTextModel != null)
                        {
                            PageNumber = ConverterTextModel.PageIndexLists.Count().ToString();
                            result = await ConverterHelper.TxtConvert(filename, OutputPath, GetProgress, PageIndexLists, ConverterTextModel.Pawssword);
                        }
                        break;
                    case 6:
                        if (ConverterCSVModel != null)
                        {
                            PageNumber = ConverterCSVModel.PageIndexLists.Count().ToString();
                            result = await ConverterHelper.CSVConvert(filename, OutputPath, GetProgress, ConverterCSVModel.PageIndexLists, ConverterCSVModel.Pawssword);
                        }
                        break;
                    case 7:

                        if (ConverterImgModel != null)
                        {
                            PageNumber = ConverterImgModel.PageIndexLists.Count().ToString();
                            result = await ConverterHelper.ImgConvert(filename, OutputPath, GetProgress, PageIndexLists, ConverterImgModel.Pawssword, ConverterImgModel.Type);
                        }
                        break;
                    default:
                        break;
                }
                document.Release();
                PDFDataTable.Rows[fileNamesIndex]["FileState"] = "完成";
                fileNamesIndex++;
            }
            ConverterGridIsEnabled = "True";
        }
        #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);
                SetConverterGridIsEnabled = "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("待确定");
                SetConverterGridIsEnabled = "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)
            {
                SetConverterGridIsEnabled = "False";
                AddFileVisibility = Visibility.Visible;
            }
            updateListview("待确定");
        }


        public void PDFFileCount()
        {
            if (fileNames.Count == 0)
            {
                SetConverterGridIsEnabled = "False";
                AddFileVisibility = Visibility.Visible;
            }
            else
            {
                SetConverterGridIsEnabled = "True";
                AddFileVisibility = Visibility.Collapsed;
            }
        }
        public void ChangeConverter(int index)
        {
            ConverterTypeIndex=index;
            NavigationParameters param = new NavigationParameters();
            param.Add(ParameterNames.ViewContentViewModel, this);
            if (index == 0 || index == 1 || index == 6 || index == 7)
            {
                ConverterVisible = Visibility.Collapsed;
                ConverterRegion.RequestNavigate(ConverterRegionName, HomePageConverterDialogModel.GetConverter[index], param);
                ConverterVisible = Visibility.Visible;
            }
            else { ConverterVisible = 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("待确定");
                ChangeConverter(0);
            }
        }
       

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

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
            ConverterHelper.Clear();
        }
        #endregion
    }
}
