using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using Platform.Common.BasicFunctions;
using Platform.Controls.ControlsHelper;
using Platform.Controls.TableContainer;
using Platform.Controls.TradeExtension;
using Platform.Hotkeys;
using Platform.Presentation.FocusManagers;
using Platform.Presentation.Interfaces;
using Platform.Common.RunningParameters;

namespace Platform.Controls.ComponentContainer
{
    /// <summary>
    /// DataBox.xaml 的交互逻辑
    /// </summary>
    public partial class DataBox : UserControl, INotifyPropertyChanged
    {
        DataGridTemplateColumn colRadioColumn;
        DataGridTemplateColumn colCheckColumn;
        bool isDone; //控制是否触发LostFocus

        //2013-8-14
        Grid grid;
        Popup popDataDetails;

        public DataBox()
        {
            InitializeComponent();
            this.KeyDown += (sender, e) =>
            {
                var focusManager = Platform.Presentation.FocusManagers.FocusManager
                 .GetManagerInstance(dhccDataGrid);
                if (focusManager != null) return;
                //补充非焦点控制模式下的快捷键
                if (e.Key == Key.S && HotKeyHelper.IsControl)
                {
                    ShowDataBoxItem();
                }
            };
            txtFilter.PreviewKeyDown += txtFilter_PreviewKeyDown;
            dhccDataGrid.LoadingRow += dhccDataGrid_LoadingRow;
            dhccDataGrid.PreviewMouseDoubleClick += dhccDataGrid_PreviewMouseDoubleClick;
            Platform.Presentation.FocusManagers.FocusManager.AddPreviewLostFocusHandler(dhccDataGrid, dhccDataGrid_PreviewLostFocus);

            dhccDataGrid.Loaded += new RoutedEventHandler(dhccDataGrid_Loaded);

            cbxFilter.Loaded += new RoutedEventHandler(cbxFilter_Loaded);

            interval.AutoReset = true;
            interval.Elapsed += interval_Elapsed;

            EventHandler mouseHandler = (sender, e) =>
            {
                var focusManager = Platform.Presentation.FocusManagers.FocusManager
                    .GetManagerInstance(dhccDataGrid);
                if (focusManager == null) return;

                var flg = focusManager.MoveFocusElement(dhccDataGrid);

                if (!flg)
                {
                    InputEventArgs args = e as InputEventArgs;
                    if (args != null) args.Handled = true;
                }
            };

            Platform.Presentation.FocusManagers.FocusManager
                .SetOnlyMouseControlHandled(txtFilter, mouseHandler);

            Platform.Presentation.FocusManagers.FocusManager
                .SetOnlyMouseControlHandled(cbxFilter, mouseHandler);

            Platform.Presentation.FocusManagers.FocusManager
                .SetOnlyMouseControlHandled(btnClear, mouseHandler);

            Platform.Presentation.FocusManagers.FocusManager
               .SetOnlyMouseControlHandled(btnPrint, mouseHandler);

            Platform.Presentation.FocusManagers.FocusManager
            .SetOnlyMouseControlHandled(btnExport, mouseHandler);

            //dhccDataGrid.SelectionUnit = DataGridSelectionUnit.CellOrRowHeader;

            #region FocusHandled

            Platform.Presentation.FocusManagers.FocusManager
                .SetFocusHandled(dhccDataGrid, (sender, e) =>
            {
                if (this.dhccDataGrid.ScrollViewer == null ||
                    this.dhccDataGrid.FocusManager == null) return FocusHandledResult.Forward;

                FocusHandledResult result = FocusHandledResult.Self;

                //键盘控制提示关闭 
                if (popDataDetails != null)
                {
                    if (popDataDetails.IsOpen == true)
                    {
                        popDataDetails.IsOpen = false;
                    }
                }

                #region 2013-8-24 柜员自定义快捷键DataBox部分功能配置（全选，全清，显示提示，隐藏提示，DataBox打印）
                var pressKey = HotKeyHelper.GetKeyName(e.Key);
                #endregion

                if (txtFilter.IsKeyboardFocused)
                {
                    return FocusHandledResult.Self;
                }

                if (this.dhccDataGrid.Items.Count == 0)
                {
                    if (e.Key == Key.Up || (e.Key == Key.Tab && HotKeyHelper.IsShift) ||
                        (e.Key == Key.K && this.dhccDataGrid.IsReadOnly))
                    {
                        result = FocusHandledResult.Backward;
                    }
                    else
                    {
                        result = FocusHandledResult.Forward;
                    }
                }
                else if (e.Key == Key.Up)
                {
                    if (HotKeyHelper.IsControl)
                    {
                        this.dhccDataGrid.ScrollViewer.LineUp();
                    }
                    else if (HotKeyHelper.IsShift)
                    {
                        this.dhccDataGrid.ScrollViewer.PageUp();
                    }
                    else
                    {
                        if (this.dhccDataGrid.SelectedIndex > 0)
                        {
                            this.dhccDataGrid.SelectedIndex--;
                            this.dhccDataGrid.ScrollIntoView(this.dhccDataGrid.Items[this.dhccDataGrid.SelectedIndex]);
                        }
                        else
                        {
                            if (IsShowPageBar)
                            {
                                if (dataPager.PageIndex > 1)
                                {
                                    dataPager.PageIndex--;
                                }
                                else
                                {
                                    if (dataPager.Total % dataPager.PageSize != 0)
                                    {
                                        dataPager.PageCount = dataPager.Total / dataPager.PageSize + 1;
                                    }
                                    else
                                    {
                                        dataPager.PageCount = dataPager.Total / dataPager.PageSize;
                                    }
                                    dataPager.PageIndex = dataPager.PageCount;
                                }

                                dataPager.RaisePageChanged();
                            }

                            if (this.dhccDataGrid.SelectedIndex == 0 && !IsShowPageBar)
                            {
                                result = FocusHandledResult.Backward;
                            }
                            else
                            {
                                this.dhccDataGrid.ScrollViewer.ScrollToEnd();
                                this.dhccDataGrid.SelectedIndex = this.dhccDataGrid.Items.Count - 1;
                            }
                        }
                    }
                }
                else if (e.Key == Key.Down)
                {
                    if (HotKeyHelper.IsControl)
                    {
                        this.dhccDataGrid.ScrollViewer.LineDown();
                    }
                    else if (HotKeyHelper.IsShift)
                    {
                        this.dhccDataGrid.ScrollViewer.PageDown();
                    }
                    else
                    {
                        if (this.dhccDataGrid.SelectedIndex < this.dhccDataGrid.Items.Count - 1)
                        {
                            this.dhccDataGrid.SelectedIndex++;
                            this.dhccDataGrid.ScrollIntoView(this.dhccDataGrid.Items[this.dhccDataGrid.SelectedIndex]);
                        }
                        else
                        {
                            if (IsShowPageBar)
                            {
                                if (dataPager.Total % dataPager.PageSize != 0)
                                {
                                    dataPager.PageCount = dataPager.Total / dataPager.PageSize + 1;
                                }
                                else
                                {
                                    dataPager.PageCount = dataPager.Total / dataPager.PageSize;
                                }

                                if (dataPager.PageIndex < dataPager.PageCount)
                                {
                                    dataPager.PageIndex++;
                                }
                                else
                                {
                                    dataPager.PageIndex = 1;
                                }
                                dataPager.RaisePageChanged();
                            }
                            this.dhccDataGrid.ScrollViewer.ScrollToHome();
                            this.dhccDataGrid.SelectedIndex = 0;
                        }
                    }
                }
                else if (e.Key == Key.Left)
                {
                    if (this.dhccDataGrid.IsReadOnly || HotKeyHelper.IsControl)
                    {
                        this.dhccDataGrid.ScrollViewer.LineLeft();
                    }
                    else if (HotKeyHelper.IsShift)
                    {
                        this.dhccDataGrid.ScrollViewer.PageLeft();
                    }
                    else
                    {
                        //编辑状态移动焦点
                    }
                }
                else if (e.Key == Key.Right)
                {
                    if (this.dhccDataGrid.IsReadOnly || HotKeyHelper.IsControl)
                    {
                        this.dhccDataGrid.ScrollViewer.LineRight();
                    }
                    else if (HotKeyHelper.IsShift)
                    {
                        this.dhccDataGrid.ScrollViewer.PageRight();
                    }
                    else
                    {
                        //编辑状态移动焦点
                    }
                }
                else if (e.Key == Key.Tab)
                {
                    if (HotKeyHelper.IsShift)
                    {
                        result = FocusHandledResult.Backward;
                    }
                    else if (this.dhccDataGrid.IsReadOnly)
                    {
                        result = FocusHandledResult.Forward;
                    }
                    else
                    {
                        //编辑状态点击Tab键
                    }
                }
                else if (e.Key == Key.Escape)
                {
                    ////增加ESC关闭窗口的处理方式（关闭对话框）翟国栋（数据行为空时，ESC可关闭窗口）2013-3-9
                    //if (this.dhccDataGrid.Items.Count == 0)
                    //{
                    var element = this.FindVisualTreeAncestor(d => d is Platform.Controls.TradeExtension.PageDialog);
                    if (element != null)
                    {
                        if (MessageBox.Show("将关闭当前操作窗口,是否确认关闭操作？", "提示信息", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                        {
                            Platform.Controls.TradeExtension.PageDialog.flagEsc = true;
                            ((Platform.Controls.TradeExtension.PageDialog)element).Close();
                        }
                    }
                    else
                    {
                        result = FocusHandledResult.Backward;
                    }
                    //}
                    //else
                    //{
                    //    //南琦原来的处理
                    //    result = FocusHandledResult.Backward;
                    //}
                }
                else if (e.Key == Key.PageUp)
                {
                    this.dhccDataGrid.ScrollViewer.PageUp();
                }
                else if (e.Key == Key.PageDown)
                {
                    this.dhccDataGrid.ScrollViewer.PageDown();
                }
                else if (e.Key == Key.Home)
                {
                    this.dhccDataGrid.ScrollViewer.ScrollToHome();
                    this.dhccDataGrid.SelectedIndex = 0;
                }
                else if (e.Key == Key.End)
                {
                    this.dhccDataGrid.ScrollViewer.ScrollToEnd();
                    this.dhccDataGrid.SelectedIndex = this.dhccDataGrid.Items.Count - 1;
                }
                else if (e.Key == Key.Enter)
                {
                    if (this.dhccDataGrid.SelectedItem != null)
                    {
                        isDone = true;
                        result = FocusHandledResult.Forward;
                        //交易界面焦点继续2013-8-10翟国栋 对话框关闭处理
                        Platform.Controls.TradeExtension.PageDialog.flagEsc = false;

                    }
                }
                //复制当前行内容
                else if (e.Key == Key.C && HotKeyHelper.IsControl)
                {
                    var drv = this.dhccDataGrid.SelectedItem as DataRowView;

                    if (drv != null && drv.Row != null)
                    {
                        string clipText = string.Join("|", drv.Row.ItemArray);
                        Clipboard.SetDataObject(clipText);
                    }
                }
                //复制当前选中单元格内容
                else if (e.Key == Key.X && HotKeyHelper.IsControl)
                {
                    var drv = this.dhccDataGrid.SelectedItem as DataRowView;
                    if (drv != null && drv.Row != null && this.dhccDataGrid.CurrentColumn != null)
                    {
                        string clipText = drv[this.dhccDataGrid.CurrentColumn.Header.ToString()].ToString();
                        Clipboard.SetDataObject(clipText);
                    }
                }
                //展现详细的行数据
                else if (e.Key == Key.S && HotKeyHelper.IsControl)
                {
                    ShowDataBoxItem();
                }
                ///VIM Move start
                else if ((e.Key == Key.J && this.dhccDataGrid.IsReadOnly)/* || (e.Key == Key.N && HotKeyHelper.IsControl)*/)
                {
                    if (this.dhccDataGrid.SelectedIndex < this.dhccDataGrid.Items.Count - 1)
                    {
                        this.dhccDataGrid.SelectedIndex++;
                        this.dhccDataGrid.ScrollIntoView(this.dhccDataGrid.Items[this.dhccDataGrid.SelectedIndex]);
                    }
                    else
                    {
                        if (IsShowPageBar)
                        {
                            if (dataPager.Total % dataPager.PageSize != 0)
                            {
                                dataPager.PageCount = dataPager.Total / dataPager.PageSize + 1;
                            }
                            else
                            {
                                dataPager.PageCount = dataPager.Total / dataPager.PageSize;
                            }

                            if (dataPager.PageIndex < dataPager.PageCount)
                            {
                                dataPager.PageIndex++;
                            }
                            else
                            {
                                dataPager.PageIndex = 0;
                            }
                            dataPager.RaisePageChanged();
                        }
                        this.dhccDataGrid.ScrollViewer.ScrollToHome();
                        this.dhccDataGrid.SelectedIndex = 0;
                    }
                }
                else if ((e.Key == Key.K && this.dhccDataGrid.IsReadOnly)/* || (e.Key == Key.P && HotKeyHelper.IsControl)*/)
                {
                    if (this.dhccDataGrid.SelectedIndex > 0)
                    {
                        this.dhccDataGrid.SelectedIndex--;
                        this.dhccDataGrid.ScrollIntoView(this.dhccDataGrid.Items[this.dhccDataGrid.SelectedIndex]);
                    }
                    else
                    {
                        if (IsShowPageBar)
                        {
                            if (dataPager.PageIndex > 1)
                            {
                                dataPager.PageIndex--;
                            }
                            else
                            {
                                if (dataPager.Total % dataPager.PageSize != 0)
                                {
                                    dataPager.PageCount = dataPager.Total / dataPager.PageSize + 1;
                                }
                                else
                                {
                                    dataPager.PageCount = dataPager.Total / dataPager.PageSize;
                                }
                                dataPager.PageIndex = dataPager.PageCount;
                            }

                            dataPager.RaisePageChanged();
                        }

                        this.dhccDataGrid.ScrollViewer.ScrollToEnd();
                        this.dhccDataGrid.SelectedIndex = this.dhccDataGrid.Items.Count - 1;
                    }
                }
                else if ((e.Key == Key.H && this.dhccDataGrid.IsReadOnly) || (e.Key == Key.B && HotKeyHelper.IsControl))
                {
                    this.dhccDataGrid.ScrollViewer.LineLeft();
                }
                else if ((e.Key == Key.L && this.dhccDataGrid.IsReadOnly) || (e.Key == Key.F && HotKeyHelper.IsControl))
                {
                    this.dhccDataGrid.ScrollViewer.LineRight();
                }
                else if ((e.Key == Key.D6 && HotKeyHelper.IsShift))
                {
                    this.dhccDataGrid.ScrollViewer.ScrollToLeftEnd();
                }
                else if ((e.Key == Key.D4 && HotKeyHelper.IsShift) || (e.Key == Key.E && HotKeyHelper.IsControl))
                {
                    this.dhccDataGrid.ScrollViewer.ScrollToRightEnd();
                }
                else if (e.Key == Key.D && HotKeyHelper.IsControl)
                {
                    this.dhccDataGrid.ScrollViewer.PageDown();
                }
                else if (e.Key == Key.U && HotKeyHelper.IsControl)
                {
                    this.dhccDataGrid.ScrollViewer.PageUp();
                }
                else if (e.Key == Key.G && HotKeyHelper.IsShift)
                {
                    this.dhccDataGrid.ScrollViewer.ScrollToEnd();
                    this.dhccDataGrid.SelectedIndex = this.dhccDataGrid.Items.Count - 1;
                }
                ///VIM Move end
                //2013-8-24 柜员配置定位查询    
                else if (pressKey == "SEARCHTRADE")
                {
                    this.txtFilter.Focus();
                    e.Handled = true;
                }

                ///Choose Columns Controling
                else if (e.Key == Key.Space && _isMultiSelected)
                {
                    var row = dhccDataGrid.GetSelectedRow();
                    if (row != null) DataGridHelper.SetIsChecked(row, !DataGridHelper.GetIsChecked(row) ?? false);
                }

                ///Print
                //else if (e.Key == Key.P)
                //{
                //    if (dhccDataGrid.IsReadOnly || HotKeyHelper.IsControl)
                //    {
                //        btnPrint.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent, btnPrint));
                //    }
                //}
                else if (pressKey == "BOXPRINT")
                {
                    btnPrint.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent, btnPrint));
                }

                //全选 2013-08-13 全选/全清
                //2013 - 8-24 自定义快捷键修改
                else if (pressKey == "SELECTALL")
                {
                    if (dhccDataGrid.Columns[0].Header == null)
                    {
                        chbxAll.IsChecked = true;
                        dhccDataGrid.Rows().ToList().ForEach(dgr => DataGridHelper.SetIsChecked(dgr, true));
                    }
                }
                else if (pressKey == "UNSELECTALL")
                {
                    if (dhccDataGrid.Columns[0].Header == null)
                    {
                        chbxAll.IsChecked = false;
                        dhccDataGrid.Rows().ToList().ForEach(dgr => DataGridHelper.SetIsChecked(dgr, false));
                    }

                }
                //提示消息的显示与隐藏
                else if (pressKey == "SHOWTIP" || pressKey == "HIDTIP")
                {
                    var row = dhccDataGrid.GetSelectedRow();
                    RowsPreviewKeyDown(row, pressKey);
                }

                Predicate<KeyEventArgs> tmpHoykey = System.Threading.Interlocked.CompareExchange(
                    ref _hotkeyControlEvent, null, null);

                if (tmpHoykey != null && !tmpHoykey(e))
                    e.Handled = true;

                if (dhccDataGrid.IsReadOnly)
                {
                    e.Handled = true;
                }

                return result;
            });
            #endregion
        }

        private void ShowDataBoxItem()
        {
            try
            {
                if (ConfigManager.GetInstance().GetConfigValue("DataBoxShowItem", ConfigType.System) == "True")
                {
                    //获取数据
                    var drv = this.dhccDataGrid.SelectedItem as DataRowView;
                    if (drv != null && drv.Row != null)
                    {
                        var list = new List<Tuple<string, string>>();
                        this.dhccDataGrid.Columns.ToList().ForEach(x =>
                        {
                            if (x.Visibility != Visibility.Visible || x.Header == null)
                                return;
                            var title = x.Header.ToString();
                            var cell = x.GetCellContent(drv);
                            if (cell is TextBlock)
                                list.Add(new Tuple<string, string>(title, (cell as TextBlock).Text));
                            else if (cell is ComboBox)
                                list.Add(new Tuple<string, string>(title, (cell as ComboBox).Text));
                        });
                        //呈现数据
                        var dialog = new PageDialog();
                        var target = this.FindVisualTreeAncestor(x => x is IPage) as IPage;
                        if (target != null)
                        {
                            dialog.Open(target, new DataBoxItem(list), "详细信息");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Platform.Common.LogSystem.PlatformLogger.SystemErrorInfo("DataBox:ShowDataBoxItem触发失败！", ex);
            }
        }

        void dhccDataGrid_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            FrameworkElement originalSourceElement = e.OriginalSource as FrameworkElement;
            var clickedElement = originalSourceElement.FindVisualTreeAncestor(d =>
                       d is DataGridCell ||
                       d is DataGridCellsPanel ||
                       d is DataGridRow) as FrameworkElement;

            if (clickedElement == null) return;

            var focusManager = Platform.Presentation.FocusManagers.FocusManager
                .GetManagerInstance(dhccDataGrid);
            if (focusManager == null) return;

            isDone = true;
            focusManager.MoveFocus(Presentation.FocusManagers.FocusNavigation.Forward);

            e.Handled = true;
        }

        void dhccDataGrid_PreviewLostFocus(object sender, RoutedEventArgs e)
        {
            //var args = new RoutedEventArgs { RoutedEvent = Platform.Presentation.FocusManagers.FocusManager.LostFocusEvent };
            //dhccDataGrid.RaiseEvent(args);

            //var focusManager = Platform.Presentation.FocusManagers.FocusManager
            //   .GetManagerInstance(dhccDataGrid);
            //if (focusManager == null) return;

            //if (!isDone)
            //{
            //    focusManager.MoveFocus(Presentation.FocusManagers.FocusNavigation.Forward, false);
            //    focusManager.IsFocusContinue = false;
            //}
            //else if (_isCustomShow && isDone)
            //{
            //    var args = new RoutedEventArgs { RoutedEvent = Platform.Presentation.FocusManagers.FocusManager.LostFocusEvent };
            //    dhccDataGrid.RaiseEvent(args);

            //    DataBox.ShowCommand.Execute(null, null);
            //    focusManager.IsFocusContinue = false;
            //}
        }

        void dhccDataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.Header = e.Row.GetIndex() + 1;
        }

        void txtFilter_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            isKeyEvent = true;

            //如果在筛选框上点击ESC或者Enter,则设置焦点到DataGrid上
            if (e.Key == Key.Escape || e.Key == Key.Enter)
            {
                dhccDataGrid.Focus();
                if (this.dhccDataGrid.Items.Count == 0)
                {
                    if (dhccDataGrid.FocusManager != null)
                        this.dhccDataGrid.FocusManager.MoveFocus(FocusNavigation.Forward);
                }
                else
                {
                    if (dhccDataGrid.ScrollViewer != null)
                        this.dhccDataGrid.ScrollViewer.ScrollToHome();
                    this.dhccDataGrid.SelectedIndex = 0;
                }

                e.Handled = true;//切换焦点的时候阻止路由,这里可能会再修改
            }
            //这里用来过滤一些可能出错的符号'\之类
            else if (e.Key == Key.Oem7 || e.Key == Key.Oem4 || e.Key == Key.Oem6)
            {
                e.Handled = true;
            }
        }

        #region Public

        /// <summary>
        /// 数据绑定
        /// </summary>
        /// <param name="dtSource"></param>
        public void DataBinding(DataTable dtSource)
        {
            if (dtSource == null) return;

            _dtSource = dtSource;

            if (IsShowPageBar)
            {
                Total = _dtSource.Rows.Count;
                dataPager.PageIndex = 1;
                dataPager.RaisePageChanged();
            }
            else
            {
                BindData(_dtSource.DefaultView);
            }

            if (!string.IsNullOrEmpty(txtFilter.Text))
            {
                interval.Stop();
                interval.Start();
            }
        }

        /// <summary>
        /// 打印按钮点击事件
        /// </summary>
        public event RoutedEventHandler PrintButtonClick
        {
            add
            {
                btnPrint.Click += value;
            }
            remove
            {
                btnPrint.Click -= value;
            }
        }

        /// <summary>
        /// 打印按钮点击事件
        /// </summary>
        public event RoutedEventHandler ExportButtonClick
        {
            add
            {
                btnExport.Click += value;
            }
            remove
            {
                btnExport.Click -= value;
            }
        }

        event Predicate<KeyEventArgs> _hotkeyControlEvent;
        /// <summary>
        /// 快捷键控制
        /// </summary>
        public event Predicate<KeyEventArgs> HotkeyControlEvent
        {
            add
            {
                _hotkeyControlEvent += value;
            }
            remove
            {
                _hotkeyControlEvent -= value;
            }
        }

        #endregion

        #region FocusManager

        /// <summary>
        /// 当DataGrid失去焦点的时候,让DataBox也失去焦点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dhccDataGrid_LostFocus(object sender, RoutedEventArgs e)
        {
            this.RaiseEvent(e);
            isDone = false;
            isKeyEvent = false;
            interval.Close();
        }

        #endregion

        #region Filter

        /*
         *  对于筛选进行缓冲处理
         */
        Timer interval = new Timer(400);
        bool isKeyEvent;

        void interval_Elapsed(object sender, ElapsedEventArgs e)
        {
            interval.Stop();
            isKeyEvent = false;
            this.Dispatcher.BeginInvoke(new Action(() =>
            {
                string text = txtFilter.Text;

                IEnumerable<string> columns = null;

                if (checkListBox.HasItems)
                {
                    columns = checkListBox.Items.Cast<ListBoxItem>()
                        .Where(item => item.IsSelected)
                        .Select(item => item.Tag.ToString());
                }

                if (_dtSource.DefaultView.Filter(text, columns))
                {
                    if (IsShowPageBar)
                    {
                        Total = _dtSource.DefaultView.Count;
                        dataPager.PageIndex = 1;
                        dataPager.RaisePageChanged();

                    }
                }
                else
                    txtFilter.Clear(); //筛选出错清空筛选框
            }));
        }

        private void txt_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (txtFilter.Text.Length > 0)
            {
                btnClear.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                btnClear.Visibility = System.Windows.Visibility.Collapsed;
            }

            if (_dtSource == null || _dtSource.Rows.Count == 0) return;

            if (isKeyEvent)
            {
                interval.Stop();
                interval.Start();
            }
        }

        private void btnClear_Click(object sender, RoutedEventArgs e)
        {
            txtFilter.Clear();

            if (_dtSource == null || _dtSource.Columns.Count == 0)
            {
                return;
            }

            interval.Stop();
            interval.Start();
        }

        #region cbxFilter

        CheckBox chbxAll;
        ListBox checkListBox;

        void cbxFilter_Loaded(object sender, RoutedEventArgs e)
        {
            chbxAll = cbxFilter.Template.FindName("chbxAll", cbxFilter) as CheckBox;
            checkListBox = cbxFilter.Template.FindName("checkListBox", cbxFilter) as ListBox;

            cbxFilter.DropDownOpened += new EventHandler(cbxFilter_DropDownOpened);
            cbxFilter.PreviewMouseDown += new MouseButtonEventHandler(cbxFilter_PreviewMouseDown);
        }

        void cbxFilter_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("cbxFilter");
        }

        void cbxFilter_DropDownOpened(object sender, EventArgs e)
        {
            OpenFilterList();
        }

        private void OpenFilterList()
        {
            if (!checkListBox.HasItems)
            {
                foreach (DataGridColumn column in dhccDataGrid.Columns)
                {
                    if (column is DataGridTextColumn
                     && column.Visibility == System.Windows.Visibility.Visible
                     && column.Header is string
                     && !string.IsNullOrEmpty(column.SortMemberPath))
                    {
                        ListBoxItem item = new ListBoxItem();
                        item.Content = column.Header;
                        item.Tag = column.SortMemberPath;
                        item.IsSelected = true;

                        checkListBox.Items.Add(item);

                        cbxFilter.Items.Add(item.ToString());
                    }
                }
            }
        }

        private void checkListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            chbxAll.IsChecked = checkListBox.SelectedItems.Count == 0 ? false :
               checkListBox.SelectedItems.Count == checkListBox.Items.Count ? (bool?)true : null;

            interval.Stop();
            interval.Start();
        }

        private void chbxAll_Checked(object sender, RoutedEventArgs e)
        {
            checkListBox.SelectAll();
        }

        private void chbxAll_Unchecked(object sender, RoutedEventArgs e)
        {
            checkListBox.UnselectAll();
        }

        #endregion

        #endregion

        #region Property

        /// <summary>
        /// 获取DataBoxBase对象
        /// </summary>
        public DHCCDataGrid DataBoxHost
        {
            get
            {
                return dhccDataGrid;
            }
        }

        /// <summary>
        /// 获取txtFilter对象
        /// </summary>
        public TextBox FilterTextBox
        {
            get
            {
                return txtFilter;
            }
        }

        DataTable _dtSource;

        /// <summary>
        /// 获取数据源
        /// </summary>
        public DataTable DataSource
        {
            get { return _dtSource; }
        }

        private int _total;

        /// <summary>
        /// 获取总数据数
        /// </summary>
        public int Total
        {
            get { return _total; }
            private set
            {
                _total = value;
                RaisePropertyChanged("Total");
            }
        }

        /// <summary>
        /// 获取或设置每页显示多少条(10,20,30)
        /// </summary>
        public string PageSizeList
        {
            get { return dataPager.PageSizeList; }
            set
            {
                dataPager.PageSizeList = value;
                RaisePropertyChanged("PageSizeList");
            }
        }

        private bool _isShowPageBar;

        /// <summary>
        /// 获取或设置是否显示分页条
        /// </summary>
        public bool IsShowPageBar
        {
            get
            {
                return _isShowPageBar;
            }
            set
            {
                if (_isShowPageBar != value)
                {
                    _isShowPageBar = value;
                    RaisePropertyChanged("IsShowPageBar");

                    if (_dtSource == null) return;

                    if (_isShowPageBar)
                    {
                        Total = _dtSource.Rows.Count;

                        dataPager.RaisePageChanged();
                    }
                    else
                    {
                        BindData(_dtSource.DefaultView);
                    }

                    interval_Elapsed(null, null);
                }
            }
        }

        private bool _isShowSelectBar = true;

        /// <summary>
        /// 获取或设置是否显示搜索条
        /// </summary>
        public bool IsShowSelectBar
        {
            get
            {
                return _isShowSelectBar;
            }
            set
            {
                if (_isShowSelectBar != value)
                {
                    _isShowSelectBar = value;
                    RaisePropertyChanged("IsShowSelectBar");
                }
            }
        }

        private bool _isShowRadioColumn;

        /// <summary>
        /// 获取或设置是否显示单选列
        /// </summary>
        public bool IsShowRadioColumn
        {
            get { return _isShowRadioColumn; }
            set
            {
                if (_isShowRadioColumn != value)
                {
                    _isShowRadioColumn = value;
                    RaisePropertyChanged("IsShowRadioColumn");

                    IsVirtualizing = true;//单选时,始终支持虚拟化
                }

                if (value && colRadioColumn == null)
                {
                    colRadioColumn = this.Resources["RadioColumn"] as DataGridTemplateColumn;
                    colRadioColumn.Header = "选择";

                    colRadioColumn.CellTemplate = this.Resources["RadioButtonColumn"] as DataTemplate;
                }
            }
        }

        private bool _isShowPrintButton;

        /// <summary>
        /// 获取或设置是否显示打印按钮
        /// </summary>
        public bool IsShowPrintButton
        {
            get
            {
                return _isShowPrintButton;
            }
            set
            {
                _isShowPrintButton = value;
                RaisePropertyChanged("IsShowPrintButton");
            }
        }

        private bool _isShowExportButton;

        /// <summary>
        /// 获取或设置是否显示打印按钮
        /// </summary>
        public bool IsShowExportButton
        {
            get
            {
                return _isShowExportButton;
            }
            set
            {
                _isShowExportButton = value;
                RaisePropertyChanged("IsShowExportButton");
            }
        }

        private bool _isMultiSelected;

        /// <summary>
        /// 获取或设置是否选择多行
        /// </summary>
        public bool IsMultiSelected
        {
            get
            {
                return _isMultiSelected;
            }
            set
            {
                if (_isMultiSelected != value)
                {
                    _isMultiSelected = value;
                    RaisePropertyChanged("IsMultiSelected");

                    IsVirtualizing = !value;//多选框出现的时候,不虚拟化
                }

                if (value && colCheckColumn == null)
                {
                    colCheckColumn = new DataGridTemplateColumn();
                    colCheckColumn.HeaderTemplate = this.Resources["CheckBoxColumnHeader"] as DataTemplate;
                    colCheckColumn.CellTemplate = this.Resources["CheckBoxColumn"] as DataTemplate;
                }
            }
        }

        /// <summary>
        /// 获取或设置DataGrid的选择模式
        /// </summary>
        public DataGridSelectionMode SelectionMode
        {
            get { return dhccDataGrid.SelectionMode; }
            set
            {
                if (dhccDataGrid.SelectionMode != value)
                {
                    dhccDataGrid.SelectionMode = value;
                    RaisePropertyChanged("SelectionMode");
                }
            }
        }


        /// <summary>
        /// 获取或设置是否开启虚拟化
        /// </summary>
        public bool IsVirtualizing
        {
            get
            {
                return VirtualizingStackPanel.GetIsVirtualizing(dhccDataGrid);
            }
            set
            {
                VirtualizingStackPanel.SetIsVirtualizing(dhccDataGrid, value);
            }
        }

        private object _showContent;

        /// <summary>
        /// 设置显示内容
        /// </summary>
        public object ShowContent
        {
            set { _showContent = value; }
        }

        private bool _isCustomShow;

        /// <summary>
        /// 获取或设置是否自定义显示方式
        /// </summary>
        public bool IsCustomShow
        {
            get { return _isCustomShow; }
            set { _isCustomShow = value; }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        public void RaisePropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler tmp = System.Threading.Interlocked.CompareExchange(
                ref PropertyChanged, null, null);
            if (tmp != null)
            {
                tmp(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion

        #region private

        /// <summary>
        /// Pager Use LINQ Skip and Take
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void dataPager_PageChanged(object sender, PageChangedEventArgs args)
        {
            if (_dtSource == null) return;

            var rows = _dtSource.DefaultView
                .Cast<DataRowView>()
                .Skip((args.PageIndex - 1) * args.PageSize)
                .Take(args.PageSize);

            BindData(new System.Collections.ObjectModel.ObservableCollection<DataRowView>(rows));

            DataGridHelper.SetIsChecked(dhccDataGrid, false);
        }

        void BindData(IEnumerable source)
        {
            dhccDataGrid.Columns.Clear();

            if (_isMultiSelected && colCheckColumn != null)
            {
                dhccDataGrid.Columns.Insert(0, colCheckColumn);
            }
            else if (_isShowRadioColumn && colRadioColumn != null)
            {
                dhccDataGrid.Columns.Insert(0, colRadioColumn);
            }

            dhccDataGrid.SetItemsSource(source);
        }

        private void headerCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            dhccDataGrid.Rows().ToList().ForEach(dgr => DataGridHelper.SetIsChecked(dgr, true));
        }

        private void headerCheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            dhccDataGrid.Rows().ToList().ForEach(dgr => DataGridHelper.SetIsChecked(dgr, false));
        }

        private void cellCheckBox_CheckedChanged(object sender, RoutedEventArgs e)
        {
            var countChecked = dhccDataGrid.Rows()
                .Where(dgr => DataGridHelper.GetIsChecked(dgr) ?? false).Count();
            bool? isChecked = countChecked == 0 ? false :
                    countChecked == dhccDataGrid.Items.Count ? (bool?)true : null;

            DataGridHelper.SetIsChecked(dhccDataGrid, isChecked);
        }

        #endregion

        #region Show

        void dhccDataGrid_Loaded(object sender, RoutedEventArgs e)
        {
            if (!_isCustomShow) return;

            ScrollViewer scroll = dhccDataGrid.Template.FindName("DG_ScrollViewer", dhccDataGrid) as ScrollViewer;
            if (scroll == null) return;

            Button btnShow = scroll.Template.FindName("DataGridButton", scroll) as Button;
            if (btnShow == null) return;

            Style style = this.TryFindResource("DataGridShowButton") as Style;
            if (style == null) return;

            btnShow.Command = ShowCommand;
            btnShow.Style = style;
        }

        public static readonly RoutedCommand ShowCommand;

        static DataBox()
        {
            DataBox.ShowCommand = new RoutedCommand("Show", typeof(DataBox));
            Type typeFromHandle = typeof(DataBox);
            CommandManager.RegisterClassInputBinding(typeFromHandle, new InputBinding(DataBox.ShowCommand,
                new KeyGesture(Key.F3)));
            CommandManager.RegisterClassCommandBinding(typeFromHandle, new CommandBinding(DataBox.ShowCommand,
                new ExecutedRoutedEventHandler(DataBox.OnExecutedShow),
                new CanExecuteRoutedEventHandler(DataBox.OnCanExecuteShow)));
        }

        private static void OnExecutedShow(object sender, ExecutedRoutedEventArgs e)
        {
            ((DataBox)sender).OnExecutedShow(e);
        }

        private static void OnCanExecuteShow(object sender, CanExecuteRoutedEventArgs e)
        {
            ((DataBox)sender).OnCanExecuteShow(e);
        }

        protected virtual void OnExecutedShow(ExecutedRoutedEventArgs e)
        {
            if (_showContent == null) return;

            FrameworkElement fe = _showContent as FrameworkElement;
            if (fe != null)
            {
                DependencyObject d = fe.Parent;
                if (d == null) return;

                if (d is ContentControl)
                {
                    d.SetValue(ContentPresenter.ContentProperty, null);
                }
                else
                {
                    return;
                }
            }

            DataBoxShowData show = new DataBoxShowData();
            show.Owner = this.GetOwnerWindow();
            show.trade.Content = _showContent;
            show.ShowDialog();
            e.Handled = true;
        }

        protected virtual void OnCanExecuteShow(CanExecuteRoutedEventArgs e)
        {
            if (this.CanShow(e))
            {
                e.CanExecute = true;
                e.Handled = true;
                return;
            }
            e.ContinueRouting = true;
        }

        private bool CanShow(CanExecuteRoutedEventArgs e)
        {
            if (dhccDataGrid.SelectedItem == null)
            {
                return false;
            }

            return true;
        }
        #endregion

        #region DataBox行提示信息
        private void RowsPreviewKeyDown(DataGridRow dgr, string key)
        {
            bool flag = false;
            bool countFlag = false;
            if (key == "SHOWTIP")
            {
                // 创建一个grid 对象
                grid = new Grid();
                GridHelper.SetShowBorder(grid, true);
                GridHelper.SetGridLineThickness(grid, 0.5);
                GridHelper.SetGridLineBrush(grid, Brushes.LightGray);

                Border border = new Border
                             {
                                 BorderBrush = new SolidColorBrush(Colors.Gray),
                                 BorderThickness = new Thickness(1, 1, 1, 1)
                             };

                border.CornerRadius = new CornerRadius(2);

                //弹出框对象
                popDataDetails = new Popup();
                grid.Background = Brushes.White;
                //定义列
                ColumnDefinition column1 = new ColumnDefinition();
                column1.Width = new GridLength(120);
                ColumnDefinition column2 = new ColumnDefinition();
                column2.Width = new GridLength(180);
                ColumnDefinition column3 = new ColumnDefinition();
                column3.Width = new GridLength(120);
                ColumnDefinition column4 = new ColumnDefinition();
                column4.Width = new GridLength(180);

                grid.ColumnDefinitions.Add(column1);
                grid.ColumnDefinitions.Add(column2);
                grid.ColumnDefinitions.Add(column3);
                grid.ColumnDefinitions.Add(column4);

                if (popDataDetails.IsOpen == true)
                {
                    popDataDetails.IsOpen = false;
                    grid.Children.Clear();
                }

                if (dgr == null) return;
                var drv = dgr.Item as DataRowView;
                if (dhccDataGrid.Columns[0] is DataGridTemplateColumn)
                {
                    flag = true;
                }

                #region 一行多列转多行四列
                DataTable dtData = new DataTable();
                DataColumn colFirstColumn = new DataColumn("colFirstColumn");
                DataColumn colFirstValue = new DataColumn("colFirstValue");
                DataColumn colSencondColumn = new DataColumn("colSencondColumn");
                DataColumn colSencondValue = new DataColumn("colSencondValue");

                dtData.Columns.Add(colFirstColumn);
                dtData.Columns.Add(colFirstValue);
                dtData.Columns.Add(colSencondColumn);
                dtData.Columns.Add(colSencondValue);

                DataRow row = null;
                int colCount = 0;
                if (flag)
                {
                    colCount = drv.Row.ItemArray.Length - 2;
                }
                else
                {
                    colCount = drv.Row.ItemArray.Length - 1;
                }
                if (colCount % 2 != 0)
                {
                    countFlag = true;
                }
                for (int i = 0; i < colCount; )
                {
                    row = dtData.NewRow();

                    if (flag)
                    {
                        row["colFirstColumn"] = dhccDataGrid.Columns[i + 1].Header.ToString();
                        row["colFirstValue"] = drv.Row[i].ToString();

                        row["colSencondColumn"] = dhccDataGrid.Columns[i + 2].Header.ToString();
                        row["colSencondValue"] = drv.Row[i + 1].ToString();
                    }
                    else
                    {
                        row["colFirstColumn"] = dhccDataGrid.Columns[i].Header.ToString();
                        row["colFirstValue"] = drv.Row[i].ToString();
                        row["colSencondColumn"] = dhccDataGrid.Columns[i + 1].Header.ToString();
                        row["colSencondValue"] = drv.Row[i + 1].ToString();
                    }
                    i = i + 2;
                    dtData.Rows.Add(row);
                }

                if (countFlag)
                {
                    row = dtData.NewRow();
                    if (flag)
                    {
                        row["colFirstColumn"] = dhccDataGrid.Columns[colCount + 2].Header.ToString();
                        row["colFirstValue"] = drv.Row[colCount + 1].ToString();
                    }
                    dtData.Rows.Add(row);
                }

                #region 颜色设置
                Color bgColor = (Color)ColorConverter.ConvertFromString("#F5FAFA");
                Color fontColor = (Color)ColorConverter.ConvertFromString("#797268");
                Color colFontColor = (Color)ColorConverter.ConvertFromString("#4f6b72");

                #endregion
                #endregion
                for (int i = 0; i < dtData.Rows.Count; i++)
                {
                    RowDefinition rowcontent = new RowDefinition();
                    rowcontent.Height = new GridLength(28);
                    grid.RowDefinitions.Add(rowcontent);

                    for (int j = 0; j < dtData.Columns.Count; j++)
                    {
                        TextBlock columnName = new TextBlock();
                        columnName.FontSize = 14;
                        columnName.Height = 28;

                        if (j % 2 == 0)
                        {
                            columnName.Padding = new Thickness(0, 3, 5, 3);
                            columnName.Background = new SolidColorBrush(bgColor);
                            columnName.FontWeight = FontWeights.Bold;
                            columnName.Foreground = new SolidColorBrush(colFontColor);
                            columnName.TextAlignment = TextAlignment.Right;
                            columnName.Text = dtData.Rows[i][j].ToString();
                            columnName.Width = 120;
                        }
                        else
                        {
                            columnName.Padding = new Thickness(5, 3, 0, 3);
                            columnName.Foreground = new SolidColorBrush(fontColor);
                            columnName.HorizontalAlignment = HorizontalAlignment.Left;
                            columnName.Text = dtData.Rows[i][j].ToString();
                        }
                        Grid.SetRow(columnName, i);
                        Grid.SetColumn(columnName, j);
                        grid.Children.Add(columnName);
                    }
                }

                border.Child = grid;
                popDataDetails.Child = border;
                popDataDetails.StaysOpen = false;
                popDataDetails.AllowsTransparency = true;
                popDataDetails.Placement = PlacementMode.Center;
                popDataDetails.PlacementTarget = dhccDataGrid;
                popDataDetails.PopupAnimation = PopupAnimation.Fade;
                popDataDetails.IsOpen = true;
            }
            if (key == "HIDTIP")
            {
                if (popDataDetails.IsOpen == true)
                {
                    popDataDetails.IsOpen = false;
                }

            }
        }
        #endregion
    }
}
