using PDF_Office.Views.Dialog.HomePageToolsDialogs.HomePagePrinter;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Windows.Controls;
using System.Windows;
using System.Diagnostics;
using System.Drawing.Printing;
using PDFSettings;
using ComPDFKit.PDFDocument;
using PDF_Office.Model;
using System.Drawing;
using System.Reflection;
using PDF_Office.Model.Dialog.HomePageToolsDialogs.HomePagePrinter;
using System.Threading.Tasks;
using static PDF_Office.Model.Dialog.ToolsDialogs.SaftyDialogs.SetPasswordDialogModel;
using ComPDFKit.PDFPage;
using PDF_Office.Helper;
using System.Drawing.Drawing2D;
using static PDF_Office.Model.Dialog.HomePageToolsDialogs.HomePagePrinter.HomePagePrinterDialogModel;
using ComPDFKitViewer.PdfViewer;

namespace PDF_Office.ViewModels.Dialog.HomePageToolsDialogs.HomePagePrinter
{
    public class HomePagePrinterDialogViewModel : BindableBase, IDialogAware, INavigationAware
    {
        public IDialogService Dialogs;
        public IRegionManager PrintModRegion;
        private Object locker = new Object();
        private CPDFViewer currentViewer;
        private string currentPrintModName;

        public Dictionary<string, string> GetContentByPrintMod;
        public Dictionary<int, string> GetPrinterNameByPrinterIndex;

        public HomePagePrinterDialogModel homePagePrinterDialogModel;
        public PrintSettingsInfo printSettingsInfo;

        private Visibility _printModVisible = Visibility.Collapsed;
        public Visibility PrintModVisible
        {
            get { return _printModVisible; }
            set { SetProperty(ref _printModVisible, value); }
        }

        #region 界面和组件初始化
        private string _printModRegionName;
        public string PrintModRegionName
        {
            get
            {
                return _printModRegionName;
            }
            set
            {
                SetProperty(ref _printModRegionName, value);
            }
        }

        private List<string> _printerNameList;
        public List<string> PrinterNameList
        {
            get { return _printerNameList; }
            set { _printerNameList = value; }
        }

        private List<string> _printContentList;
        public List<string> PrintContentList
        {
            get { return _printContentList; }
            set { _printContentList = value; }
        }

        private List<string> _printerDirectionList;
        private CPDFDocument document;

        public List<string> PrintDirectionList
        {
            get { return _printerDirectionList; }
            set { _printerDirectionList = value; }
        }
        #endregion

        #region 属性设置
        private int _printerIndex;
        public int PrinterIndex
        {
            get { return _printerIndex; }
            set { _printerIndex = value; }
        }
        #endregion

        #region 打印
        private PrintDocument printDocument = new PrintDocument();
        private PrinterSettings printerSettings = new PrinterSettings();
        private PageSettings PageSettings = new PageSettings();

        /// <summary>
        ///待打印页面集合，存储页面索引值
        /// </summary>
        private List<int> TargetPages = new List<int>();

        private int currentListIndex = 0;
        private bool annotation = true;
        private bool form = true;

        private int currentViewerPageIndex = 0;

        System.Drawing.Point location = new System.Drawing.Point(10, 10);
        System.Drawing.Size size = new System.Drawing.Size(600, 150);
        #endregion

        public DelegateCommand<object> DelegateChangePrintModCommand { get; set; }

        public HomePagePrinterDialogViewModel(IDialogService dialogService, IRegionManager regionManager)
        {
            Dialogs = dialogService;
            PrintModRegion = regionManager;
            PrintModVisible = Visibility.Visible;
            PrintModRegionName = Guid.NewGuid().ToString();
            DelegateChangePrintModCommand = new DelegateCommand<object>(ChangePrintMod);
            homePagePrinterDialogModel = new HomePagePrinterDialogModel();
            printSettingsInfo = new PrintSettingsInfo();

            GetContentByPrintMod = new Dictionary<string, string>();
            InitGetContentByPrintMod(ref GetContentByPrintMod);

            GetPrinterNameByPrinterIndex = new Dictionary<int, string>();
            InitGetPrinterNameByPrinterIndex(ref GetPrinterNameByPrinterIndex);

            InitComponentAsync();
            InitPrinterSettings();

        }

        #region 组件初始化
        private void InitComponentAsync()
        {
            InitPrinterNameList();
            InitPrintContentList();
            InitPrintContentList();
            InitPrintDirectionList();
        }

        private void PaintPageAtIndex(object currentViewerIndex)
        {
            try
            {
                lock (locker)
                {
                    #region 根据不同打印模式 做不同处理
                    switch (currentPrintModName)
                    {
                        case "ModPoster":

                            break;
                        case "ModMutiple":

                            break;
                        case "ModBooklet":
                            //打印机要适时设置双面打印

                            break;
                        case "ModSize"://普通 大小模式
                        default:
                            PreviewModSize(currentViewerPageIndex);
                            break;
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {

            }
        }

        private void InitPrinterNameList()
        {
            PrinterNameList = new List<string>();
            PrintDocument printDocument = new PrintDocument();
            string defaultPrinterName = printDocument.PrinterSettings.PrinterName;

            foreach (string printerListItem in PrinterSettings.InstalledPrinters)
            {
                PrinterNameList.Add(printerListItem);
            }
        }
        private void InitPrintContentList()
        {
            PrintContentList = new List<string>();
            PrintContentList.Add("文档");
            PrintContentList.Add("文档和标记");
            PrintContentList.Add("文档和图章");
        }

        private void InitPrintDirectionList()
        {
            PrintDirectionList = new List<string>();
            PrintDirectionList.Add("横向");
            PrintDirectionList.Add("纵向");
        }

        private void InitGetContentByPrintMod(ref Dictionary<string, string> dictionary)
        {
            dictionary.Add("ModSize", "HomePagePrinterModSizeContent");
            dictionary.Add("ModPoster", "HomePagePrinterModPosterContent");
            dictionary.Add("ModMutiple", "HomePagePrinterModMutipleContent");
            dictionary.Add("ModBooklet", "HomePagePrinterModBookletContent");
        }

        private void InitGetPrinterNameByPrinterIndex(ref Dictionary<int, string> dictionary)
        {
            int index = 0;
            PrinterNameList = new List<string>();
            PrintDocument printDocument = new PrintDocument();
            string defaultPrinterName = printDocument.PrinterSettings.PrinterName;

            foreach (string printerListItem in PrinterSettings.InstalledPrinters)
            {
                dictionary.Add(index++, printerListItem);
            }
            if (index == 0)
            {
#if DEBUG
                MessageBox.Show("No Printer!");
#endif
            }
        }

        #endregion

        #region 打印初始化
        public double GetDpiByGraphics()
        {
            BindingFlags bindingAttr = BindingFlags.Static | BindingFlags.NonPublic;
            PropertyInfo property = typeof(SystemParameters).GetProperty("Dpi", bindingAttr);
            return (int)property.GetValue(null, null);
        }
        public void InitPrinterSettings()
        {
            location = new System.Drawing.Point((int)(18 * GetDpiByGraphics() / 120), (int)(66 * GetDpiByGraphics() / 120));
            size = new System.Drawing.Size((int)(624 * GetDpiByGraphics() / 120), (int)(130 * GetDpiByGraphics() / 120));
        }

        public async Task InitPrintParamsAsync()
        {
            printSettingsInfo.PrinterName = GetPrinterNameByPrinterIndex[PrinterIndex];
            printSettingsInfo.Copies = 1;
            printSettingsInfo.IsBlackAndWhite = false;
            printSettingsInfo.IsReverseOrder = false;
            printSettingsInfo.PrintWithAnnot = true;
            printSettingsInfo.PrintWithForm = true;
            printSettingsInfo.EnumPrintOrientation = EnumPrintOrientation.StatusHorizontal;

            SizeSetttingsInfo sizeSetttingsInfo = new SizeSetttingsInfo();
            sizeSetttingsInfo.SizeType = EnumSizeType.StatusAdaptive;
            sizeSetttingsInfo.DisplayRatio = 100;
            printSettingsInfo.SizeSetttingsInfo = sizeSetttingsInfo;

            await Task.Run(() => { PaintPageAtIndex(currentViewerPageIndex); });
        }
        #endregion

        #region 四种打印的预览
        /// <summary>
        /// 重新调整图片大小(比例不变) 缩放图片
        /// 可以直接传入目标区域大小，不会丢失原图比例
        /// </summary>
        /// <param name="image"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public System.Drawing.Image ResizeImage(System.Drawing.Image image, System.Drawing.Size size)
        {
            //获取图片宽度
            int sourceWidth = image.Width;
            //获取图片高度
            int sourceHeight = image.Height;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;
            //计算宽度的缩放比例
            //nPercentW = ((float)size.Width * (float)GetDpiByGraphics()/120/ (float)sourceWidth);
            ////计算高度的缩放比例
            //nPercentH = ((float)size.Height*(float)GetDpiByGraphics() / 120 / (float)sourceHeight);
            nPercentW = ((float)size.Width / (float)sourceWidth);
            //计算高度的缩放比例
            nPercentH = ((float)size.Height / (float)sourceHeight);

            if (nPercentH < nPercentW)
                nPercent = nPercentH;
            else
                nPercent = nPercentW;
            //期望的宽度
            int destWidth = (int)(sourceWidth * nPercent);
            //期望的高度
            int destHeight = (int)(sourceHeight * nPercent);

            System.Drawing.Bitmap b = new System.Drawing.Bitmap(destWidth, destHeight);
            Graphics g = Graphics.FromImage((System.Drawing.Image)b);
            //g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.SmoothingMode = SmoothingMode.None; //抗锯齿
            g.InterpolationMode = InterpolationMode.HighQualityBicubic; //高质量的双三次插值
            g.CompositingQuality = CompositingQuality.HighQuality; //高质量、低速度复合
            //绘制图像
            g.DrawImage(image, 0, 0, destWidth, destHeight);
            g.Dispose();
            return (System.Drawing.Image)b;
        }

        private async void PreviewModSize(int pageIndex)
        {
            CPDFPage cPDFPage = document.PageAtIndex(pageIndex);
            if (cPDFPage == null)
            {
                double left = 0;
                double top = 0;
                double rate = 0;
                int dpi = (int)GetDpiByGraphics();
                Bitmap bitmap = await ToolMethod.RenderPageBitmap(document, (int)(cPDFPage.PageSize.Width * rate * 1.4), (int)(cPDFPage.PageSize.Height * rate * 1.4), pageIndex, printSettingsInfo.PrintWithAnnot, printSettingsInfo.PrintWithForm);
                var pageBound = printDocument.DefaultPageSettings.Bounds;
                double ZoomRate = (double)printSettingsInfo.SizeSetttingsInfo.DisplayRatio / 100.0;
                if (printSettingsInfo.SizeSetttingsInfo.SizeType == EnumSizeType.StatusAdaptive)
                {
                    float zoompercent = 0;
                    float percentW = 0;
                    float percentH = 0;
                    percentW = ((float)(pageBound.Width * rate) / (float)bitmap.Width);
                    percentH = ((float)(pageBound.Height * rate) / (float)bitmap.Height);
                    zoompercent = percentH > percentW ? percentW : percentH;

                    var newSize = new System.Drawing.Size((int)(bitmap.Width * zoompercent), (int)(bitmap.Height * zoompercent));
                    bitmap = (Bitmap)ResizeImage(bitmap, newSize);

                    left = (pageBound.Width * rate - bitmap.Width) / 2;
                    top = (pageBound.Height * rate - bitmap.Height) / 2;

                    int pwidth = (int)(pageBound.Width * rate);
                    int pheight = (int)(pageBound.Height * rate);

                    Bitmap bmp = new Bitmap(pwidth, pheight);
                    Graphics g = Graphics.FromImage(bmp);
                    g.DrawImage(bitmap, (float)left, (float)top, bitmap.Width, bitmap.Height);
                }
            }
        }
        #endregion

        private void EnterSelectedMod(string currentPrinterModContent)
        {
            NavigationParameters param = new NavigationParameters();
            PrintModVisible = Visibility.Collapsed;
            PrintModRegion.RequestNavigate(PrintModRegionName, GetContentByPrintMod[currentPrinterModContent]);
            PrintModVisible = Visibility.Visible;
            //TODO:
        }



        private void ChangePrintMod(object e)
        {
            var args = e as Button;
            if (args != null)
            {
                currentPrintModName = args.Name;
                EnterSelectedMod(currentPrintModName);
                //TODO：
            }
        }

        public string Title => "";

        public event Action<IDialogResult> RequestClose;

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {
        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
            CPDFViewer viewer = null;
            string filepath = "";
            parameters.TryGetValue<CPDFViewer>(ParameterNames.PDFViewer, out viewer);
            parameters.TryGetValue<string>(ParameterNames.FilePath, out filepath);
            if (viewer != null && viewer.Document != null)
            {
                currentViewer = viewer;
                document = currentViewer.Document;
                InitPrintParamsAsync();

            }
        }

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
        }

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

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
        }
    }
}
