using ComPDFKit.PDFDocument;
using ComPDFKit.PDFWatermark;
using ComPDFKitViewer.AnnotEvent;
using ComPDFKitViewer.PdfViewer;
using Microsoft.Office.Interop.Word;
using PDF_Office.EventAggregators;
using PDF_Office.Helper;
using PDF_Office.Model;
using PDF_Office.Model.EditTools.Background;
using PDF_Office.Model.EditTools.Watermark;
using PDF_Office.Properties;
using PDF_Office.ViewModels.Tools;
using PDFSettings;
using Prism.Commands;
using Prism.Common;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Windows.Media;

namespace PDF_Office.ViewModels.EditTools.Watermark
{
    public class WatermarkCreateTextContentViewModel : BindableBase, INavigationAware
    {
        public WatermarkInfo WatermarkInfo = new WatermarkInfo();

        private WatermarkItem TemplateWatermarkItem;

        IEventAggregator eventAggregator;

        private CPDFViewer PDFViewer;

        private List<string> _opacityList = new List<string>();
        public List<string> OpacityList
        {
            get { return _opacityList; }
            set
            {
                SetProperty(ref _opacityList, value);
            }
        }

        private void InitOpacityList()
        {
            OpacityList.Clear();
            for (int temp = 0; temp <= 100; temp += 10)
            {
                OpacityList.Add(temp.ToString() + " %");
            }
        }

        private List<string> _rotationList = new List<string>();
        public List<string> RotationList
        {
            get { return _rotationList; }
            set
            {
                SetProperty(ref _rotationList, value);
            }
        }

        private void InitRotationList()
        {
            RotationList.Clear();
            for (int temp = -45; temp <= 45; temp += 15)
            {
                RotationList.Add(temp.ToString());
            }
        }

        private List<string> _fontNameList = new List<string>();
        public List<string> FontNameList
        {
            get { return _fontNameList; }
            set
            {
                SetProperty(ref _fontNameList, value);
            }
        }

        private void InitFontNameList()
        {
            FontNameList.Clear();
            FontNameList.Add("Courier");
            FontNameList.Add("Courier-Bold");
            FontNameList.Add("Courier-Oblique");
            FontNameList.Add("Courier-BoldOblique");
            FontNameList.Add("Helvetica");
            FontNameList.Add("Helvetica-Bold");
            FontNameList.Add("Helvetica-Oblique");
            FontNameList.Add("Helvetica-BoldOblique");
            FontNameList.Add("Times-Roman");
            FontNameList.Add("Times-Bold");
            FontNameList.Add("Times-Italic");
            FontNameList.Add("Times-BoldItalic");
        }

        private List<string> _fontSizeList = new List<string>();
        public List<string> FontSizeList
        {
            get { return _fontSizeList; }
            set
            {
                SetProperty(ref _fontSizeList, value);
            }
        }

        private void InitFontSizeList()
        {
            FontSizeList.Clear();
            FontSizeList.Add("自动");
            for (int temp = 8; temp <= 15; temp += 1)
            {
                FontSizeList.Add(temp.ToString() + "pt");
            }
        }

        private List<string> _scaleList = new List<string>();
        public List<string> ScaleList
        {
            get { return _scaleList; }
            set
            {
                SetProperty(ref _scaleList, value);
            }
        }

        private void InitScaleList()
        {
            ScaleList.Clear();
            for (int temp = 0; temp <= 100; temp += 10)
            {
                ScaleList.Add(temp.ToString() + " %");
            }
        }

        private List<string> _isFrontList = new List<string>();
        public List<string> IsFrontList
        {
            get { return _isFrontList; }
            set
            {
                SetProperty(ref _isFrontList, value);
            }
        }

        private void InitIsFrontList()
        {
            IsFrontList.Clear();
            IsFrontList.Add("位于页面上方");
            IsFrontList.Add("位于页面下方");
        }

        private string _textValue = "一个水印";
        public string TextValue
        {
            get { return _textValue; }
            set
            {
                SetProperty(ref _textValue, value);

            }
        }

        private int _rotationValue = 0;
        public int RotationValue
        {
            get { return _rotationValue; }
            set
            {
                SetProperty(ref _rotationValue, value);
                WatermarkInfo.Rotation = ((float)RotationValue / 180) * 3.1415926f;
                eventAggregator.GetEvent<SetWatermarkEvent>().Publish(new WatermarkInfoUnicode
                {
                    Unicode = Unicode,
                    Status = WatermarkInfo
                });
            }
        }

        private int _opacityValue = 100;
        public int OpacityValue
        {
            get { return _opacityValue; }
            set
            {
                SetProperty(ref _opacityValue, value);
                WatermarkInfo.Opacity = (byte)(((float)OpacityValue / 100) * 225);
                eventAggregator.GetEvent<SetWatermarkEvent>().Publish(new WatermarkInfoUnicode
                {
                    Unicode = Unicode,
                    Status = WatermarkInfo
                });
            }
        }

        private int _relativeScaleValue = 50;
        public int RelativeScaleValue
        {
            get { return _relativeScaleValue; }
            set
            {
                SetProperty(ref _relativeScaleValue, value);
            }
        }

        private string _rotationText = "0";
        public string RotationText
        {
            get { return _rotationText; }
            set
            {
                SetProperty(ref _rotationText, value);
            }
        }

        private string _opacityText = "100 %";
        public string OpacityText
        {
            get { return _opacityText; }
            set
            {
                SetProperty(ref _opacityText, value);

            }
        }

        private string _relativeScaleText = "50 %";
        public string RelativeScaleText
        {
            get { return _relativeScaleText; }
            set
            {
                SetProperty(ref _relativeScaleText, value);
            }
        }

        private string _vertOffsetValue = "0";
        public string VertOffsetValue
        {
            get { return _vertOffsetValue; }
            set
            {
                SetProperty(ref _vertOffsetValue, value);
                WatermarkInfo.VertOffset = float.Parse(VertOffsetValue);
                eventAggregator.GetEvent<SetWatermarkEvent>().Publish(new WatermarkInfoUnicode
                {
                    Unicode = Unicode,
                    Status = WatermarkInfo
                });
            }
        }

        private string _horizOffsetValue = "0";
        public string HorizOffsetValue
        {
            get { return _horizOffsetValue; }
            set
            {
                SetProperty(ref _horizOffsetValue, value);
                WatermarkInfo.HorizOffset = float.Parse(HorizOffsetValue);
                eventAggregator.GetEvent<SetWatermarkEvent>().Publish(new WatermarkInfoUnicode
                {
                    Unicode = Unicode,
                    Status = WatermarkInfo
                });
            }
        }

        private string _verticalSpacingValue = "6";
        public string VerticalSpacingValue
        {
            get { return _verticalSpacingValue; }
            set
            {
                SetProperty(ref _verticalSpacingValue, value);
                WatermarkInfo.VerticalSpacing = float.Parse(VerticalSpacingValue);
                eventAggregator.GetEvent<SetWatermarkEvent>().Publish(new WatermarkInfoUnicode
                {
                    Unicode = Unicode,
                    Status = WatermarkInfo
                });
            }
        }

        private string _horizontalSpacingValue = "6";
        public string HorizontalSpacingValue
        {
            get { return _horizontalSpacingValue; }
            set
            {
                SetProperty(ref _horizontalSpacingValue, value);
                WatermarkInfo.HorizontalSpacing = float.Parse(HorizontalSpacingValue);
                eventAggregator.GetEvent<SetWatermarkEvent>().Publish(new WatermarkInfoUnicode
                {
                    Unicode = Unicode,
                    Status = WatermarkInfo
                });
            }
        }

        private int _fontSizeSelectedIndex = 0;
        public int FontSizeSelectedIndex
        {
            get { return _fontSizeSelectedIndex; }
            set
            {
                SetProperty(ref _fontSizeSelectedIndex, value);
                SetFontSize(FontSizeSelectedIndex);
                eventAggregator.GetEvent<SetWatermarkEvent>().Publish(new WatermarkInfoUnicode
                {
                    Unicode = Unicode,
                    Status = WatermarkInfo
                });
            }
        }

        private int _fontNameSelectedIndex = 0;
        public int FontNameSelectedIndex
        {
            get { return _fontNameSelectedIndex; }
            set
            {
                SetProperty(ref _fontNameSelectedIndex, value);
                SetFontName(FontNameSelectedIndex);
                eventAggregator.GetEvent<SetWatermarkEvent>().Publish(new WatermarkInfoUnicode
                {
                    Unicode = Unicode,
                    Status = WatermarkInfo
                });
            }
        }

        private int _isFrontSelectedIndex = 0;
        public int IsFrontSelectedIndex
        {
            get { return _isFrontSelectedIndex; }
            set
            {
                SetProperty(ref _isFrontSelectedIndex, value);
                SetIsFront(IsFrontSelectedIndex);
                eventAggregator.GetEvent<SetWatermarkEvent>().Publish(new WatermarkInfoUnicode
                {
                    Unicode = Unicode,
                    Status = WatermarkInfo
                });
            }
        }

        private bool _isFullValue = false;
        public bool IsFullValue
        {
            get { return _isFullValue; }
            set
            {
                SetProperty(ref _isFullValue, value);
                WatermarkInfo.Isfull = IsFullValue;
                eventAggregator.GetEvent<SetWatermarkEvent>().Publish(new WatermarkInfoUnicode
                {
                    Unicode = Unicode,
                    Status = WatermarkInfo
                });
            }
        }
        private SolidColorBrush _solidColorBrush = null;
        public SolidColorBrush SolidColorBrush
        {
            get
            {
                return _solidColorBrush;
            }
            set
            {

                SetProperty(ref _solidColorBrush, value);
            }
        }

        private Color _stringColor = Color.FromArgb(0xFF, 0xFF, 0x00, 0x00);
        public Color StringColor
        {
            get
            {
                return _stringColor;
            }
            set
            {
                SetProperty(ref _stringColor, value);
                WatermarkInfo.TextColor = EditToolsHelper.ConvertColor(value);
                SolidColorBrush = new SolidColorBrush(_stringColor);
                eventAggregator.GetEvent<SetWatermarkEvent>().Publish(new WatermarkInfoUnicode
                {
                    Unicode = Unicode,
                    Status = WatermarkInfo
                });
            }
        }
        public string _pageRangeText = "0";
        public string PageRangeText
        {
            get { return _pageRangeText; }
            set
            {
                _pageRangeText = value;
                EditToolsHelper.GetPageRange(PageRangeSelectIndex, PDFViewer.Document, ref WatermarkInfo.PageRange, PageRangeText);
                eventAggregator.GetEvent<SetWatermarkEvent>().Publish(new WatermarkInfoUnicode
                {
                    Unicode = Unicode,
                    Status = WatermarkInfo
                });
            }
        }

        private int _pageRangeSelectIndex = 0;
        public int PageRangeSelectIndex
        {
            get { return _pageRangeSelectIndex; }
            set
            {
                SetProperty(ref _pageRangeSelectIndex, value);
                WatermarkInfo.PageRangeIndex = PageRangeSelectIndex;
                EditToolsHelper.GetPageRange(PageRangeSelectIndex, PDFViewer.Document, ref WatermarkInfo.PageRange, PageRangeText);
                eventAggregator.GetEvent<SetWatermarkEvent>().Publish(new WatermarkInfoUnicode
                {
                    Unicode = Unicode,
                    Status = WatermarkInfo
                });
            }
        }

        private ObservableDictionary<string, bool> _getLocationFromNumber = new ObservableDictionary<string, bool>();
        public ObservableDictionary<string, bool> GetLocationFromNumber
        {
            get { return _getLocationFromNumber; }
            set { _getLocationFromNumber = value; }
        }

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

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

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

        public string Unicode = null;

        public WatermarkCreateTextContentViewModel(IEventAggregator eventAggregator)
        {
            this.eventAggregator = eventAggregator;
            Unicode = App.mainWindowViewModel.SelectedItem.Unicode;
            WatermarkInfo.WatermarkType = C_Watermark_Type.WATERMARK_TYPE_TEXT;
            ChangeLocationCommand = new DelegateCommand<object>(ChangeLocation);
            SelectedColorChangedCommand = new DelegateCommand<object>(ChangedColor);
            TextValueChangedCommand = new DelegateCommand<object>(TextValueChanged);

            InitList();
            InitWatermarkInfo();
            InitLocationButtonMatrix();
            eventAggregator.GetEvent<SaveWatermarkTemplateEvent>().Subscribe(SaveWatermarkTemplate, e => e.Unicode == Unicode);
            eventAggregator.GetEvent<ConfirmEditWatermarkTemplateItemEvent>().Subscribe(ConfirmEditWatermarkTemplateItem, e => e.Unicode == Unicode);
        }

        public void SaveWatermarkTemplate(EnumTextOrFileUnicode enumTextOrFileunicode)
        {
            EnumTextOrFile enumTextOrFile = enumTextOrFileunicode.Status;
            if (enumTextOrFile == EnumTextOrFile.StatusText)
            {
                SaveCurrentTemplate();
            }
        }

        public void ConvertInfoToItem(ref WatermarkItem watermarkItem, WatermarkInfo watermarkInfo)
        {
            if (watermarkInfo != null)
            {
                watermarkItem.type = watermarkInfo.WatermarkType;
                watermarkItem.text = watermarkInfo.Text;
                watermarkItem.fontSize = watermarkInfo.TextSize;
                watermarkItem.fontName = watermarkInfo.FontName;
                watermarkItem.textcolor = watermarkInfo.TextColor;
                watermarkItem.horizalign = watermarkInfo.WatermarkHorizalign;
                watermarkItem.vertalign = watermarkInfo.WatermarkVertalign;
                watermarkItem.isFullScreen = watermarkInfo.Isfull;
                watermarkItem.isfront = watermarkInfo.IsFront;
                watermarkItem.opacity = watermarkInfo.Opacity;
                watermarkItem.rotation = watermarkInfo.Rotation;
                watermarkItem.vertOffset = watermarkInfo.VertOffset;
                watermarkItem.horizOffset = watermarkInfo.HorizOffset;
                watermarkItem.verticalSpacing = watermarkInfo.VerticalSpacing;
                watermarkItem.horizontalSpacing = watermarkInfo.HorizontalSpacing;
                watermarkItem.pageRangeIndex = watermarkInfo.PageRangeIndex;
                watermarkItem.pageRange = watermarkInfo.PageRange;
            }
        }

        public void ConvertItemToInfo(WatermarkItem watermarkItem, ref WatermarkInfo watermarkInfo)
        {
            if (watermarkItem != null)
            {
                watermarkInfo.WatermarkType = C_Watermark_Type.WATERMARK_TYPE_TEXT;
                watermarkInfo.Text = watermarkItem.text;
                watermarkInfo.TextSize = watermarkItem.fontSize;
                watermarkInfo.FontName = watermarkItem.fontName;
                watermarkInfo.TextColor = watermarkItem.textcolor;
                watermarkInfo.WatermarkHorizalign = watermarkItem.horizalign;
                watermarkInfo.WatermarkVertalign = watermarkItem.vertalign;
                watermarkInfo.Isfull = watermarkItem.isFullScreen;
                watermarkInfo.IsFront = watermarkItem.isfront;
                watermarkInfo.Opacity = watermarkItem.opacity;
                watermarkInfo.Rotation = watermarkItem.rotation;
                watermarkInfo.VertOffset = watermarkItem.vertOffset;
                watermarkInfo.HorizOffset = watermarkItem.horizOffset;
                watermarkInfo.VerticalSpacing = watermarkItem.verticalSpacing;
                watermarkInfo.HorizontalSpacing = watermarkItem.horizontalSpacing;
                watermarkInfo.PageRangeIndex = watermarkItem.pageRangeIndex;
                EditToolsHelper.GetPageRange(watermarkItem.pageRangeIndex, PDFViewer.Document, ref WatermarkInfo.PageRange, watermarkItem.pageRange);
            }

        }


        public void SaveCurrentTemplate()
        {
            var watermarkItem = new WatermarkItem();
            ConvertInfoToItem(ref watermarkItem, WatermarkInfo);
            watermarkItem.templateName += Settings.Default.WatermarkIndex.ToString();
            try
            {
                //创建缓存文件夹
                string folderPath = Path.Combine(App.CurrentPath, "Watermark");
                //有可能因为其他原因存在同名文件，导致创建文件夹失败，需要先删除同名文件
                //保险措施(猜测)
                if (File.Exists(folderPath))
                {
                    File.Delete(folderPath);
                }

                DirectoryInfo tempfolder = new DirectoryInfo(folderPath);
                if (!tempfolder.Exists)
                {
                    tempfolder.Create();
                }

                //预览图缓存
                string saveName = Guid.NewGuid().ToString();
                string savePath = Path.Combine(folderPath, saveName);
                System.Windows.Size pageSize = new System.Windows.Size { Width = 128, Height = 160 };
                CPDFDocument tempDocument = CPDFDocument.CreateDocument();
                if (tempDocument != null)
                {
                    tempDocument.InsertPage(0, pageSize.Width, pageSize.Height, null);
                    CreateWatermark(tempDocument, WatermarkInfo);
                    //获取透明背景的图片
                    var bitmap = ToolMethod.RenderPageBitmapNoWait(tempDocument, (int)pageSize.Width, (int)pageSize.Height, 0, false, false, 0x00FFFFFF);
                    using (FileStream stream = new FileStream(savePath, FileMode.Create))
                    {
                        bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                    }

                    watermarkItem.previewImagePath = savePath;
                    tempDocument.Release();

                    Settings.Default.WatermarkTemplateList.Add(watermarkItem);
                    Settings.Default.Save();
                }
            }
            catch
            {

            }
            this.eventAggregator.GetEvent<EnterTemplateListOrCreateEvent>().Publish(new EnumTemplateListOrCreateUnicode
            {
                Unicode = Unicode,
                Status = EnumTemplateListOrCreate.StatusTemplate
            });
        }

        private void InitLocationButtonMatrix()
        {
            GetLocationFromNumber.Clear();
            for (var temp = 0; temp <= 22; temp++)
            {
                GetLocationFromNumber.Add(temp.ToString(), true);
                if (temp % 10 == 2)
                {
                    temp += 7;
                }
            }
            int Num = (int)WatermarkInfo.WatermarkVertalign * 10 + (int)WatermarkInfo.WatermarkHorizalign;
            GetLocationFromNumber[Num.ToString()] = false;

        }

        public void ChangeLocation(object e)
        {
            string args = e as string;
            if (args != null)
            {
                WatermarkInfo.WatermarkVertalign = (C_Watermark_Vertalign)(int.Parse(args) / 10);
                WatermarkInfo.WatermarkHorizalign = (C_Watermark_Horizalign)(int.Parse(args) % 10);
                eventAggregator.GetEvent<SetWatermarkEvent>().Publish(new WatermarkInfoUnicode
                {
                    Unicode = Unicode,
                    Status = WatermarkInfo
                });
                InitLocationButtonMatrix();
            }
        }

        private void ChangedColor(object obj)
        {
            if (obj != null)
            {
                var colorValue = (Color)obj;
                if (colorValue != null)
                {

                    StringColor = colorValue;
                }
            }
        }
        private void TextValueChanged(object obj)
        {
            if (obj != null)
            {
                var textValue = obj as System.Windows.Controls.TextBox;
                if (textValue != null)
                {

                    TextValue = textValue.Text;
                    WatermarkInfo.Text = TextValue;
                    eventAggregator.GetEvent<SetWatermarkEvent>().Publish(new WatermarkInfoUnicode
                    {
                        Unicode = Unicode,
                        Status = WatermarkInfo
                    });
                }
            }

        }

        private void SetFontName(int Index)
        {
            WatermarkInfo.FontName = FontNameList[Index];
        }

        private void SetFontSize(int Index)
        {
            if (Index == 0)
            {
                WatermarkInfo.TextSize = 10;
            }
            else
            {
                WatermarkInfo.TextSize = (Index + 7) * 1.33f;
            }
        }

        private void SetIsFront(int Index)
        {
            if (Index == 0)
            {
                WatermarkInfo.IsFront = true;
            }
            if (Index == 1)
            {
                WatermarkInfo.IsFront = false;
            }
        }

        public void ConfirmEditToolsWatermark()
        {
            eventAggregator.GetEvent<SetWatermarkEvent>().Publish(new WatermarkInfoUnicode
            {
                Unicode = Unicode,
                Status = WatermarkInfo
            });
        }

        private void InitList()
        {
            InitOpacityList();
            InitFontNameList();
            InitFontSizeList();
            InitIsFrontList();
            InitRotationList();
            InitScaleList();
        }

        private void InitWatermarkInfo()
        {

            WatermarkInfo.Text = TextValue;
            WatermarkInfo.Rotation = (float)(((float)RotationValue / 180) * Math.PI);
            WatermarkInfo.Opacity = (byte)(((float)OpacityValue / 100) * 225);
            WatermarkInfo.VertOffset = float.Parse(VertOffsetValue);
            WatermarkInfo.HorizOffset = float.Parse(HorizOffsetValue);
            WatermarkInfo.VerticalSpacing = float.Parse(VerticalSpacingValue);
            WatermarkInfo.HorizontalSpacing = float.Parse(HorizontalSpacingValue);
            WatermarkInfo.WatermarkHorizalign = C_Watermark_Horizalign.WATERMARK_HORIZALIGN_CENTER;
            WatermarkInfo.WatermarkVertalign = C_Watermark_Vertalign.WATERMARK_VERTALIGN_CENTER;
            WatermarkInfo.Isfull = IsFullValue;
            SetFontName(FontNameSelectedIndex);
            SetFontSize(FontSizeSelectedIndex);
            SetIsFront(IsFrontSelectedIndex);
            StringColor = Color.FromArgb(0xFF, 0xFF, 0x00, 0x00);
        }

        /// <summary>
        /// 根据已知Info初始化
        /// </summary>
        public void InitComponentBySelectedInfo()
        {
            ConvertItemToInfo(TemplateWatermarkItem, ref WatermarkInfo);
            TextValue = WatermarkInfo.Text;
            VertOffsetValue = WatermarkInfo.VertOffset.ToString();
            HorizOffsetValue = WatermarkInfo.HorizOffset.ToString();
            VerticalSpacingValue = WatermarkInfo.VerticalSpacing.ToString();
            HorizontalSpacingValue = WatermarkInfo.HorizontalSpacing.ToString();
            PageRangeSelectIndex = WatermarkInfo.PageRangeIndex;
            FontNameSelectedIndex = FontNameList.IndexOf(WatermarkInfo.FontName);
            FontSizeSelectedIndex = FontSizeList.IndexOf(((int)(WatermarkInfo.TextSize / 1.33f)).ToString() + "pt");
            IsFrontSelectedIndex = Convert.ToInt32(!WatermarkInfo.IsFront);
            RotationText = ((int)((WatermarkInfo.Rotation/ Math.PI) *180)).ToString();
            OpacityText = ((((float)WatermarkInfo.Opacity)/225)*100).ToString() + " %";
            RelativeScaleText = WatermarkInfo.TextSize.ToString() + " %";
            InitLocationButtonMatrix();

        }
            public void CreateWatermark(CPDFDocument document, WatermarkInfo watermarkInfo)
            {
                if (watermarkInfo != null)
                {
                    document.DeleteWatermarks();
                    CPDFWatermark watermark;
                    if (watermarkInfo.WatermarkType == C_Watermark_Type.WATERMARK_TYPE_TEXT)
                    {
                        watermark = document.InitWatermark(C_Watermark_Type.WATERMARK_TYPE_TEXT);
                        watermark.SetText(watermarkInfo.Text);
                        watermark.SetFontName(watermarkInfo.FontName);
                        watermark.SetFontSize(watermarkInfo.TextSize);
                        watermark.SetTextRGBColor(watermarkInfo.TextColor);
                    }
                    else
                    {
                        watermark = document.InitWatermark(C_Watermark_Type.WATERMARK_TYPE_IMG);
                        if (watermarkInfo.ImageArray != null)
                        {
                            watermark.SetImage(watermarkInfo.ImageArray, watermarkInfo.ImageWidth, watermarkInfo.ImageHeight);
                        }
                        watermark.SetScale(0.1f);
                    }
                    watermark.SetRotation(watermarkInfo.Rotation);
                    watermark.SetOpacity(watermarkInfo.Opacity);
                    watermark.SetFront(watermarkInfo.IsFront);
                    watermark.SetVertalign(watermarkInfo.WatermarkVertalign);
                    watermark.SetHorizalign(watermarkInfo.WatermarkHorizalign);
                    watermark.SetFullScreen(watermarkInfo.Isfull);
                    watermark.SetVertOffset(watermarkInfo.VertOffset);
                    watermark.SetHorizOffset(watermarkInfo.HorizOffset);
                    watermark.SetHorizontalSpacing(watermarkInfo.HorizontalSpacing);
                    watermark.SetVerticalSpacing(watermarkInfo.VerticalSpacing);
                    watermark.SetPages("0");
                    Trace.WriteLine("IsCreateWatermark: " + watermark.CreateWatermark());
                    Trace.WriteLine("IsUpdateWatermark: " + watermark.UpdateWatermark());
                }
            }

            public void ConfirmEditWatermarkTemplateItem(EnumTextOrFileUnicode enumTextOrFileunicode)
            {
                EnumTextOrFile enumTextOrFile = enumTextOrFileunicode.Status;
                if (enumTextOrFile == EnumTextOrFile.StatusText)
                {
                    var watermarkItem = new WatermarkItem();
                    ConvertInfoToItem(ref watermarkItem, WatermarkInfo);
                    try
                    {
                        //创建缓存文件夹
                        string folderPath = Path.Combine(App.CurrentPath, "Watermark");
                        //有可能因为其他原因存在同名文件，导致创建文件夹失败，需要先删除同名文件
                        //保险措施(猜测)
                        if (File.Exists(folderPath))
                        {
                            File.Delete(folderPath);
                        }

                        DirectoryInfo tempfolder = new DirectoryInfo(folderPath);
                        if (!tempfolder.Exists)
                        {
                            tempfolder.Create();
                        }

                        //预览图缓存
                        string saveName = Guid.NewGuid().ToString();
                        string savePath = Path.Combine(folderPath, saveName);
                        System.Windows.Size pageSize = new System.Windows.Size { Width = 128, Height = 160 };
                        CPDFDocument tempDocument = CPDFDocument.CreateDocument();
                        if (tempDocument != null)
                        {
                            tempDocument.InsertPage(0, pageSize.Width, pageSize.Height, null);
                            CreateWatermark(tempDocument, WatermarkInfo);

                            //获取透明背景的图片
                            var bitmap = ToolMethod.RenderPageBitmapNoWait(tempDocument, (int)pageSize.Width, (int)pageSize.Height, 0, false, false, 0x00FFFFFF);
                            using (FileStream stream = new FileStream(savePath, FileMode.Create))
                            {
                                bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                            }

                            watermarkItem.previewImagePath = savePath;
                            tempDocument.Release();

                            Settings.Default.WatermarkTemplateList[TemplateWatermarkItem.listIndex] = watermarkItem;
                            Settings.Default.Save();
                        }
                    }
                    catch
                    {

                    }
                    this.eventAggregator.GetEvent<EnterTemplateListOrCreateEvent>().Publish(new EnumTemplateListOrCreateUnicode
                    {
                        Unicode = Unicode,
                        Status = EnumTemplateListOrCreate.StatusTemplate
                    });

                }
            }

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

            public void OnNavigatedFrom(NavigationContext navigationContext)
            {
            }

            public void OnNavigatedTo(NavigationContext navigationContext)
            {
                navigationContext.Parameters.TryGetValue<CPDFViewer>(ParameterNames.PDFViewer, out PDFViewer);
                EditToolsHelper.GetPageRange(PageRangeSelectIndex, PDFViewer.Document, ref WatermarkInfo.PageRange, PageRangeText);
                if (navigationContext.Parameters.TryGetValue<WatermarkItem>("WatermarkItem", out TemplateWatermarkItem))
                {
                    InitComponentBySelectedInfo();
                }

            }
        }
    }
