using ComPDFKitViewer.AnnotEvent;
using ComPDFKitViewer.PdfViewer;
using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Windows;
using System.Windows.Media.Imaging;
using System.Drawing;
using static Dropbox.Api.Sharing.MemberAction;
using System.IO;
using PDF_Master.Helper;
using Microsoft.Win32;
using System.Windows.Interop;
using PDF_Master.CustomControl;
using System.Windows.Controls;
using PDF_Master.Model.Dialog.HomePageToolsDialogs.HomePagePrinter;
using ComPDFKit.PDFPage;
using System.Drawing.Printing;
using System.Security.Policy;
using Microsoft.AppCenter.Utils.Files;
using File = System.IO.File;
using Directory = System.IO.Directory;
using System.Drawing.Imaging;
using Microsoft.Office.Interop.Word;
using static Dropbox.Api.Sharing.ListFileMembersIndividualResult;
using Prism.Regions;
using System.Windows.Input;
using Microsoft.Office.Interop.Excel;
using static PDF_Master.Model.Dialog.ToolsDialogs.SaftyDialogs.DeleteSafetySettintgsModel;
using Prism.Services.Dialogs;

namespace PDF_Master.ViewModels.PropertyPanel.AnnotPanel
{
    public class SnapshotEditMenuViewModel : BindableBase
    {
        public CustomIconToggleBtn ToggleBtn { get; set; }
        public SnapshotEditToolArgs SnapToolArgs { get; set; }
        public CPDFViewer PDFViewer { get; set; }

        public AreaCropPageUndoManager areaCropPageUndoManager;

        private CPDFViewer saveToPDFViewer = new CPDFViewer();

        public event EventHandler<KeyValuePair<string, object>> SnapToolEvent;

        public DelegateCommand SnapCopyCommand { get; set; }

        public DelegateCommand ExportPNGCommand { get; set; }

        public DelegateCommand ExportJPGCommand { get; set; }

        public DelegateCommand ExportPDFCommand { get; set; }
        public DelegateCommand CroppingCommand { get; set; }

        public DelegateCommand PrintCommand { get; set; }

        public SnapshotEditMenuViewModel()
        {
            SnapCopyCommand = new DelegateCommand(CopyEvent);
            ExportPNGCommand = new DelegateCommand(ExportPNGEvent);
            ExportJPGCommand = new DelegateCommand(ExportJPGEvent);
            ExportPDFCommand = new DelegateCommand(ExportPDFEvent);
            CroppingCommand = new DelegateCommand(CroppingEvent);
            PrintCommand = new DelegateCommand(PrintEvent);
        }

        private void PrintEvent()
        {
            if (SnapToolArgs != null && PDFViewer != null && PDFViewer.ToolManager != null)
            {
                try
                {
                    WriteableBitmap saveBitmap = SnapToolArgs.GetSnapshotImage();
                    if (saveBitmap != null)
                    {
                        PrintDialog printDlg = new PrintDialog();
                        if (printDlg.ShowDialog() == true)
                        {
                            DrawingVisual visualItem = new DrawingVisual();
                            DrawingContext drawContext = visualItem.RenderOpen();
                            drawContext.DrawImage(saveBitmap, new Rect(0, 0, saveBitmap.Width, saveBitmap.Height));
                            drawContext.Close();
                            printDlg.PrintVisual(visualItem, "Snapshot");
                        }
                    }
                    PDFViewer.RemoveTool(false);
                    PDFViewer.SetMouseMode(MouseModes.PanTool);
                    if (SnapToolEvent != null)
                    {
                        KeyValuePair<string, object> param = new KeyValuePair<string, object>("CloseSnap", null);
                        SnapToolEvent.Invoke(this, param);
                    }
                }
                catch (Exception ex)
                {
                }
            }
        }

        private void CroppingEvent()
        {
            if (SnapToolArgs != null && PDFViewer != null && PDFViewer.ToolManager != null)
            {
                Rect rect = SnapToolArgs.GetSnapshotPDFRect(out int CurrentIndex);
                List<int> cropPageList = new List<int>();
                cropPageList.Add(CurrentIndex);
                areaCropPageUndoManager.ADDAreaCropPage(cropPageList, rect, PDFViewer.Document.GetPageSize(cropPageList[0]));
                PDFViewer?.CropPage(CPDFDisplayBox.CropBox, rect, cropPageList);
                PDFViewer.GoToPage(CurrentIndex);
                //Rect rect1 = new Rect(-rect.Left, -rect.Top, PDFViewer.Document.GetPageSize(7).Width + rect.Left, PDFViewer.Document.GetPageSize(7).Height + rect.Top);
                //PDFViewer?.CropPage(CPDFDisplayBox.CropBox, rect1, cropPageList);
                PDFViewer.UndoManager.AddHistory(areaCropPageUndoManager);
                PDFViewer.UndoManager.CanSave = true;
                PDFViewer.SetMouseMode(MouseModes.PanTool);
                if (SnapToolEvent != null)
                {
                    KeyValuePair<string, object> param = new KeyValuePair<string, object>("CloseSnap", null);
                    SnapToolEvent.Invoke(this, param);
                }
            }
        }

        private void ExportPDFEvent()
        {
            SnapshotEditExport("PDF");
        }

        private void ExportJPGEvent()
        {
            SnapshotEditExport("JPG");
        }

        private void ExportPNGEvent()
        {
            SnapshotEditExport("PNG");
        }

        private void SnapshotEditExport(string type)
        {
            if (SnapToolArgs != null && PDFViewer != null && PDFViewer.ToolManager != null)
            {
                SaveFileDialog dlg = new SaveFileDialog();
                switch (type)
                {
                    case "PNG":
                        dlg.Filter = "PNG|*.png";
                        break;

                    case "JPG":
                        dlg.Filter = "JPG|*.jpg";
                        break;

                    case "PDF":
                        dlg.Filter = "PDF|*.pdf";
                        break;
                }

                dlg.FileName = PDFViewer.Document.FileName;
                if (dlg.FileName == null || dlg.FileName.Trim().Length == 0)
                {
                    dlg.FileName = "Blank" + DateTime.Now.ToString("yyyyMMddHHmmss");
                }
                if (dlg.ShowDialog() == true)
                {
                    string fileName = dlg.FileName;
                    WriteableBitmap saveBitmap = SnapToolArgs.GetSnapshotImage();
                    if (saveBitmap != null)
                    {
                        if (dlg.SafeFileName.ToLower().EndsWith(".jpg"))
                        {
                            Stream saveStream = dlg.OpenFile();
                            JpegBitmapEncoder jpgEncoder = new JpegBitmapEncoder();
                            BitmapFrame frame = BitmapFrame.Create(saveBitmap);
                            jpgEncoder.Frames.Add(frame);
                            jpgEncoder.Save(saveStream);
                            saveStream.Dispose();
                            //导出后打开对应文件夹
                            CommonHelper.ExplorerFile(dlg.FileName);
                        }
                        else if (dlg.SafeFileName.ToLower().EndsWith(".png"))
                        {
                            Stream saveStream = dlg.OpenFile();
                            PngBitmapEncoder pngEncoder = new PngBitmapEncoder();
                            BitmapFrame frame = BitmapFrame.Create(saveBitmap);
                            pngEncoder.Frames.Add(frame);
                            pngEncoder.Save(saveStream);
                            saveStream.Dispose();
                            //导出后打开对应文件夹
                            CommonHelper.ExplorerFile(dlg.FileName);
                        }
                        else if (dlg.SafeFileName.ToLower().EndsWith(".pdf"))
                        {
                            //Stream saveStream = dlg.OpenFile();

                            string imagePath = SaveImage(saveBitmap);
                            if (CreateFile(imagePath))
                            {
                                bool result = saveToPDFViewer.Document.WriteToFilePath(dlg.FileName);
                            }

                            //saveStream.Dispose();
                            //导出后打开对应文件夹
                            CommonHelper.ExplorerFile(dlg.FileName);
                        }
                    }

                    if (PDFViewer != null && PDFViewer.ToolManager != null)
                    {
                        PDFViewer.RemoveTool(false);
                        PDFViewer.SetMouseMode(MouseModes.PanTool);
                        if (SnapToolEvent != null)
                        {
                            KeyValuePair<string, object> param = new KeyValuePair<string, object>("CloseSnap", null);
                            SnapToolEvent.Invoke(this, param);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 创建文件,路径为空时表示创建空白文档
        /// 否则表示从图片路径创建PDf
        /// </summary>
        /// <param name="imagePath"></param>
        /// <returns></returns>
        public bool CreateFile(string imagePath = null)
        {
            string fileName = null;

            saveToPDFViewer.CreateDocument();
            if (saveToPDFViewer.Document == null)
            {
                AlertsMessage alertsMessage = new AlertsMessage();
                alertsMessage.ShowDialog("", "创建文件失败.", "OK");
                return false;
            }

            if (string.IsNullOrEmpty(imagePath))
            {
                fileName = "Blank Page.pdf";
                //默认插入595*842 大小的页面
                saveToPDFViewer.Document.InsertPage(0, 595, 842, null);
            }
            else
            {
                fileName = imagePath.Substring(imagePath.LastIndexOf("\\") + 1, imagePath.LastIndexOf(".") - imagePath.LastIndexOf("\\") - 1) + ".pdf";
                Bitmap pic = new Bitmap(imagePath);
                int width = pic.Size.Width;
                int height = pic.Size.Height;

                string ex = System.IO.Path.GetExtension(imagePath);
                //其他格式或者名称中含空格的图片 在本地先转存一下
                if ((ex != ".jpg" && ex != ".jpeg") || !Uri.IsWellFormedUriString(imagePath, UriKind.Absolute))
                {
                    //将其他格式图片转换成jpg
                    string folderPath = Path.GetTempPath();
                    if (File.Exists(folderPath))
                    {
                        File.Delete(folderPath);
                    }
                    DirectoryInfo tempfolder = new DirectoryInfo(folderPath);
                    if (!tempfolder.Exists)
                    {
                        tempfolder.Create();
                    }
                    string targetPath = System.IO.Path.Combine(folderPath, Guid.NewGuid().ToString());
                    imagePath = targetPath;
                    pic.Save(targetPath, ImageFormat.Jpeg);
                }
                pic.Dispose();

                var result = saveToPDFViewer.Document.InsertPage(0, width, height, imagePath);
                if (!result)
                {
                    AlertsMessage alertsMessage = new AlertsMessage();
                    alertsMessage.ShowDialog("", "创建文件失败.", "OK");
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// 保存WriteableBitmap图像
        /// </summary>
        /// <param name="wtbBmp"></param>
        private string SaveImage(WriteableBitmap wtbBmp)
        {
            string isSave = null;
            if (wtbBmp == null)
            {
                return isSave;
            }
            try
            {
                DirectoryInfo tempfolder = new DirectoryInfo(Path.Combine(App.CurrentPath, "Temp"));
                string strpath = tempfolder + DateTime.Now.ToString("yyyyMMddfff") + ".jpg";
                if (!File.Exists(tempfolder.FullName))
                {
                    Directory.CreateDirectory(tempfolder.FullName);
                }

                using (FileStream stream = new FileStream(strpath, FileMode.Create))
                {
                    JpegBitmapEncoder bitmapEncoder = new JpegBitmapEncoder();
                    bitmapEncoder.Frames.Add(BitmapFrame.Create(wtbBmp));
                    bitmapEncoder.Save(stream);
                    isSave = strpath;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
                isSave = null;
            }
            return isSave;
        }

        /// <summary>
        /// 复制
        /// </summary>
        private void CopyEvent()
        { 
            if (SnapToolArgs != null)
            {
                WriteableBitmap saveBitmap = SnapToolArgs.GetSnapshotImage();
                if (saveBitmap != null)
                {
                    Bitmap bitmap = BitmapFromWriteableBitmap(saveBitmap);
                    Clipboard.SetImage(ChangeBitmapToBitmapSource(bitmap));
                    PDFViewer.RemoveTool(false);
                    PDFViewer.SetMouseMode(MouseModes.PanTool);
                    if (SnapToolEvent != null)
                    {
                        KeyValuePair<string, object> param = new KeyValuePair<string, object>("CloseSnap", null);
                        SnapToolEvent.Invoke(this, param);
                    }
                }
            } 
        }

        private System.Drawing.Bitmap BitmapFromWriteableBitmap(WriteableBitmap writeBmp)
        {
            System.Drawing.Bitmap bmp;
            using (MemoryStream outStream = new MemoryStream())
            {
                BitmapEncoder enc = new BmpBitmapEncoder();
                enc.Frames.Add(BitmapFrame.Create((BitmapSource)writeBmp));
                enc.Save(outStream);
                bmp = new System.Drawing.Bitmap(outStream);
            }
            return bmp;
        }

        /// <summary>
        /// 从Bitmap转换成BitmapSource
        /// </summary>
        /// <param name="bmp"></param>
        /// <returns></returns>
        public BitmapSource ChangeBitmapToBitmapSource(Bitmap bmp)
        {
            BitmapSource returnSource;
            try
            {
                returnSource = Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
            }
            catch
            {
                returnSource = null;
            }
            return returnSource;
        }
    }
}