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

namespace PDF_Office.ViewModels.Dialog.HomePageToolsDialogs
{
    public class HomePagePictureToPDFDialogViewModel : BindableBase, IDialogAware
    {
        #region 参数和属性
        private List<string> fileNames;
        
        public List<int> fileNamesView = new List<int>();
        public HomePagePictureToPDFDialogModel pictureToPDFModel=new HomePagePictureToPDFDialogModel();
        private DataTable imagesDataTable = new DataTable();
        public DataTable ImagesDataTable
        {
            get { return imagesDataTable; }
            set
            {
                SetProperty(ref imagesDataTable, 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 ToPDFCommand { get; set; }

        public DelegateCommand ADDPictureCommand { get; set; }

        public DelegateCommand ADDPictureFilesCommand { get; set; }

        public DelegateCommand RemovePictureFileCommand { get; set; }

        public DelegateCommand SelectFileCommand { get; set; }

        #endregion
        public HomePagePictureToPDFDialogViewModel()
        {
            ToPDFCommand = new DelegateCommand(topdf);
            ADDPictureCommand = new DelegateCommand(addpicture);
            ADDPictureFilesCommand = new DelegateCommand(addpicturefiles);
            RemovePictureFileCommand = new DelegateCommand(removepicturefile);
            SelectFileCommand = new DelegateCommand(selectFile);

        }
        #region 逻辑函数
        private void topdf() {
            updateListview("正在转换");
            DataTable imagesdatayable = new DataTable();
            imagesdatayable.Columns.Add("FileName");
            imagesdatayable.Columns.Add("FileSize");
            imagesdatayable.Columns.Add("FileState");
            if (pictureToPDFModel.Mode == HomePagePictureToPDFDialogModel.ToPDFFileMode.NewFiles)
            {
                foreach (var filename in fileNames)
                {
                    Image img = Image.FromFile(filename);
                    CPDFDocument topdfdoc = CPDFDocument.CreateDocument();
                    FileInfo fileinfo = new FileInfo(filename);
                    JpegInsertPage(ref topdfdoc, filename, fileinfo,img.Width,img.Height);
                    Trace.WriteLine("Path.GetTempPath():" + Path.GetTempPath());
                    topdfdoc.WriteToFilePath(savefilename(filename));
                    topdfdoc.Release();
                    string file_size = (((float)fileinfo.Length) / 1024).ToString() + " K";
                    imagesdatayable.Rows.Add(fileinfo.Name, file_size, "确认");
                    ImagesDataTable = imagesdatayable;
                }
                System.Diagnostics.Process.Start("Explorer", "/select," + savefilename(fileNames[0]));
            }
            if (pictureToPDFModel.Mode == HomePagePictureToPDFDialogModel.ToPDFFileMode.OneNewFile)
            {
                CPDFDocument topdfdoc = CPDFDocument.CreateDocument();
                int pageindex = 0;
                foreach (var filename in fileNames) {
                    Image img = Image.FromFile(filename);
                    FileInfo fileinfo = new FileInfo(filename);
                    JpegInsertPage(ref topdfdoc, filename, fileinfo,img.Width, img.Height);
                    pageindex++;
                    string file_size = (((float)fileinfo.Length) / 1024).ToString() + " K";
                    imagesdatayable.Rows.Add(fileinfo.Name, file_size, "确认");
                    ImagesDataTable = imagesdatayable;
                }
                System.Diagnostics.Process.Start("Explorer", "/select," + savefilename(fileNames[0]));
                topdfdoc.WriteToFilePath(savefilename(fileNames[0]));
                topdfdoc.Release();
            }
            if (pictureToPDFModel.Mode == HomePagePictureToPDFDialogModel.ToPDFFileMode.SelectFileName)
            {
                CPDFDocument topdfdoc =CPDFDocument.InitWithFilePath(pictureToPDFModel.FilePath);
                if (topdfdoc == null)
                {
                    Trace.WriteLine("Document==null");
                    //TODO
                    MessageBoxEx.Show("文档为空");
                    return;
                }
                if (topdfdoc.IsEncrypted)
                {
                    Trace.WriteLine("youmima");
                    MessageBoxEx.Show("文档加密");
                    //TODO
                    return;
                }
                int pageindex = topdfdoc.PageCount;
                foreach (var filename in fileNames)
                {
                    Image img = Image.FromFile(filename);
                    FileInfo fileinfo = new FileInfo(filename);
                    JpegInsertPage(ref topdfdoc, filename, fileinfo, img.Width, img.Height, pageindex);
                    pageindex++;
                    string file_size = (((float)fileinfo.Length) / 1024).ToString() + " K";
                    imagesdatayable.Rows.Add(fileinfo.Name, file_size, "确认");
                    ImagesDataTable = imagesdatayable;
                }
                topdfdoc.WriteToLoadedPath();
                System.Diagnostics.Process.Start("Explorer", "/select," + topdfdoc.FilePath);
                topdfdoc.Release();
            }
            RequestClose.Invoke(new DialogResult(ButtonResult.OK));
        }

        /// <summary>
        /// 设置保存后的文件名
        /// </summary>
        public string savefilename(string filename)
        {
            FileInfo file = new FileInfo(filename);
            return filename.Replace(file.Name, "") +pictureToPDFModel.FrontFileNameLabel+file.Name+pictureToPDFModel.RearFileNameLabel+".pdf";
        }

        /// <summary>
        /// 选择PDF文件
        /// </summary>
        private void selectFile()
        {
            System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog();
            dlg.Multiselect = false;
            dlg.Filter = "PDF|*.pdf;*.PDF;";
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                SelectFileName=dlg.FileName;
                pictureToPDFModel.FilePath = dlg.FileName;
            }
        }

        /// <summary>
        /// 添加图片文件
        /// </summary>
        private void addpicture()
        {
            System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog();
            dlg.Multiselect = true;
            dlg.Filter = "Picture|*.png;*.PNG;*.jpg;*.JPG;*.bmp;*.gif;*tiff;";
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                fileNames.AddRange(dlg.FileNames.ToList());
                RemoveExcess(ref fileNames);
                AddFileVisibility = Visibility.Collapsed;
                updateListview("待确定");
            }
        }

        /// <summary>
        /// 添加图片文件夹
        /// </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 == ".png" || fi.Extension == ".jpg" || fi.Extension == ".jpeg" || fi.Extension ==".bmp"|| fi.Extension == ".gif"|| fi.Extension == ".tiff")
                    {
                        fileNames.Add(app);
                    }
                }
                RemoveExcess(ref fileNames);
                updateListview("待确定");
                AddFileVisibility = Visibility.Collapsed;
            }
        }

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

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

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

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

        /// <summary>
        /// 更新listview显示
        /// state 状态显示字符串
        /// </summary>
        public void updateListview( string state) {
            DataTable imagesdatayable = new DataTable();
            imagesdatayable.Columns.Add("FileName");
            imagesdatayable.Columns.Add("FileSize");
            imagesdatayable.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";
                imagesdatayable.Rows.Add(f.Name, file_size, state);
            }
            ImagesDataTable = imagesdatayable;

        }

        /// <summary>
        /// 图片转PNG
        /// picturefile 图片文件名
        /// filePath 保存路径
        /// </summary>
        public bool SavePng(string picturefile, string filePath)
        {
            Image img = Image.FromFile(picturefile);
            try
            {
                using (var bmp = new Bitmap(img.Width, img.Height))
                {
                    bmp.SetResolution(img.HorizontalResolution, img.VerticalResolution);

                    using (var g = Graphics.FromImage(bmp))
                    {
                        g.Clear(Color.White);
                        g.DrawImageUnscaled(img, 0, 0);
                    }
                    bmp.Save(filePath, System.Drawing.Imaging.ImageFormat.Png);
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 图片转JPeG
        /// picturefile 图片文件名
        /// filePath 保存路径
        /// </summary>
        public bool SaveJpeg(string picturefile, string filePath)
        {
            Image img = Image.FromFile(picturefile);
            try
            {
                using (var bmp = new Bitmap(img.Width, img.Height))
                {
                    bmp.SetResolution(img.HorizontalResolution, img.VerticalResolution);

                    using (var g = Graphics.FromImage(bmp))
                    {
                        g.Clear(Color.White);
                        g.DrawImageUnscaled(img, 0, 0);
                    }
                    //存储各种格式
                    //bmp.Save(filePath, System.Drawing.Imaging.ImageFormat.Gif);
                    //bmp.Save(filePath, System.Drawing.Imaging.ImageFormat.Png);
                    bmp.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 插入JPeG图片
        /// topdfdoc 所要插入的文档
        /// filename 图片文件名
        /// fileinfo 文件信息
        /// width page宽
        /// height page高
        /// index 插入位置
        /// </summary>
        private void JpegInsertPage(ref CPDFDocument topdfdoc,string filename, FileInfo fileinfo,int width,int height,int index=0) {

            string tempFileName = "";
            if (fileinfo.Extension == ".jpg"|| fileinfo.Extension == ".jpeg")
            {
                topdfdoc.InsertPage(index, width, height, filename);
            }
            else 
            {
                tempFileName = Path.GetTempPath() + "pngtemp.jpg";
                if (!PictureConverter.SaveJpeg(filename, tempFileName))
                { 
                    MessageBoxEx.Show("图片格式有问题");
                }
                topdfdoc.InsertPage(index, width, height, tempFileName);
            }
        }
        #endregion

        #region 构架行为
        public string Title => "图片转PDF";

        public event Action<IDialogResult> RequestClose;

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {
        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
            string[] filepath=null;
            parameters.TryGetValue<string[]>(ParameterNames.FilePath, out filepath);
            if (filepath!=null)
            {
                fileNames=filepath.ToList();
                ImagesDataTable.Columns.Add("FileName");
                ImagesDataTable.Columns.Add("FileSize");
                ImagesDataTable.Columns.Add("FileState");
                updateListview("待确定");
            }
        }
        #endregion
    }
}
