using ComPDFKit.PDFDocument;
using ComPDFKitViewer.AnnotEvent;
using ComPDFKitViewer.PdfViewer;
using Microsoft.Win32;
using PDF_Office.Model;
using PDF_Office.Model.AnnotPanel;
using PDF_Office.Properties;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Ink;
using System.Windows.Media.Imaging;

namespace PDF_Office.ViewModels.PropertyPanel.AnnotPanel
{
    class SignatureAnnotPropertyViewModel : BindableBase, INavigationAware
    {
        private CPDFViewer PDFViewer;
        private IDialogService dialogs;
        public DelegateCommand ShowDialogCommand { get; set; }

        public ObservableCollection<Signature> SignatureList { get; set; }
        public SignatureAnnotPropertyViewModel(IDialogService dialogService)
        {
            dialogs = dialogService;
            ShowDialogCommand = new DelegateCommand(ShowDialog);
            SignatureList = new ObservableCollection<Signature>();
            LoadSettings();
        }

        /// <summary>
        /// 加载缓存的签名
        /// </summary>
        private void LoadSettings()
        {
            PDFSettings.SignatureList items = Settings.Default.SignatureList;
            if (items != null)
            {
                for (int i = 0; i < items.Count; i++)
                {
                    Signature customStamp = new Signature();
                    customStamp.SourcePath = items[i].SourcePath;
                    customStamp.DrawingPath = items[i].DrawingPath;
                    customStamp.inkThickness= items[i].inkThickness;
                    customStamp.inkColor= items[i].inkColor;
                    customStamp.Type = (SignatureType)items[i].Type;
                    SignatureList.Add(customStamp);
                }
            }
        }
        public void SetSignature(Signature signature)
        {
            switch (signature.Type)
            {
                case SignatureType.TextType:
                case SignatureType.ImageType:
                    {
                        StampAnnotArgs stampArgs = new StampAnnotArgs();
                        stampArgs.Opacity = 1;
                        stampArgs.Type = StampType.IMAGE_STAMP;
                        stampArgs.ImagePath = signature.SourcePath;
                        PDFViewer.SetMouseMode(MouseModes.AnnotCreate);
                        PDFViewer.SetToolParam(stampArgs);
                    }
                    break;
                case SignatureType.Drawing:
                    {
                        StampAnnotArgs stampArgs = new StampAnnotArgs();
                        stampArgs.SetInkData(GetPoints(signature.DrawingPath), signature.inkThickness, signature.inkColor);
                        PDFViewer.SetMouseMode(MouseModes.AnnotCreate);
                        PDFViewer.SetToolParam(stampArgs);
                    }
                    break;
                default:
                    break;
            }
        }
        private List<List<Point>> GetPoints(string Path)
        {
            StrokeCollection Strokes;
            List<List<Point>> RawPointList = new List<List<Point>>();
            using (FileStream strokeStream = File.OpenRead(Path))
            {
                Strokes = new StrokeCollection(strokeStream);
            }

            for (int kk = 0; kk < Strokes.Count; kk++)
            {
                List<Point> p = new List<Point>();
                RawPointList.Add(p);
                for (int gg = 0; gg < Strokes[kk].StylusPoints.Count; gg++)
                {
                    var point = Strokes[kk].StylusPoints[gg].ToPoint();

                    if (point.X >= 0 && point.Y >= 0)
                        RawPointList[kk].Add(point);

                }
            }
            return RawPointList;
        }
        private void ShowDialog()
        {
            bool result = true;
            DialogParameters value = new DialogParameters();
            value.Add(ParameterNames.PDFViewer, PDFViewer);
            dialogs.ShowDialog(DialogNames.SignatureCreateDialog, value, e =>
            {
                if (e.Result != ButtonResult.OK)
                {
                    result = false;
                }
                SignatureCreateDialogViewModel DialogVM = e.Parameters.GetValue<SignatureCreateDialogViewModel>(ParameterNames.DataModel);
                if (DialogVM != null)
                {
                    CreateSignature(DialogVM);
                }
            });
            if (!result)
            {
                return;
            }
        }

        /// <summary>
        /// 创建签名，并保存到APP缓存
        /// </summary>
        /// <param name="viewModel"></param>
        private void CreateSignature(SignatureCreateDialogViewModel viewModel)
        {
            Signature Signature = new Signature();
            if (viewModel.IsRemoveBackground)
            {
                if (!string.IsNullOrEmpty(viewModel.SaveToPath))
                {
                    App.CachePath.AddToDeleteFiles(viewModel.SaveToPath);
                }
                Signature.SourcePath = viewModel.RemoveBackgroundSaveToPath;
            }
            else
            {
                Signature.SourcePath = viewModel.SaveToPath;
            }
            Signature.DrawingPath = viewModel.DrawingSaveToPath;
            Signature.Type = (SignatureType)viewModel.TabItemIndex;
            Signature.inkThickness = viewModel.DrawingAttributeObject.Width;
            Signature.inkColor = viewModel.DrawingAttributeObject.Color;
            SignatureList.Add(Signature);

            //缓存数据
            PDFSettings.SignatureList stamps = Settings.Default.SignatureList;
            if (stamps == null)
            {
                stamps = Settings.Default.SignatureList = new PDFSettings.SignatureList();
            }

            PDFSettings.SignatureItem signature = new PDFSettings.SignatureItem();
            signature.DrawingPath = Signature.DrawingPath;
            signature.SourcePath = Signature.SourcePath;
            signature.inkThickness = Signature.inkThickness;
            signature.inkColor = Signature.inkColor;
            signature.Type = (PDFSettings.SignatureType)Signature.Type;
            stamps.Add(signature);
            Settings.Default.Save();
        }

        /// <summary>
        /// 导出签名
        /// </summary>
        public void SaveToPath(string FileType, Signature Item)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Title = "保存" + FileType + "文件";
            saveFileDialog.Filter = "（*）|*." + FileType;

            if (saveFileDialog.ShowDialog() == false)
            {
                return;
            }
            BitmapEncoder encoder;
            if (FileType.ToUpper() == "JPG")
            {
                encoder = new JpegBitmapEncoder();
            }
            else
            {
                encoder = new PngBitmapEncoder();
            }
            encoder.Frames.Add(BitmapFrame.Create(new Uri(Item.SourcePath)));
            string path = saveFileDialog.FileName;
            switch (FileType.ToUpper())
            {
                case "PDF":
                    CPDFDocument newDoc = CPDFDocument.CreateDocument();
                    BitmapFrame frame = BitmapFrame.Create(new Uri(Item.SourcePath));
                    byte[] imageData = new byte[frame.PixelWidth * frame.PixelHeight * 4];
                    frame.CopyPixels(imageData, frame.PixelWidth * 4, 0);
                    newDoc.InsertPage(0, frame.PixelWidth, frame.PixelHeight, imageData, CPDFDocumentImageMode.CPDFDocumentImageModeScaleToFill);
                    newDoc.WriteToFilePath(path);
                    break;
                case "PNG":
                    using (FileStream stream = new FileStream(path, FileMode.Create))
                    {
                        encoder.Save(stream);
                    }
                    break;
                default:
                    break;
            }
            System.Diagnostics.Process.Start("explorer", "/select,\"" + path + "\"");
        }

        public void DeleteSignature(Signature Item)
        {
            int index = SignatureList.IndexOf(Item);
            App.CachePath.AddToDeleteFiles(Item.SourcePath);
            if (!string.IsNullOrEmpty(Item.DrawingPath))
            {
                App.CachePath.AddToDeleteFiles(Item.DrawingPath);
            }
            SignatureList.RemoveAt(index);

            PDFSettings.SignatureList signature = Settings.Default.SignatureList;
            signature.RemoveAt(index);
            Settings.Default.Save();
        }
        public void DeleteAll()
        {
            foreach (Signature item in SignatureList)
            {
                App.CachePath.AddToDeleteFiles(item.SourcePath);

                if (!string.IsNullOrEmpty(item.DrawingPath))
                {
                    App.CachePath.AddToDeleteFiles(item.DrawingPath);
                }
            }
            SignatureList.Clear();

            PDFSettings.SignatureList signature = Settings.Default.SignatureList;
            signature.Clear();
            Settings.Default.Save();
        }
        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
            return;
        }

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            navigationContext.Parameters.TryGetValue<CPDFViewer>(ParameterNames.PDFViewer, out PDFViewer);
            if (PDFViewer == null)
            {
                return;
            }
        }
    }
}
