using ComPDFKit.PDFDocument;
using ComPDFKit.PDFPage;
using PDF_Office.CustomControl;
using PDFSettings.Settings;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;

namespace PDF_Office.Helper
{
    public static class ToolMethod
    {
        /// <summary>
        /// 返回跟DPi 无关的图片
        /// </summary>
        /// <param name="document"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        public static async Task<Bitmap> RenderPageBitmap(CPDFDocument document,int width,int height,int pageIndex,bool annot,bool form)
        {
            if (width <= 0.0 || height<= 0.0)
            {
                return null;
            }

            Bitmap bitmap = new Bitmap((int)width, (int)height, PixelFormat.Format32bppArgb);
            BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, (int)width, (int)height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
            try
            {
                CPDFPage kMPDFPage = document.PageAtIndex(pageIndex);
                await Task.Run(()=> kMPDFPage.RenderPageBitmap(0,0,width,height, uint.MaxValue, bitmapData.Scan0,annot?1:0,form));
               // kMPDFPage.RenderPageBitmapWithMatrix((float)1, new System.Windows.Rect(), uint.MaxValue, bitmapData.Scan0, 1, form: true);
            }
            catch (Exception)
            {
                return null;
            }

            bitmap.UnlockBits(bitmapData);
            return bitmap;
        }

        public static Bitmap RenderPageBitmapNoWait(CPDFDocument document, int width, int height, int pageIndex,bool annote,bool form,uint custombackground=0xFFFFFFFF)
        {
            if (width <= 0.0 || height <= 0.0)
            {
                return null;
            }

            Bitmap bitmap = new Bitmap((int)width, (int)height, PixelFormat.Format32bppArgb);
            BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, (int)width, (int)height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
            try
            {
                CPDFPage kMPDFPage = document.PageAtIndex(pageIndex);
                //1-显示注释 0-不显示注释  form-true 显示表单   form-false  不显示表单
                if (custombackground != 0xFFFFFFFF)
                {
                    kMPDFPage.RenderPageBitmap(0, 0, width, height, custombackground, bitmapData.Scan0, annote ? 1 : 0, form);
                }
                else
                {
                    kMPDFPage.RenderPageBitmap(0, 0, width, height, uint.MaxValue, bitmapData.Scan0, annote ? 1 : 0, form);
                }
                //kMPDFPage.RenderPageBitmapWithMatrix((float)1, new System.Windows.Rect(), uint.MaxValue, bitmapData.Scan0, 1, form: true);
            }
            catch (Exception)
            {
                return null;
            }

            bitmap.UnlockBits(bitmapData);
            return bitmap;
        }


        public static void SetFileThumbImg(string fileName)
        {

            bool isNewDocument = false;
            //检查是否是新文档
            OpenFileInfo isnew = SettingHelper.GetFileInfo(fileName);
            if (isnew == null)
                isNewDocument = true;

            //检查是否是加密文档  要在open前检查
            bool isLockedfile = false;
            CPDFDocument tempdoc = CPDFDocument.InitWithFilePath(fileName);
            if (tempdoc != null && (bool)(tempdoc.IsLocked))
                isLockedfile = true;

            OpenFileInfo fileInfo = SettingHelper.GetFileInfo(fileName);


            if (fileInfo != null)
            {
                try
                {
                    if (string.IsNullOrWhiteSpace(fileInfo.ThumbImgPath) || isLockedfile)//未保存文档首页缩略图时，提取第一页当缩略图
                    {
                        if (isLockedfile)
                        {
                            fileInfo.ThumbImgPath = "pack://application:,,,/Resources/FilesType/ic_propertybar_file_pdf_lock.png";
                        }
                        else
                        {
                            if (tempdoc.PageCount > 0)
                            {
                                var size = tempdoc.GetPageSize(0);
                                System.Drawing.Bitmap bitmap = ToolMethod.RenderPageBitmapNoWait(tempdoc, (int)size.Width, (int)size.Height, 0, true, true);
                                string folderPath = System.IO.Path.Combine(App.CurrentPath, "CoverImage");
                                //有可能因为其他原因存在同名文件，导致创建文件夹失败，需要先删除文件
                                //保险措施(猜测)
                                if (File.Exists(folderPath))
                                    File.Delete(folderPath);
                                DirectoryInfo folder = new DirectoryInfo(folderPath);
                                if (!folder.Exists)
                                    folder.Create();
                                string imageName = Guid.NewGuid().ToString();
                                string imagePath = System.IO.Path.Combine(folderPath, imageName);
                                using (FileStream stream = new FileStream(imagePath, FileMode.Create))
                                {
                                    bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                                }
                                fileInfo.ThumbImgPath = imagePath;
                            }
                        }


                    }
                    else//解锁文件覆盖了加密文件的情况 或者本地缩略图文件被删除
                    {
                        if (tempdoc.PageCount > 0 && (!File.Exists(fileInfo.ThumbImgPath) || (!tempdoc.IsEncrypted && fileInfo.ThumbImgPath.Equals("pack://application:,,,/Resources/Image/Home/FilesType/ic_propertybar_file_pdf_lock.png"))))
                        {
                            var size = tempdoc.GetPageSize(0);
                            System.Drawing.Bitmap bitmap = ToolMethod.RenderPageBitmapNoWait(tempdoc, (int)size.Width, (int)size.Height, 0, true, true);
                            string folderPath = System.IO.Path.Combine(App.CurrentPath, "CoverImage");
                            if (File.Exists(folderPath))
                                File.Delete(folderPath);
                            DirectoryInfo folder = new DirectoryInfo(folderPath);
                            if (!folder.Exists)
                                folder.Create();
                            string imageName = Guid.NewGuid().ToString();
                            string imagePath = System.IO.Path.Combine(folderPath, imageName);
                            using (FileStream stream = new FileStream(imagePath, FileMode.Create))
                            {
                                bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                            }
                            fileInfo.ThumbImgPath = imagePath;
                        }
                    }
                }
                catch
                {
                    fileInfo.ThumbImgPath = null;
                    MessageBoxEx.Show("LoadFile_GetThumbnailFailedWarning");
                }
            }

        }


        public static BitmapImage GetFileThumbImg(string path)
        {
            BitmapImage bitmap = new BitmapImage();
            if (File.Exists(path))
            {
                bitmap.BeginInit();
                bitmap.CacheOption = BitmapCacheOption.OnLoad;
                using (Stream ms = new MemoryStream(File.ReadAllBytes(path)))
                {
                    bitmap.StreamSource = ms;
                    bitmap.EndInit();
                    bitmap.Freeze();
                }
            }
            else if (path.Equals("pack://application:,,,/Resources/FilesType/ic_propertybar_file_pdf_lock.png"))
                bitmap = new BitmapImage(new Uri("pack://application:,,,/Resources/FilesType/ic_propertybar_file_pdf_lock.png"));
            else//最近文档 但是删除了缩略图的情况
                bitmap = new BitmapImage(new Uri("pack://application:,,,/Resources/FilesType/ic_propertybar_file_png_Large.png"));
            return bitmap;
        }

    }
}
