using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.ComponentModel;
using System.Drawing;
using Platform.Common.RunningParameters;
using System.Globalization;

namespace Platform.Controls.ComponentContainer
{
    /// <summary>
    /// RtfEditorBox.xaml 的交互逻辑
    /// </summary>    
    public partial class RtfEditorBox : UserControl
    {

        /// <summary>
        /// 记录文本格式
        /// </summary>
        private string _txtType = null;
        /// <summary>
        /// 初始化RtfEditorBox
        /// </summary>
        public RtfEditorBox()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 文本编辑框Loaded事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RtfEditor_Loaded(object sender, RoutedEventArgs e)
        {
            RichTextControl.Width = this.Width;
            RichTextControl.Document.PageWidth = RichTextControl.MaxWidth;
            //文本选中区域
            TextRange range = new TextRange(RichTextControl.Selection.Start, RichTextControl.Selection.End);            
            //默认字体
            Fonttype.SelectedValue = range.GetPropertyValue(FlowDocument.FontFamilyProperty).ToString();
            //默认字体大小
            Fontheight.SelectedValue = range.GetPropertyValue(FlowDocument.FontSizeProperty).ToString();
            RichTextControl.Focus();

        }

        public string text
        {
            get
            {
                TextRange range = new TextRange(RichTextControl.Document.ContentStart, RichTextControl.Document.ContentEnd);
                return range.Text;
            }
            set
            {
                _txtType = value;
            }
        }
        /// <summary>
        /// 打开对话框，加载文本文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ToolStripButtonOpen_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            // 初始化对话框
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.FileName = ""; // 默认文件的名称
            dlg.DefaultExt = ".rtf"; //默认文件的扩展名
            dlg.Filter = "RichText documents (.rtf)|*.rtf|Text documents (.txt)|*.txt"; // 过滤文件的后缀名
            // 显示文本对话框
            dlg.ValidateNames = true;
            dlg.CheckFileExists = true;
            dlg.CheckPathExists = true;

            Nullable<bool> result = dlg.ShowDialog();

            // 打开文件返回的值
            if (result == true)
            {
                string path = dlg.FileName;
                TextRange range;
                FileStream fStream;
                var filter = path.Substring(path.LastIndexOf('.') + 1, 3);
                if (filter == "txt" || filter == "rtf")
                {
                    if (File.Exists(path))
                    {
                        range = new TextRange(RichTextControl.Document.ContentStart, RichTextControl.Document.ContentEnd);

                        if (filter == "rtf")
                        {
                            fStream = new FileStream(path, FileMode.OpenOrCreate);
                            range.Load(fStream, DataFormats.Rtf);
                            fStream.Close();
                        }
                        if (filter == "txt")
                        {
                            using (StreamReader read = new StreamReader(path, PlatformSettings.Encoding))
                            {
                                RichTextControl.AppendText(read.ReadToEnd());
                            }
                        }

                    }
                }
                else
                {

                    MessageBox.Show("不支持" + filter + "格式,请重新选择支持的格式", "提示框");
                    return;
                }

            }
            RichTextControl.Focus();
        }
        /// <summary>
        /// 删除线
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ToolStripButtonStrikeout_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            TextRange range = new TextRange(RichTextControl.Selection.Start, RichTextControl.Selection.End);

            TextDecorationCollection tdc = (TextDecorationCollection)RichTextControl.Selection.GetPropertyValue(Inline.TextDecorationsProperty);

            if (tdc == null || !tdc.Equals(TextDecorations.Strikethrough))
            {
                tdc = TextDecorations.Strikethrough;

            }
            else
            {
                tdc = new TextDecorationCollection();
            }
            range.ApplyPropertyValue(Inline.TextDecorationsProperty, tdc);

        }

        /// <summary>
        /// 文本前景色事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ToolStripButtonTextcolor_Click(object sender, RoutedEventArgs e)
        {
            ColorDialog colorDialog = new ColorDialog();
            if ((bool)colorDialog.ShowDialog())
            {
                TextRange range = new TextRange(RichTextControl.Selection.Start, RichTextControl.Selection.End);

                range.ApplyPropertyValue(FlowDocument.ForegroundProperty, new SolidColorBrush(colorDialog.SelectedColor));
            }
            RichTextControl.Focus();
        }

        /// <summary>
        /// 文本背景色事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ToolStripButtonBackcolor_Click(object sender, RoutedEventArgs e)
        {
            ColorDialog colorDialog = new ColorDialog();
            if ((bool)colorDialog.ShowDialog())
            {
                TextRange range = new TextRange(RichTextControl.Selection.Start, RichTextControl.Selection.End);

                range.ApplyPropertyValue(FlowDocument.BackgroundProperty, new SolidColorBrush(colorDialog.SelectedColor));
            }
            RichTextControl.Focus();
        }

        /// <summary>
        /// 字体大小更改事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Fontheight_DropDownClosed(object sender, EventArgs e)
        {
            string fontHeight = (string)Fontheight.SelectedItem;

            if (fontHeight != null)
            {
                RichTextControl.Selection.ApplyPropertyValue(System.Windows.Controls.RichTextBox.FontSizeProperty, fontHeight);
            }
            RichTextControl.Focus();
        }

        /// <summary>
        /// 字体格式更改事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Fonttype_DropDownClosed(object sender, EventArgs e)
        {
            string fontName = (string)Fonttype.SelectedItem;

            if (fontName != null)
            {
                RichTextControl.Selection.ApplyPropertyValue(System.Windows.Controls.RichTextBox.FontFamilyProperty, fontName);
            }
            RichTextControl.Focus();
        }
        private void RichTextControl_TextChanged(object sender, TextChangedEventArgs e)
        {
            RichTextControl.Focus();
        }
        private void AdjustWidth()
        {
            Rect rectStart = RichTextControl.Document.ContentStart.GetCharacterRect(LogicalDirection.Forward);
            Rect rectEnd = RichTextControl.Document.ContentEnd.GetCharacterRect(LogicalDirection.Forward);
            var width = rectEnd.Right - rectStart.Left;
            var mywidth = Math.Min(RichTextControl.MaxWidth, width);
            if (mywidth > this.Width)
            {
                RichTextControl.Document.PageWidth = mywidth;
            }
        }

      

      
     


        /// <summary>
        /// RichTextControl_KeyDown事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RichTextControl_KeyDown(object sender, KeyEventArgs e)
        {
            string fontName = (string)Fonttype.SelectedValue;
            string fontHeight = (string)Fontheight.SelectedValue;
            TextRange range = new TextRange(RichTextControl.Selection.Start, RichTextControl.Selection.End);

            if (!string.IsNullOrEmpty(fontName))
            {
                range.ApplyPropertyValue(TextElement.FontFamilyProperty, fontName);
            }
            if (!string.IsNullOrEmpty(fontHeight))
            {
                range.ApplyPropertyValue(TextElement.FontSizeProperty, fontHeight);
            }

        }

        /// <summary>
        ///  打开对话框快捷键
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RichTextControl_KeyUp(object sender, KeyEventArgs e)
        {
            // Ctrl + O
            if ((Keyboard.Modifiers == ModifierKeys.Control) && (e.Key == Key.O))
            {
                ToolStripButtonOpen_Click(sender, e);
            }
        }

        /// <summary>
        /// 清空文本框
        /// </summary>
        public void Clear()
        {
            RichTextControl.Document.Blocks.Clear();
        }

        /// <summary>
        /// 设置Rtf文本文件
        /// </summary>
        /// <param name="rtf"></param>
        public void SetRTF(string rtf)
        {
            TextRange range = new TextRange(RichTextControl.Document.ContentStart, RichTextControl.Document.ContentEnd);
            try
            {
                using (MemoryStream rtfMemoryStream = new MemoryStream())
                {
                    using (StreamWriter rtfStreamWriter = new StreamWriter(rtfMemoryStream))
                    {

                        rtfStreamWriter.Write(rtf);
                        rtfStreamWriter.Flush();
                        rtfMemoryStream.Seek(0, SeekOrigin.Begin);
                        range.Load(rtfMemoryStream, DataFormats.Rtf);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 得到trf文本文件
        /// </summary>
        /// <returns></returns>
        public string GetRTF()
        {
            TextRange range = new TextRange(RichTextControl.Document.ContentStart, RichTextControl.Document.ContentEnd);
            try
            {
                using (MemoryStream rtfMemoryStream = new MemoryStream())
                {
                    using (StreamWriter rtfStreamWriter = new StreamWriter(rtfMemoryStream))
                    {
                        range.Save(rtfMemoryStream, DataFormats.Rtf);

                        rtfMemoryStream.Flush();
                        rtfMemoryStream.Position = 0;
                        StreamReader sr = new StreamReader(rtfMemoryStream);
                        return sr.ReadToEnd();
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        public void HideToorBar()
        {
            toolBarPanel.Visibility = Visibility.Collapsed;
        }
    }
}
