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.Data;

namespace SiaSun.LMS.WPFClient.UC
{
    /// <summary>
    /// ucModelValuePanel.xaml 的交互逻辑
    /// </summary>
    public partial class ucModelValuePanel : UserControl
    {
        public ucModelValuePanel()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 根据DataGrid以及DataRow初始化控件
        /// </summary>
        public void U_InitControl(DataGrid gridApp, DataRow rowSource)
        {
            this.panelItem.Children.Clear();
            this.DataContext = rowSource;

            //开始初始化
            this.BeginInit();
            foreach (DataGridColumn col in gridApp.Columns)
            {
                if (col.Visibility == System.Windows.Visibility.Visible)
                {
                    //判断类型
                    if (col is DataGridTextColumn)
                    {
                        AddTextBlock((col as DataGridTextColumn), rowSource);
                    }
                    else if (col is DataGridCheckBoxColumn)
                    {
                        AddCheckBox((col as DataGridCheckBoxColumn), rowSource);
                    }
                    else if (col is DataGridComboBoxColumn)
                    {
                        AddComboBox((col as DataGridComboBoxColumn), rowSource);
                    }
                }
            }

            //结束初始化
            this.EndInit();
        }

        #region     ------添加控件

        /// <summary>
        /// 添加文本编辑
        /// </summary>
        private void AddTextBlock(DataGridTextColumn colText, DataRow rowSource)
        {
            //获得列绑定对象
            Binding bind = colText.Binding as Binding;
            if (bind == null)
                return;

            string strPath = bind.Path.Path;

            //添加内容控件
            TextBlock txtContent = new TextBlock();
            txtContent.Margin = new Thickness(10, 2, 5, 10);
            this.panelItem.Children.Add(txtContent);

            //设置绑定关系
            Binding bindContent = new Binding(string.Format("[{0}]", strPath));
            txtContent.SetBinding(TextBlock.TextProperty, bindContent);
        }

        /// <summary>
        /// 添加选中框
        /// </summary>
        private void AddCheckBox( DataGridCheckBoxColumn colChk, DataRow rowSource)
        {
            //获得列绑定对象
            Binding bind = colChk.Binding as Binding;
            if (bind == null)
                return;

            string strPath = bind.Path.Path;

            //控件定义
            CheckBox chkBox = new CheckBox();
            chkBox.IsThreeState = false;
            chkBox.Margin = new Thickness(10, 2, 5, 10);
            this.panelItem.Children.Add(chkBox);

            //设置绑定关系
            Binding bindContent = new Binding();
            chkBox.SetBinding(CheckBox.IsCheckedProperty, string.Format("[{0}]", strPath));
        }

        /// <summary>
        /// 添加选中框
        /// </summary>
        private void AddComboBox(DataGridComboBoxColumn colCmb, DataRow rowSource)
        {
            //获得列绑定对象
            Binding bind = colCmb.SelectedValueBinding as Binding;
            if (bind == null)
                return;
            string strPath = bind.Path.Path;

            //设置内容控件
            ComboBox cmb = new ComboBox();
            cmb.Margin = new Thickness(10, 2, 5, 10);
            cmb.DisplayMemberPath = colCmb.DisplayMemberPath;
            cmb.SelectedValuePath = colCmb.SelectedValuePath;
            cmb.ItemsSource = colCmb.ItemsSource;
            this.panelItem.Children.Add(cmb);

            //设置绑定关系
            Binding bindContent = new Binding();
            cmb.SetBinding(ComboBox.SelectedValueProperty, string.Format("[{0}]", strPath));
        }

        #endregion

        /// <summary>
        /// 根据Model实例对象初始化控件
        /// </summary>
        public void U_InitControl<T>(string WindowName, string XmlTableName, T Model)
        {
            this.panelItem.Children.Clear();
            this.DataContext = Model;

            try
            {
                CustomerDescriptions cusDescription = new CustomerDescriptions();
                using (DataTable tableFieldDescription = string.IsNullOrEmpty(WindowName) ? cusDescription.GetStyleDataTable(XmlTableName) : cusDescription.GetFormStyleDataTable(WindowName, XmlTableName))
                {
                    //根据序号排序并添加列显示
                    DataRow[] arRowField = tableFieldDescription.Rows.Cast<DataRow>().ToArray<DataRow>();
                    var queryField = from row in arRowField orderby Convert.ToInt32(row["Order"].ToString()) select row;

                    //判断控件类型设置显示列样式
                    foreach (DataRow rowField in queryField)
                    {
                        if (!rowField.IsNull("Header") && !String.IsNullOrEmpty(rowField["Header"].ToString()))
                        {
                            string strControlType = rowField["ControlType"].ToString().ToLower();
                            //判断类型
                            switch (strControlType)
                            {
                                case "checkbox":
                                    AddCheckBox<T>(Model, rowField);
                                    break;
                                case "combobox":
                                    AddComboBox<T>(Model, rowField);
                                    break;
                                case "elementcombox":
                                    AddElmentComboBox(Model, rowField);
                                    break;
                                default:
                                    AddTextBlock<T>(Model, rowField);
                                    break;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MainApp._MessageDialog.ShowException(ex);
            }
        }

        #region     ------添加控件

        /// <summary>
        /// 添加文本编辑
        /// </summary>
        private void AddTextBlock<T>( T Model, DataRow rowField)
        {
            //添加内容控件
            TextBlock txtContent = new TextBlock();
            txtContent.Margin = new Thickness(10, 2, 5, 10);
            this.panelItem.Children.Add(txtContent);

            //设置绑定关系
            Binding bindContent = new Binding(rowField["Column"].ToString());
            txtContent.SetBinding(TextBlock.TextProperty, bindContent);
        }

        /// <summary>
        /// 添加选中框
        /// </summary>
        private void AddCheckBox<T>(T Model, DataRow rowField)
        {
            //控件定义
            CheckBox chkBox = new CheckBox();
            chkBox.IsThreeState = false;
            chkBox.Margin = new Thickness(10, 2, 5, 10);
            this.panelItem.Children.Add(chkBox);

            //设置绑定关系
            Binding bindContent = new Binding(rowField["Column"].ToString());
            chkBox.SetBinding(CheckBox.IsCheckedProperty, bindContent);
        }

        /// <summary>
        /// 添加选中框
        /// </summary>
        private void AddComboBox<T>(T Model, DataRow rowField)
        {
            //设置内容控件
            ComboBox cmb = new ComboBox();
            cmb.Margin = new Thickness(10, 2, 5, 10);
            cmb.DisplayMemberPath = "NAME".ToLower();
            cmb.SelectedValuePath = "VALUE".ToLower();
            cmb.ItemsSource = new CustomerDescriptions().GetComboBoxDataTable(rowField["DataBind"].ToString()).DefaultView;

            this.panelItem.Children.Add(cmb);

            //设置绑定关系
            Binding bindContent = new Binding(rowField["Column"].ToString());
            cmb.SetBinding(ComboBox.SelectedValueProperty, bindContent);
        }

        /// <summary>
        /// 添加选中框
        /// </summary>
        private void AddElmentComboBox<T>(T Model, DataRow rowField)
        {
            //设置内容控件
            ComboBox cmb = new ComboBox();
            cmb.Margin = new Thickness(10, 2, 5, 2);
            this.panelItem.Children.Add(cmb);
            if (!rowField.IsNull("DataBind"))
            {
                string[] arStr = rowField["DataBind"].ToString().Split('|');
                cmb.ItemsSource = arStr;
            }

            //设置绑定关系
            Binding bindContent = new Binding(rowField["Column"].ToString());
            cmb.SetBinding(ComboBox.SelectedValueProperty, bindContent);
        }

        #endregion

        /// <summary>
        /// 获得查询条件
        /// </summary>
        /// <returns></returns>
        public string U_GetWhere()
        {
            string strWhere = null;
            string strColumn=null;
            string strValue = null;
            foreach (DependencyObject obj in this.panelItem.Children)
            {
                if (obj is TextBlock)
                {
                    TextBlock txt = obj as TextBlock;
                    Binding bind = BindingOperations.GetBinding(txt, TextBlock.TextProperty);
                    if (bind != null)
                    { 
                        strColumn = bind.Path.Path;
                        strValue = txt.Text;
                    }
                }
                else if (obj is CheckBox)
                {
                    CheckBox chk = obj as CheckBox;
                    Binding bind = BindingOperations.GetBinding(chk, CheckBox.IsCheckedProperty);
                    if (bind != null)
                    {
                        strColumn = bind.Path.Path;
                        strValue = Convert.ToInt32(chk.IsChecked.ToString()).ToString();
                    }
                }
                else if (obj is ComboBox)
                {
                    ComboBox cmb = obj as ComboBox;
                    if (cmb.HasItems&&cmb.SelectedValue != null)
                    {
                        Binding bind = BindingOperations.GetBinding(cmb, ComboBox.SelectedValueProperty);
                        strColumn = bind.Path.Path;
                        strValue = cmb.SelectedValue.ToString();
                      }
                }

                strWhere += string.Format("{0}{1}='{2}'",(string.IsNullOrEmpty(strWhere)?string.Empty:" AND "),strColumn,strValue);
            }
            return strWhere.Replace('[', ' ').Replace(']', ' ');
        }
    }
}