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.Shapes;
using System.IO;
using System.Windows.Xps.Packaging;
using System.Threading;
using System.Text.RegularExpressions;

namespace Platform.Print
{
    /// <summary>
    /// PrintPreviewWindow.xaml 的交互逻辑
    /// </summary>
    public partial class PrintPreviewWindow : Window
    {
        #region 字段
        /// <summary>
        /// 打印管理类
        /// </summary>
        private PrintManager _printManager;

        #endregion

        #region Prop
        #region IsEnableFocusControl
        public bool IsEnableFocusControl
        {
            get { return (bool)GetValue(IsEnableFocusControlProperty); }
            set { SetValue(IsEnableFocusControlProperty, value); }
        }

        public static readonly DependencyProperty IsEnableFocusControlProperty =
            DependencyProperty.Register("IsEnableFocusControl", typeof(bool), typeof(PrintPreviewWindow), new UIPropertyMetadata(true));
        #endregion
        #endregion

        #region 方法
        /// <summary>
        /// 初始化打印窗体
        /// </summary>
        /// <param name="xpsFile">要解析的xps文件</param>
        /// <param name="device">打印设备</param>
        /// <param name="isReprint">是否添加补打标记</param>
        public PrintPreviewWindow(FileInfo xpsFile, PrintDevice device, bool isReprint = false)
        {
            InitializeComponent();

            if (xpsFile == null)
                throw new ArgumentNullException("xpsFile");
            _printManager = new PrintManager(xpsFile, device, isReprint);
            Panel_Print.Width = _printManager.PrintElement.Width;
            Panel_Print.Height = _printManager.PrintElement.Height;
            Panel_Print1.Width = _printManager.PrintElement.Width;
            Panel_Print1.Height = _printManager.PrintElement.Height;
            //表单名称
            Text_Title.Text = _printManager.Title;
            //表单描述
            Text_Description.Text = _printManager.Description;
            //背景画刷
            Brush background = Brushes.White;
            if (!string.IsNullOrEmpty(_printManager.Subject))
            {
                try
                {
                    //要求必须使用全局资源作为背景图像
                    if (_printManager.Subject.StartsWith("ImageSource_"))
                    {
                        if (_printManager.Subject.Contains("/RES/"))
                        {
                            String path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "RES", Regex.Split(_printManager.Subject, "/RES/")[1]);
                            if (File.Exists(path))
                            {
                                var ms = new MemoryStream(File.ReadAllBytes(path));
                                //防止内存泄漏,页面关闭时销毁内存流
                                this.Closed += (sender, e) => { ms.Close(); };
                                var imageSource = new BitmapImage();
                                imageSource.BeginInit();
                                imageSource.StreamSource = ms;
                                imageSource.EndInit();
                                background = new ImageBrush(imageSource);
                            }
                        }
                        else
                        {
                            Uri uri = null;
                            if (Uri.TryCreate(_printManager.Subject.Substring(12), UriKind.RelativeOrAbsolute, out uri))
                                background = new ImageBrush(new BitmapImage(uri));
                        }
                    }
                    else if (_printManager.Subject.StartsWith("StaticResource_"))
                    {
                        background = Application.Current.TryFindResource(_printManager.Subject.Substring(15)) as Brush;
                    }
                }
                catch (Exception ex)
                {
                    Platform.Common.LogSystem.PlatformLogger.TradeErrorInfo("背景图转换出错！" + _printManager.Subject, ex);
                    background = Brushes.White;
                }
            }
            if (!_printManager.IsNotingPreview)
            {
                Panel_Print.Background = background;
                _printManager.PrintElement.Background = Brushes.Transparent;
                Panel_Print1.Background = new VisualBrush(_printManager.PrintElement);
            }
            else
            {
                Panel_NotingPreview.Visibility = System.Windows.Visibility.Visible;
                Panel_NotingPreview.Background = background;
            }
        }


        private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
            e.Handled = true;
        }

        private void CancelCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            this.Close();
        }

        private void PrintCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            _printManager.Print();
            this.Close();

        }

        /// <summary>
        /// 是否已经打印
        /// </summary>
        public bool IsPrinted
        {
            get
            {
                return this._printManager.IsPrinted;
            }
        }
        #endregion
    }
}
