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.Reflection;
using System.Data;

namespace SiaSun.LMS.WPFClient.SYS
{
    /// <summary>
    /// ROLE_WINDOW_CONTROL.xaml 的交互逻辑
    /// </summary>
    public partial class ROLE_WINDOW_CONTROL : AvalonDock.DocumentContent
    {
        IList<Model.SYS_MENU> listMenu = new List<Model.SYS_MENU>();
        IList<Model.SYS_ROLE_WINDOW> listROLE_WINDOW = new List<Model.SYS_ROLE_WINDOW>();

        /// <summary>
        /// 构造函数
        /// </summary>
        public ROLE_WINDOW_CONTROL()
        {
            InitializeComponent();

            this.gridRole.gridApp.SelectionChanged += new SelectionChangedEventHandler(gridRole_SelectionChanged);
            this.tvwWindow.U_ItemSelectedChanged += new UC.ucTreeView.U_ItemSelectedChangedHandler(tvwWindow_U_ItemSelectedChanged);
        }

        /// <summary>
        /// 窗体加载
        /// </summary>
        private void DocumentContent_Loaded(object sender, RoutedEventArgs e)
        {
            //加载所有角色
            this.RoleBind();
        }

        #region     ------加载角色

        /// <summary>
        /// 加载角色
        /// </summary>
        private void RoleBind()
        {
            this.gridRole.U_WindowName = this.GetType().Name;
            this.gridRole.U_TableName = "SYS_ROLE";
            this.gridRole.U_XmlTableName = "SYS_ROLE";
            this.gridRole.U_OrderField = "ROLE_ORDER";
            this.gridRole.U_Where = string.Format("ROLE_ID>0");

            this.gridRole.U_AllowOperatData = false;
            this.gridRole.U_AllowChecked = false;
            this.gridRole.U_AllowPage = false;

            this.gridRole.U_InitControl();
        }

        /// <summary>
        /// 选择角色显示角色窗体信息
        /// </summary>
        private void gridRole_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.gridRole.U_SelectedItem == null)
                return;
            
            //加载所有的窗体
            this.LoadWindowItems();
        }

        #endregion

        #region     ------加载窗体菜单

        /// <summary>
        /// 加载所有的窗体菜单
        /// </summary>
        private void LoadWindowItems()
        {
            try
            {
                //清除控件显示数据
                this.gridControl.ItemsSource = null;
                this.tvwWindow.U_Clear();

                //获得所有窗体菜单
                this.listMenu = MainApp._I_SystemService.MENU_GetList();
                //分组
                var queryGroup = from menu in listMenu
                                 where !string.IsNullOrEmpty(menu.MENU_PARAMETER) && menu.MENU_SELECTEDFLAG == "1"
                                 orderby menu.MENU_ORDER
                                 group menu by menu.MENU_PARENT_ID into a
                                 select a;
                foreach (var menuParent in queryGroup)
                {
                    //上级节点
                    Model.SYS_MENU mSYS_MENU = listMenu.Single(r => r.MENU_ID == menuParent.Key);
                    //添加节点
                    TreeViewItem itemParent = this.tvwWindow.U_AddTreeViewItem(null, mSYS_MENU.MENU_NAME, mSYS_MENU.MENU_ID);
                    foreach (Model.SYS_MENU mMenu in listMenu.Where(r => r.MENU_PARENT_ID == menuParent.Key && !string.IsNullOrEmpty(r.MENU_PARAMETER) && !string.IsNullOrEmpty(r.MENU_PARAMETER) && r.MENU_DEVELOPFLAG == "1"))
                    {
                        this.tvwWindow.U_AddTreeViewItem(itemParent, mMenu.MENU_NAME, mMenu.MENU_ID);
                    }
                    //展开
                    itemParent.IsExpanded = true;
                    if (!itemParent.HasItems)
                    {
                        this.tvwWindow.tvwList.Items.Remove(itemParent);
                    }
                }
            }
            catch (Exception ex)
            {
                MainApp._MessageDialog.ShowException(ex);
            }
        }

        /// <summary>
        /// 选项更改
        /// </summary>
        void tvwWindow_U_ItemSelectedChanged(TreeViewItem itemSelected)
        {
            //刷新重新加载窗体控件
            this.Refresh();
        }

        #endregion 

        #region     -------加载窗体所有控件信息

        /// <summary>
        /// 加载窗体控件
        /// </summary>
        private void LoadWindowControls(int ROLE_ID,Model.SYS_MENU mMENU)
        {
            //清空初始化
            this.listROLE_WINDOW.Clear();
            this.gridControl.ItemsSource = null;

            try
            {
                if (!string.IsNullOrEmpty(mMENU.MENU_CLASS))
                {
                    Type typeWindow = Type.GetType(mMENU.MENU_CLASS);
                    if (typeWindow != null)
                    {
                        //获得实例
                        object objWindow = Activator.CreateInstance(typeWindow);
                        if (objWindow != null)
                        {
                            AvalonDock.DocumentContent docWin = objWindow as AvalonDock.DocumentContent;
                            if (docWin != null)
                            {
                                //获得所有控件对象
                                foreach (object obj in LogicalTreeHelper.GetChildren(docWin))
                                {
                                    if (obj is FrameworkElement)
                                    {
                                        FrameworkElement elem = obj as FrameworkElement;
                                        //加载子控件
                                        this.LoadControls(ROLE_ID, mMENU, elem);
                                    }
                                }
                            }
                        }
                    }
                }
                //设置数据源
                this.gridControl.ItemsSource = listROLE_WINDOW;
            }
            catch (Exception ex)
            {
                MainApp._MessageDialog.ShowException(ex.Message);
            }
        }

        /// <summary>
        /// 加载所有控件
        /// </summary>
        private void LoadControls(int ROLE_ID,Model.SYS_MENU mMENU,FrameworkElement elemParent)
        {
            if (elemParent != null)
            {
                foreach (object obj in LogicalTreeHelper.GetChildren(elemParent))
                {
                    if (obj is FrameworkElement)
                    {
                        FrameworkElement elem = obj as FrameworkElement;
                        if (elem.GetType() == typeof(System.Windows.Controls.Button) || elem.GetType() == typeof(System.Windows.Controls.MenuItem))
                        {
                            //如果是按钮
                            if (elem.GetType() == typeof(System.Windows.Controls.Button))
                            {
                                Button btn = (Button)elem;
                                if (btn.Content != null)
                                {
                                    //添加到列表
                                    this.AddRoleWindowControlList(ROLE_ID, mMENU.MENU_ID, btn.Name, btn.Content.ToString());
                                }
                            }

                            //如果是菜单
                            if (elem.GetType() == typeof(System.Windows.Controls.MenuItem))
                            {
                                MenuItem menuItem = (MenuItem)elem;
                                //添加到列表
                                this.AddRoleWindowControlList(ROLE_ID, mMENU.MENU_ID, menuItem.Name, menuItem.Header.ToString());
                            }             
                        }
                        else
                        {
                            //加载控件
                            this.LoadControls(ROLE_ID,mMENU, elem);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 添加角色控件列表
        /// </summary>
        private void AddRoleWindowControlList(int ROLE_ID,int MENU_ID,string CONTROL_NAME,string CONTROL_HEADER)
        {
            //添加列表
            Model.SYS_ROLE_WINDOW mROLE_WINDOW = new Model.SYS_ROLE_WINDOW();
            mROLE_WINDOW.ROLE_ID = ROLE_ID;
            mROLE_WINDOW.MENU_ID = MENU_ID;
            mROLE_WINDOW.CONTROL_NAME = CONTROL_NAME;
            mROLE_WINDOW.CONTROL_HEADER = CONTROL_HEADER;
            mROLE_WINDOW.FLAG = this.GetFlagValue(ROLE_ID, MENU_ID, CONTROL_NAME);
            this.listROLE_WINDOW.Add(mROLE_WINDOW);
        }

        /// <summary>
        /// 获得标识值
        /// </summary>
        /// <returns></returns>
        private int GetFlagValue(int ROLE_ID,int MenuID,string CONTROL_NAME)
        {
            int intFlag = 0;
            Model.SYS_ROLE_WINDOW mROLE_WINDOW = MainApp._I_SystemService.ROLE_WINDOW_GetModel_MENU_CONTROL(ROLE_ID, MenuID, CONTROL_NAME);
            if (mROLE_WINDOW != null)
            {
                intFlag = mROLE_WINDOW.FLAG;
            }
            return intFlag;
        }

        #endregion

        #region     ------添加窗体样式

        /// <summary>
        /// 按钮事件
        /// </summary>
        private void WrapPanel_Click(object sender, RoutedEventArgs e)
        {
            Button btn = e.OriginalSource as Button;
            if (btn != null)
            {
                switch (btn.Name)
                {
                    case "btnSave":
                        this.Save();
                        break;
                    case "btnRefresh":
                        this.Refresh();
                        break;
                }
            }
        }

        /// <summary>
        /// 保存
        /// </summary>
        private void Save()
        {
            if (this.gridRole.U_SelectedItem == null || this.tvwWindow.U_SelectedItem == null)
                return;
            
            if (MainApp._MessageDialog.ShowDialog(Enum.MessageConverter.Save.ToString(),null) == Sid.Windows.Controls.TaskDialogResult.Ok)
            {
                string strResult = string.Empty;

                //结束编辑
                this.gridControl.U_EndCurrentEdit();

                //获得角色ID
                int intRoleID = Convert.ToInt32((this.gridRole.U_SelectedItem as DataRowView)["ROLE_ID"]);

                //提交保存
                bool boolResult = MainApp._I_SystemService.ROLE_WINDOW_Save(intRoleID,Convert.ToInt32(this.tvwWindow.U_SelectedItem.Tag), this.listROLE_WINDOW, out strResult);
                MainApp._MessageDialog.ShowResult(boolResult, strResult);
            }
        }    
        
        /// <summary>
        /// 刷新
        /// </summary>
        private void Refresh()
        {
            if (this.gridRole.U_SelectedItem == null || this.tvwWindow.U_SelectedItem == null)
                return;

            try
            {
                //清空
                this.gridControl.ItemsSource = null;

                //设置显示
                grpbControl.Header = string.Format(this.grpbControl.Tag.ToString(),this.tvwWindow.U_SelectedItem.Header.ToString());

                //获得角色ID
                DataRowView rowViewRole = this.gridRole.U_SelectedItem as DataRowView;
                if (rowViewRole != null)
                {
                    //角色ID
                    int intRoleID = Convert.ToInt32(rowViewRole["ROLE_ID"]);
                    //获得MenuID
                    int intMenuID = Convert.ToInt32(this.tvwWindow.U_SelectedItem.Tag);
                    if (this.listMenu.Count(r => r.MENU_ID == intMenuID) > 0)
                    {
                        Model.SYS_MENU mMenu = this.listMenu.Single(r => r.MENU_ID == intMenuID);

                        //加载控件
                        this.LoadWindowControls(intRoleID, mMenu);
                    }
                }
            }
            catch (Exception ex)
            {
                MainApp._MessageDialog.ShowException(ex);
            }
        }

        #endregion
    }
}