using ComPDFKit.PDFAnnotation;
using ComPDFKitViewer;
using ComPDFKitViewer.AnnotEvent;
using ComPDFKitViewer.PdfViewer;
using PDF_Master.CustomControl.CompositeControl;
using PDF_Master.Helper;
using PDF_Master.Model;
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.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;

namespace PDF_Master.ViewModels.Form
{

    public class ListBoxPropertyViewModel : FormBaseVM, INavigationAware
    {
        #region Command变量
        public DelegateCommand<string> FieldNameTextChangedCommand { get; set; }
        public DelegateCommand<string> ToolTipTextChangedCommand { get; set; }

        //外观

        public DelegateCommand<object> ResetColorCommand { get; set; }
        public DelegateCommand<object> ResetColorCheckedBtnCommand { get; set; }

        public DelegateCommand<string> FormContentTextChangedCommand { get; set; }

        public DelegateCommand<object> LineStyleCommand { get; set; }
        //选项
        public DelegateCommand<object> AddOptionCommand { get; set; }
        public DelegateCommand<object> RemoveOptionCommand { get; set; }
        public DelegateCommand<object> UpItemOptionCommand { get; set; }
        public DelegateCommand<object> DownItemOptionCommand { get; set; }
        public DelegateCommand<string> OptionKeyTextChangedCommand { get; set; }

        public DelegateCommand<string> OptionKeyValueTextChangedCommand { get; set; }
        public DelegateCommand<object> OptionSelectionChangedCommand { get; set; }
        #endregion

        #region 变量
        private CPDFViewer PDFViewer;
        private WidgetListBoxArgs listBoxArgs;
        private IDialogService dialogs;
        public event EventHandler<int> SelectResetColorBtnHandler;
        public List<ComboDataItem> FontFamilyItems { get; private set; }
        public List<ComboDataItem> FontStyleItems { get; private set; }
        public List<ComboDataItem> AglinmentItems { get; private set; }
        public ObservableCollection<ComboDataItem> OptionItems { get; private set; }

        #endregion


        #region 初始化
        public ListBoxPropertyViewModel(IDialogService dialogService)
        {
            dialogs = dialogService;
            InitVariable();
            InitCommand();
        }

        private void InitVariable()
        {

            InitAllResetColor();
            InitFontFamilyComboBox();
            InitFontStyleComboBox();
            InitAglinmentItemsComboBox();
            InitOptionItems();
        }

        private void InitOptionItems()
        {
            OptionItems = new ObservableCollection<ComboDataItem>();
            OptionItems.CollectionChanged -= OptionItems_CollectionChanged;
            OptionItems.CollectionChanged += OptionItems_CollectionChanged;
        }

        private void OptionItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (OptionItems.Count == 0)
                IsRemoveOption = false;
        }

        private void InitAllResetColor()
        {
            ResetColorOne = InitResetColor(Color.FromArgb(0xFF, 0x00, 0x00, 0x00), Color.FromArgb(0xFF, 0x00, 0x00, 0x00), Colors.Transparent);

            ResetColorTwo = InitResetColor(Color.FromArgb(0xFF, 0xC2, 0xC2, 0xC2), Color.FromArgb(0xFF, 0x00, 0x00, 0x00), Color.FromArgb(0xFF, 0xFF, 0xFF, 0xFF));

            ResetColorThree = InitResetColor(Color.FromArgb(0xFF, 0xff, 0xff, 0xff), Color.FromArgb(0xFF, 0xFB, 0x18, 0x18), Color.FromArgb(0xFF, 0xFF, 0xFF, 0xFF));

            ResetColorForth = InitResetColor(Color.FromArgb(0xFF, 0xff, 0xff, 0xff), Color.FromArgb(0xFF, 0x18, 0xA0, 0xFB), Color.FromArgb(0xFF, 0xff, 0xff, 0xff));
        }

        private void InitFontFamilyComboBox()
        {
            FontFamilyItems = new List<ComboDataItem>();
            ComboDataItem item = new ComboDataItem("Courier", "Courier New");
            FontFamilyItems.Add(item);
            item = new ComboDataItem("Helvetica", "Helvetica");
            FontFamilyItems.Add(item);
            item = new ComboDataItem("Times-Roman", "Times New Roman");
            FontFamilyItems.Add(item);
        }

        private void InitFontStyleComboBox()
        {
            FontStyleItems = new List<ComboDataItem>();
            ComboDataItem item = new ComboDataItem("Regular", "Regular");
            FontStyleItems.Add(item);
            item = new ComboDataItem("Bold", "Bold");
            FontStyleItems.Add(item);
            item = new ComboDataItem("Italic", "Italic");
            FontStyleItems.Add(item);

            item = new ComboDataItem("Bold Italic", "Bold Italic");
            FontStyleItems.Add(item);
        }

        private void InitAglinmentItemsComboBox()
        {
            AglinmentItems = new List<ComboDataItem>();
            ComboDataItem item = new ComboDataItem("Left", "Left");
            AglinmentItems.Add(item);
            item = new ComboDataItem("Center", "Center");
            AglinmentItems.Add(item);
            item = new ComboDataItem("Right", "Right");
            AglinmentItems.Add(item);
        }

        private void InitCommand()
        {
            //一般
            FieldNameTextChangedCommand = new DelegateCommand<string>(FieldNameTextChanged);
            ToolTipTextChangedCommand = new DelegateCommand<string>(ToolTipTextChanged);
            //外观
            ResetColorCheckedBtnCommand = new DelegateCommand<object>(ResetColorCheckedBtn);
            ResetColorCommand = new DelegateCommand<object>(ResetColorEvent);
            LineStyleCommand = new DelegateCommand<object>(LineStyleBtnEvent);

            //选项
            FormContentTextChangedCommand = new DelegateCommand<string>(FormContentTextChanged);
            AddOptionCommand = new DelegateCommand<object>(AddOption);
            RemoveOptionCommand = new DelegateCommand<object>(RemoveOption);
            UpItemOptionCommand = new DelegateCommand<object>(UpItemOption);
            DownItemOptionCommand = new DelegateCommand<object>(DownItemOption);
            OptionKeyTextChangedCommand = new DelegateCommand<string>(OptionKeyTextChanged);
            OptionKeyValueTextChangedCommand = new DelegateCommand<string>(OptionKeyValueTextChanged);
            OptionSelectionChangedCommand = new DelegateCommand<object>(OptionSelectionChanged);
        }

        #endregion


        #region 事件


        private void FieldNameTextChanged(string obj)
        {
            if (string.IsNullOrEmpty(obj) == false && IsCurrentWidget == true)
            {
                FieldName = obj;

            }
        }

        private void ToolTipTextChanged(string obj)
        {
            if (string.IsNullOrEmpty(obj) == false && IsCurrentWidget == true)
            {
                ToolTipStr = obj;
            }
        }


        private void LineStyleBtnEvent(object obj)
        {
            if (obj != null)
            {
                switch ((string)obj)
                {
                    case "Solid":
                        BorderStyle = ComPDFKit.PDFAnnotation.C_BORDER_STYLE.BS_SOLID;
                        break;
                    case "Dotted":
                        BorderStyle = ComPDFKit.PDFAnnotation.C_BORDER_STYLE.BS_DASHDED;
                        break;
                }
            }
        }


        private void FormContentTextChanged(string obj)
        {
            if (obj != null && IsCurrentWidget == true)
            {
                FormContent = obj;
            }
        }


        private void OptionKeyValueTextChanged(string obj)
        {
            if (string.IsNullOrEmpty(obj) == false && IsCurrentWidget == true)
            {
                OptionKeyValue = obj;
            }
            UpdateIsInputOption();
        }

        private void OptionKeyTextChanged(string obj)
        {
            if (string.IsNullOrEmpty(obj) == false && IsCurrentWidget == true)
            {
                OptionKey = obj;
            }

            UpdateIsInputOption();
        }

        private void OptionSelectionChanged(object obj)
        {
            if (obj != null && obj is int == true)
            {
                UpdateAllOptionBtn((int)obj);
            }

        }

        //刷新所有Option有关的按钮状态
        private void UpdateAllOptionBtn(int SelectedIndex)
        {
            var count = OptionItems.Count;
            if (SelectedIndex <= -1)
            {
                IsDownOption = false;
                IsUpOption = false;
                IsRemoveOption = false;
            }
            else
            {
                IsRemoveOption = true;
                IsUpOption = SelectedIndex == 0 ? false : true;
                IsDownOption = (SelectedIndex == count - 1) ? false : true;
            }
            OptionSelectedIndex = SelectedIndex;
        }

        //Option是否可输入内容
        private void UpdateIsInputOption()
        {
            if (string.IsNullOrEmpty(OptionKeyValue) || string.IsNullOrEmpty(OptionKey))
            {
                IsInputOption = false;
            }
            else
            {
                foreach (var item in OptionItems)
                {
                    if (item.ValueStr == OptionKeyValue || item.Content == OptionKey)
                    {
                        IsInputOption = false;
                        return;
                    }
                }

                IsInputOption = true;
            }
        }
        //新增Option项
        private void AddOption(object obj)
        {

            if (string.IsNullOrEmpty(OptionKey) || string.IsNullOrEmpty(OptionKeyValue))
                return;

            var item = new ComboDataItem(OptionKeyValue, OptionKey);
            OptionItems.Add(item);
            OptionsList[item.Content] = item.ValueStr;
            ChangeValue(AnnotAttrib.ListOptions, OptionsList);
            OptionKey = "";
            OptionKeyValue = "";
            UpdateAllOptionBtn(OptionSelectedIndex);
        }
        //移除Option项
        private void RemoveOption(object obj)
        {
            if (obj != null)
            {
                var item = (ComboDataItem)obj;
                OptionsList.Remove(item.Content);
                OptionItems.Remove(item);
                ChangeValue(AnnotAttrib.ListOptions, OptionsList);
                UpdateAllOptionBtn(-1);
            }
        }
        //向下移项
        private void DownItemOption(object obj)
        {
            if (obj != null)
            {
                var item = (ComboDataItem)obj;
                var index = OptionItems.IndexOf(item);
                if (index < OptionItems.Count - 1)
                {
                    OptionItems.Move(index, index + 1);
                    UpdateAllOptionBtn(index + 1);
                    OptionsList.Clear();
                    foreach (var itemOption in OptionItems)
                    {
                        OptionsList[itemOption.Content] = itemOption.ValueStr;
                    }
                    ChangeValue(AnnotAttrib.ListOptions, OptionsList);
                }
            }
        }
        //向上移项
        private void UpItemOption(object obj)
        {
            if (obj != null)
            {
                var item = (ComboDataItem)obj;
                var index = OptionItems.IndexOf(item);
                if (index > 0)
                {
                    OptionItems.Move(index, index - 1);
                    UpdateAllOptionBtn(index - 1);
                    OptionsList.Clear();
                    foreach (var itemOption in OptionItems)
                    {
                        OptionsList[itemOption.Content] = itemOption.ValueStr;
                    }
                    ChangeValue(AnnotAttrib.ListOptions, OptionsList);
                }
            }
        }


        private void ResetColorCheckedBtn(object obj)
        {
            if (obj != null)
            {
                var str = obj as string;
                if (str != null)
                {
                    switch (str)
                    {
                        case "One":
                            BorderColor = ResetColorOne.BorderColor.Color;
                            ContentColor = ResetColorOne.FontColor.Color;
                            FillColor = ResetColorOne.FillColor.Color;
                            break;

                        case "Two":
                            BorderColor = ResetColorTwo.BorderColor.Color;
                            ContentColor = ResetColorTwo.FontColor.Color;
                            FillColor = ResetColorTwo.FillColor.Color;
                            break;

                        case "Three":
                            BorderColor = ResetColorThree.BorderColor.Color;
                            ContentColor = ResetColorThree.FontColor.Color;
                            FillColor = ResetColorThree.FillColor.Color;
                            break;

                        case "Forth":
                            BorderColor = ResetColorForth.BorderColor.Color;
                            ContentColor = ResetColorForth.FontColor.Color;
                            FillColor = ResetColorForth.FillColor.Color;
                            break;
                    }
                }
            }
        }

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


        #endregion

        #region 外部XAML触发事件

        private void UpdataSelectResetColorBtn()
        {
            int result = 0;
            if (UpdataSelectResetColor(ResetColorOne))
            {
                result = 1;
            }
            else if (UpdataSelectResetColor(ResetColorTwo))
            {
                result = 2;
            }
            else if (UpdataSelectResetColor(ResetColorThree))
            {
                result = 3;
            }
            else if (UpdataSelectResetColor(ResetColorForth))
            {
                result = 4;
            }

            SelectResetColorBtnHandler?.Invoke(null, result);
        }

        private bool UpdataSelectResetColor(ResetColor reset)
        {
            if (reset.FillColor.Color == FillColor &&
                reset.FontColor.Color == ContentColor &&
                reset.BorderColor.Color == BorderColor
                )
            {
                return true;
            }

            return false;
        }
        #endregion

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

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
            listBoxArgs = null;
            ClearVMData();
            PDFViewer.AnnotEditHandler -= PDFViewer_AnnotEditHandler;
        }

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            navigationContext.Parameters.TryGetValue<CPDFViewer>(ParameterNames.PDFViewer, out PDFViewer);
            navigationContext.Parameters.TryGetValue<WidgetListBoxArgs>("WidgetArgs", out listBoxArgs);
            navigationContext.Parameters.TryGetValue<UpdateAttributeHelper>(ParameterNames.AnnotEvent, out AttribEvent);
            PDFViewer.AnnotEditHandler -= PDFViewer_AnnotEditHandler;
            PDFViewer.AnnotEditHandler += PDFViewer_AnnotEditHandler;

            OptionsList = new Dictionary<string, string>();

            GetWidgeText();
            UpdataSelectResetColorBtn();
        }

        private void PDFViewer_AnnotEditHandler(object sender, List<AnnotEditEvent> e)
        {
            if (e != null && e.Count > 0)
            {

                var widgeArgs = e[e.Count - 1].EditAnnotArgs as WidgetArgs;
                if (widgeArgs != null)
                {
                    AnnotEditEvent editEvent = e[e.Count - 1];
                    if (editEvent.EditAction == ActionType.Modify)
                    {
                        SetSizeNoUpdateValue(widgeArgs.Width, widgeArgs.Height);
                    }
                }
            }
        }

        private void GetWidgeText()
        {
         
            if (listBoxArgs == null)
            {
                PDFViewer.SetMouseMode(MouseModes.FormEditTool);
                listBoxArgs = new WidgetListBoxArgs();
                listBoxArgs.BgColor = Colors.White;
                listBoxArgs.FontName = "Courier New";
                listBoxArgs.FontSize = 12;
                listBoxArgs.FontColor = Colors.Black;
                listBoxArgs.LineColor = Colors.Black;
                listBoxArgs.LineWidth = 2;
                listBoxArgs.Width = 100;
                listBoxArgs.Height = 72;

                PDFViewer.SetToolParam(listBoxArgs);
                isCreateWidget = true;
            }
            else
            {
                PDFViewer.SetToolParam(new AnnotHandlerEventArgs());
                isCreateWidget = false;
            }

            GetProperty();

            IsCurrentWidget = true;

        }

        private void GetProperty()
        {
            if (listBoxArgs != null)
            {
                IsLocked = listBoxArgs.Locked;
                FieldName = listBoxArgs.FieldName;
                ToolTipStr = listBoxArgs.Tooltip;
                IsReadOnly = listBoxArgs.ReadOnly;

                FillColor = listBoxArgs.BgColor;
                ContentColor = listBoxArgs.FontColor;
                BorderColor = listBoxArgs.LineColor;
                BorderThiness = listBoxArgs.LineWidth;
                BorderStyle = listBoxArgs.BorderStyle;

                string fontWeightStyleStr = "";
                if (listBoxArgs.IsItalic == false)
                {
                    if (listBoxArgs.IsBold == false)
                    {
                        fontWeightStyleStr = "Regular";
                    }
                    else
                    {
                        fontWeightStyleStr = "Bold";
                    } 
                }
                else
                {
                    if (listBoxArgs.IsBold == false)
                    {
                        fontWeightStyleStr = "Italic";
                    }
                    else
                    {
                        fontWeightStyleStr = "Bold Italic";
                    }
                        
                }
                FontWeightStyleItem = new ComboDataItem(fontWeightStyleStr);

                FontFamilyData = new ComboDataItem(listBoxArgs.FontName);
                //避免BorderStyle跟上一个值相同,而没触发更改IsSolid属性
                if (BorderStyle == C_BORDER_STYLE.BS_SOLID)
                    IsSolid = true;
                else
                    IsSolid = false;
                FontSizeData = new ComboDataItem(listBoxArgs.FontSize);
                if (isCreateWidget == false)
                {
                    HeightSize = listBoxArgs.Height;
                    WidthSize = listBoxArgs.Width;
                }

                OptionsList = listBoxArgs.ListOptions;
                OptionItems.Clear();
                foreach (string key in OptionsList.Keys)
                {
                    var item = new ComboDataItem(OptionsList[key], key);
                    OptionItems.Add(item);
                }

                if (isCreateWidget == false)
                {
                    HeightSize = listBoxArgs.Height;
                    WidthSize = listBoxArgs.Width;
                }

            }
        }
        #endregion
    }
}