using ComPDFKit.PDFDocument;
using ComPDFKitViewer.PdfViewer;
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 PDFSettings;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Media;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace PDF_Office.ViewModels.EditTools.Background
{

    public class BackgroundCreateColorContentViewModel : BindableBase, INavigationAware
    {

        IEventAggregator eventAggregator;
        private CPDFViewer PDFViewer;

        private string RedColorBtn = "RedColorBtn";
        private string GreenColorBtn = "GreenColorBtn";

        private BackgroundItem TemplateBackgroundItem;

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

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

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

        private int _rotationValue = 0;
        public int RotationValue
        {
            get { return _rotationValue; }
            set
            {
                SetProperty(ref _rotationValue, value);
                BackgroundInfo.Rotation = value;
                eventAggregator.GetEvent<SetBackgroundEvent>().Publish(new BackgroundInfoUnicode
                {
                    Unicode = Unicode,
                    Status = BackgroundInfo
                });
            }
        }

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

        private int _relativeRatioValue = 0;
        public int RelativeRatioValue
        {
            get { return _relativeRatioValue; }
            set
            {
                SetProperty(ref _rotationValue, value);
                BackgroundInfo.RelativeRatio = value;
            }
        }

        private string _verticalOffsetValue = "0";
        public string VerticalOffsetValue
        {
            get { return _verticalOffsetValue; }
            set
            {
                SetProperty(ref _verticalOffsetValue, value);
                BackgroundInfo.VertOffset = float.Parse(VerticalOffsetValue);
                eventAggregator.GetEvent<SetBackgroundEvent>().Publish(new BackgroundInfoUnicode
                {
                    Unicode = Unicode,
                    Status = BackgroundInfo
                });
            }
        }

        private string _horizontalOffset = "0";
        public string HorizontalOffsetValue
        {
            get { return _horizontalOffset; }
            set
            {
                SetProperty(ref _horizontalOffset, value);
                BackgroundInfo.HorizOffset = float.Parse(HorizontalOffsetValue);
                eventAggregator.GetEvent<SetBackgroundEvent>().Publish(new BackgroundInfoUnicode
                {
                    Unicode = Unicode,
                    Status = BackgroundInfo
                });
            }
        }

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

        private BackgroundInfo BackgroundInfo = new BackgroundInfo();

        private Color _color = Color.FromArgb(0xFF, 0xFF, 0x00, 0x00);
        public Color Color
        {
            get
            {
                return _color;
            }
            set
            {
                SetProperty(ref _color, value);
                BackgroundInfo.Color = EditToolsHelper.ConvertColor(value);
                eventAggregator.GetEvent<SetBackgroundEvent>().Publish(new BackgroundInfoUnicode
                {
                    Unicode = Unicode,
                    Status = BackgroundInfo
                });
            }
        }

        private string _pageRangeText { get; set; } = "0";
        public string PageRangeText
        {
            get { return _pageRangeText; }
            set
            {
                _pageRangeText = value;
                EditToolsHelper.GetPageRange(PageRangeSelectIndex, PDFViewer.Document, ref BackgroundInfo.PageRange, PageRangeText);
                eventAggregator.GetEvent<SetBackgroundEvent>().Publish(new BackgroundInfoUnicode
                {
                    Unicode = Unicode,
                    Status = BackgroundInfo
                });
            }
        }

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



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

        public string unicode = null;
        public string Unicode = null;

        public BackgroundCreateColorContentViewModel(IEventAggregator eventAggregator)
        {
            this.eventAggregator = eventAggregator;
            Unicode = App.mainWindowViewModel.SelectedItem.Unicode;
            ChangeLocationCommand = new DelegateCommand<object>(ChangeLocation);
            ChangeColorCommand = new DelegateCommand<object>(ChangeColor);
            BackgroundInfo.Color = EditToolsHelper.ConvertColor(Color.FromArgb(0xFF, 0xFF, 0x00, 0x00));
            InitComponent();
            BackgroundInfo.Horizalign = C_Background_Horizalign.BG_HORIZALIGN_CENTER;
            BackgroundInfo.Vertalign = C_Background_Vertalign.BG_VERTALIGN_CENTER;
            InitLocationButtonMatrix();
            eventAggregator.GetEvent<SaveBackgroundTemplateEvent>().Subscribe(SaveBackgroundTemplate, e => e.Unicode == Unicode);
            eventAggregator.GetEvent<ConfirmEditBackgroundTemplateItemEvent>().Subscribe(ConfirmEditBackgroundTemplateItem, e => e.Unicode == Unicode);
        }

        public void InitComponent()
        {
            InitOpacityList();
            InitRotationList();
            InitRelativeRatioList();
        }

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

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

        private void InitRelativeRatioList()
        {
            RelativeRatioList.Clear();
            for (int defaultRelativeRatioList = 10; defaultRelativeRatioList <= 100; defaultRelativeRatioList += 10)
            {
                RelativeRatioList.Add(defaultRelativeRatioList.ToString() + " %");
            }
        }

        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)BackgroundInfo.Vertalign * 10 + (int)BackgroundInfo.Horizalign;
            GetLocationFromNumber[Num.ToString()] = false;
        }

        public void ChangeLocation(object e)
        {
            string args = e as string;
            if (args != null)
            {
                BackgroundInfo.Vertalign = (C_Background_Vertalign)(int.Parse(args) / 10);
                BackgroundInfo.Horizalign = (C_Background_Horizalign)(int.Parse(args) % 10);
                eventAggregator.GetEvent<SetBackgroundEvent>().Publish(new BackgroundInfoUnicode
                {
                    Unicode = Unicode,
                    Status = BackgroundInfo
                });
                InitLocationButtonMatrix();
            }
        }


        public void ChangeColor(object e)
        {
            if (e != null)
            {
                var colorValue = (Color)e;
                if (colorValue != null)
                {
                    Color = colorValue;
                }
            }
        }

        public void ConvertInfoToItem(ref BackgroundItem backgroundItem, BackgroundInfo backgroundInfo)
        {
            if (backgroundItem != null)
            {
                backgroundItem.type = backgroundInfo.BackgroundType;
                backgroundItem.bgColor = backgroundInfo.Color;
                backgroundItem.horizalign = backgroundInfo.Horizalign;
                backgroundItem.vertalign = backgroundInfo.Vertalign;
                backgroundItem.vertOffset = backgroundInfo.VertOffset;
                backgroundItem.horizalign = backgroundInfo.Horizalign;
                backgroundItem.opacity = backgroundInfo.Opacity;
                backgroundItem.rotation = backgroundInfo.Rotation;
                backgroundItem.scale = backgroundInfo.Scale;
                backgroundItem.PageRangeIndex = backgroundInfo.PageRangeIndex;
                backgroundItem.pageRange = backgroundInfo.PageRange;
                backgroundItem.scale = backgroundInfo.Scale;
            }

        }

        public void SaveCurrentTemplate()
        {
            var backgroundItem = new BackgroundItem();
            ConvertInfoToItem(ref backgroundItem, BackgroundInfo);
            backgroundItem.templateName += Settings.Default.WatermarkIndex.ToString();
            try
            {
                //创建缓存文件夹
                string folderPath = Path.Combine(App.CurrentPath, "Background");
                //有可能因为其他原因存在同名文件，导致创建文件夹失败，需要先删除同名文件
                //保险措施(猜测)
                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 = PDFViewer.Document.GetPageSize(0);
                CPDFDocument tempDocument = CPDFDocument.CreateDocument();
                if (tempDocument != null)
                {
                    tempDocument.InsertPage(0, pageSize.Width, pageSize.Height, null);
                    var tempBackground = tempDocument.GetBackground();
                    tempBackground.SetBackgroundType(BackgroundInfo.BackgroundType);
                    tempBackground.SetColor(BackgroundInfo.Color);
                    tempBackground.SetScale(1);
                    tempBackground.SetRotation(BackgroundInfo.Rotation);
                    tempBackground.SetOpacity(BackgroundInfo.Opacity);
                    tempBackground.SetVertalign(BackgroundInfo.Vertalign);
                    tempBackground.SetHorizalign(BackgroundInfo.Horizalign);
                    tempBackground.SetXOffset(BackgroundInfo.HorizOffset);
                    tempBackground.SetYOffset(BackgroundInfo.VertOffset);
                    tempBackground.SetPages(BackgroundInfo.PageRange);
                    tempBackground.SetAllowsPrint(true);
                    tempBackground.SetAllowsView(true);
                    tempBackground.Update();

                    //获取透明背景的图片
                    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);
                    }

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

                    Settings.Default.BackgroundTemplateList.Add(backgroundItem);
                    Settings.Default.Save();
                }
            }
            catch
            {

            }

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

        public void ConvertItemToInfo(BackgroundItem backgroundItem, ref BackgroundInfo backgroundInfo)
        {
            if (backgroundItem != null)
            {
                backgroundInfo.BackgroundType = backgroundItem.type;
                backgroundInfo.Color = backgroundItem.bgColor;
                backgroundInfo.Horizalign = backgroundItem.horizalign;
                backgroundInfo.Vertalign = backgroundItem.vertalign;
                backgroundInfo.VertOffset = backgroundItem.vertOffset;
                backgroundInfo.Horizalign = backgroundItem.horizalign;
                backgroundInfo.Opacity = backgroundItem.opacity;
                backgroundInfo.Rotation = backgroundItem.rotation;
                backgroundInfo.Scale = backgroundItem.scale;
                backgroundInfo.PageRangeIndex = backgroundItem.PageRangeIndex;
                backgroundInfo.PageRange = backgroundItem.pageRange;
            }
        }

        /// <summary>
        /// 根据已知Info初始化
        /// </summary>
        public void InitComponentBySelectedInfo()
        {
            ConvertItemToInfo(TemplateBackgroundItem, ref BackgroundInfo);
            Color = EditToolsHelper.ConvertColor(BackgroundInfo.Color);
            RotationValue = (int)BackgroundInfo.Rotation;
            InitLocationButtonMatrix();
            HorizontalOffsetValue = (BackgroundInfo.HorizOffset).ToString();
            VerticalOffsetValue = (BackgroundInfo.VertOffset).ToString();
        }

        public void ConfirmEditBackgroundTemplateItem(EnumColorOrFileUnicode enumColorOrFileunicode)
        {
            EnumColorOrFile enumColorOrFile = enumColorOrFileunicode.Status;
            if (enumColorOrFile == EnumColorOrFile.StatusColor)
            {
                var backgroundItem = new BackgroundItem();
                ConvertInfoToItem(ref backgroundItem, BackgroundInfo);
                try
                {
                    //创建缓存文件夹
                    string folderPath = Path.Combine(App.CurrentPath, "Background");
                    //有可能因为其他原因存在同名文件，导致创建文件夹失败，需要先删除同名文件
                    //保险措施(猜测)
                    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 = PDFViewer.Document.GetPageSize(0);
                    CPDFDocument tempDocument = CPDFDocument.CreateDocument();
                    if (tempDocument != null)
                    {
                        tempDocument.InsertPage(0, pageSize.Width, pageSize.Height, null);
                        var tempBackground = tempDocument.GetBackground();
                        tempBackground.SetBackgroundType(BackgroundInfo.BackgroundType);
                        tempBackground.SetColor(BackgroundInfo.Color);
                        tempBackground.SetScale(1);
                        tempBackground.SetRotation(BackgroundInfo.Rotation);
                        tempBackground.SetOpacity(BackgroundInfo.Opacity);
                        tempBackground.SetVertalign(BackgroundInfo.Vertalign);
                        tempBackground.SetHorizalign(BackgroundInfo.Horizalign);
                        tempBackground.SetXOffset(BackgroundInfo.HorizOffset);
                        tempBackground.SetYOffset(BackgroundInfo.VertOffset);
                        tempBackground.SetPages(BackgroundInfo.PageRange);
                        tempBackground.SetAllowsPrint(true);
                        tempBackground.SetAllowsView(true);
                        tempBackground.Update();

                        //获取透明背景的图片
                        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);
                        }

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

                        Settings.Default.BackgroundTemplateList[TemplateBackgroundItem.listIndex] = backgroundItem;
                        Settings.Default.Save();
                    }
                }
                catch
                {

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


        public void SaveBackgroundTemplate(EnumColorOrFileUnicode enumColorOrFileunicode)
        {
            EnumColorOrFile enumColorOrFile = enumColorOrFileunicode.Status;
            if (enumColorOrFile == EnumColorOrFile.StatusColor)
            {
                SaveCurrentTemplate();
            }
        }
        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);
            if (navigationContext.Parameters.TryGetValue<BackgroundItem>("BackgroundItem", out TemplateBackgroundItem))
            {
                InitComponentBySelectedInfo();
            }
        }
    }
}
