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>
    /// ucRelationEdit.xaml 的交互逻辑
    /// </summary>
    public partial class ucRelationEdit : UserControl
    {
        string strRelationCode = string.Empty;
        Model.SYS_RELATION mSYS_RELATION = null;
        string strTable1, strTable2;
        string strWhere = string.Empty;
        string strOrderFields = string.Empty;

        /// <summary>
        /// 权限关系编码
        /// </summary>
        public string U_RelationCode
        {
            get { return strRelationCode; }
            set { strRelationCode = value; }
        }

        /// <summary>
        /// 查询条件
        /// </summary>
        public string U_Where
        {
            get { return strWhere; }
            set { strWhere = value; }
        }
        /// <summary>
        /// 排序
        /// </summary>
        public string U_OrderFields
        {
            get { return strOrderFields; }
            set { strOrderFields = value; }
        }

        public ucRelationEdit()
        {
            InitializeComponent();

        }
        
        /// <summary>
        /// 初始化控件
        /// </summary>
        public void U_InitControl()
        {
            //获得关系实例
            mSYS_RELATION = MainApp._I_SystemService.RELATION_GetModel(strRelationCode);
            if (mSYS_RELATION == null)
                return;

            //获得显示名称
            string[] arStrHeaderText = mSYS_RELATION.RELATION_NAME.Split('-');
            if (arStrHeaderText.Length == 2)
            {
                this.grpboxQuery.Header = string.Format(this.grpboxQuery.Header.ToString(),arStrHeaderText[0]);
                this.grpboxUnSelected.Header = string.Format( this.grpboxUnSelected.Header.ToString(),arStrHeaderText[1]);
                this.grpboxSelected.Header = string.Format(this.grpboxSelected.Header.ToString(),arStrHeaderText[1]);
            }

            //分解表名称
            string[] arStrTableName = mSYS_RELATION.RELATION_CODE.Split('-');
            if (arStrTableName.Length == 2)
            {
                strTable1 = arStrTableName[0];
                strTable2 = arStrTableName[1];

                //显示项目列表
                RelationItem_Bind();
            }
        }

        /// <summary>
        /// 权限管理项目列表
        /// </summary>
        private void RelationItem_Bind()
        {
            try
            {
                this.gridQuery.U_TableName = strTable1;
                this.gridQuery.U_Fields = "*";
                this.gridQuery.U_OrderField = mSYS_RELATION.RELATION_ID1;
                this.gridQuery.U_AllowOperatData = false;
                this.gridQuery.U_AllowChecked = false;
                this.gridQuery.U_AllowPage = false;

                //筛选条件
                if (MainApp._ROLE.ROLE_ID != 0)
                {
                    this.gridQuery.U_Where = mSYS_RELATION.RELATION_ID1 + string.Format("<>{0}", 0);
                }
                //初始化
                this.gridQuery.U_InitControl();

                this.gridQuery.gridApp.SelectionChanged += new SelectionChangedEventHandler(gridApp_SelectionChanged);

            }
            catch (Exception ex)
            {
                MainApp._MessageDialog.ShowException(ex);
            }
        }

        /// <summary>
        /// 选择行,显示关系数据
        /// </summary>
        void gridApp_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            this.LoadRelation();
        }

        /// <summary>
        /// 加载关系数据
        /// </summary>
        private void LoadRelation()
        {
            if (this.gridQuery.gridApp.SelectedItem == null)
                return;

            try
            {
                DataRowView rowView = this.gridQuery.gridApp.SelectedItem as DataRowView;
                if (rowView == null)
                    return;

                //清空显示项目
                this.lboxSelected.Items.Clear();
                this.lboxUnSelected.Items.Clear();

                //获得关联的ID1
                int intID1 = Convert.ToInt32(rowView[mSYS_RELATION.RELATION_ID1]);
                string strAppendWhere = MainApp._ROLE.ROLE_ID == 0 ? "1=1" : mSYS_RELATION.RELATION_ID2 + string.Format(">0");

                //加载所有的项目
                DataTable tableItem = MainApp._I_BaseService.GetList(string.Format("SELECT {0},{1} FROM {2} WHERE {3} {4}",
                                                                                    mSYS_RELATION.RELATION_ID2,
                                                                                    mSYS_RELATION.RELATON_NAME2,
                                                                                    strTable2,
                                                                                    (strWhere.Length == 0 ? strAppendWhere : strAppendWhere + " AND " + strWhere),
                                                                                    strOrderFields == string.Empty ? string.Empty: string.Format(" ORDER BY {0}",strOrderFields)));

                //加载所有存在的关系列表
                IList<Model.SYS_RELATION_LIST> listRELATON_LIST = MainApp._I_SystemService.RELATION_LIST_GetList_ID1(mSYS_RELATION.RELATION_ID, intID1);

                //显示未选择项目
                Relation_Bind(intID1, tableItem, listRELATON_LIST);
            }
            catch (Exception ex)
            {
                MainApp._MessageDialog.ShowException(ex);
            }
        }

        /// <summary>
        /// 显示未选择项目
        /// </summary>
        private void Relation_Bind(int ID1, DataTable tableAll, IList<Model.SYS_RELATION_LIST> listRELATON_LIST)
        {
            foreach (DataRow row in tableAll.Rows)
            {
                //获得关联的ID2
                int intID2 = Convert.ToInt32(row[mSYS_RELATION.RELATION_ID2]);

                //判断是否选择
                if (listRELATON_LIST.Count(r => r.RELATION_ID2 == intID2) > 0)
                {
                    AddImageItem(lboxSelected, row[mSYS_RELATION.RELATON_NAME2].ToString(), intID2);
                }
                else
                {
                    AddImageItem(lboxUnSelected, row[mSYS_RELATION.RELATON_NAME2].ToString(), intID2);
                }
            }
        }

        /// <summary>
        /// 添加列表项目
        /// </summary>
        private void AddImageItem(ListBox listBox, string text, object tag)
        {
            ListBoxItem item = new ListBoxItem();
            item.BeginInit();
            item.MouseDoubleClick += new MouseButtonEventHandler(item_MouseDoubleClick);
            item.Margin = new Thickness(3);
            item.Tag = tag;
            listBox.Items.Add(item);

            //添加显示内容
            StackPanel panelItem = new StackPanel();
            panelItem.Tag = tag;
            panelItem.Orientation = Orientation.Horizontal;
            item.Content = panelItem;

            //添加图像
            Image imageItem = new Image();
            imageItem.Margin = new Thickness(5,2,10,2);
            panelItem.Children.Add(imageItem);

            //获得图像路径
            //Uri url = new Uri(MainApp._APP_PATH + @"\@Images\report.png", UriKind.Absolute);
            Uri url = new Uri("/@Images/report.png", UriKind.RelativeOrAbsolute);
            BitmapImage imageURI = new BitmapImage(url);
            imageItem.Source = imageURI;

            //添加描述
            TextBlock txtHeader = new TextBlock();
            txtHeader.VerticalAlignment = System.Windows.VerticalAlignment.Center;
            txtHeader.Text = text;
            panelItem.Children.Add(txtHeader);
            item.EndInit();
        }

        /// <summary>
        /// 添加或取消选择
        /// </summary>
        private void StackPanel_Click(object sender, RoutedEventArgs e)
        {
            Button btn = e.OriginalSource as Button;
            if (btn != null)
            {
                ListBoxItem[] arItems = null;
                switch (btn.Name)
                {
                    case "btnSelect":
                        arItems = this.lboxUnSelected.SelectedItems.Cast<ListBoxItem>().ToArray();
                        break;
                    case "btnUnSelect": 
                        arItems = this.lboxSelected.SelectedItems.Cast<ListBoxItem>().ToArray();
                        break;
                }

                //添加选择
                if (arItems.Length > 0)
                {
                    foreach (ListBoxItem item in arItems)
                    {
                        this.ExchangeItem(item);
                    }
                }
            }
        }

        /// <summary>
        /// 双击移除选项
        /// </summary>
        void item_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            ListBoxItem itemSelected = e.Source as ListBoxItem;
            if (itemSelected != null)
            {
                this.ExchangeItem(itemSelected);
            }
        }

        /// <summary>
        /// 交换选项
        /// </summary>
        private void ExchangeItem(ListBoxItem item)
        {
            if (lboxUnSelected.Items.Contains(item))
            {
                lboxUnSelected.Items.Remove(item);
                lboxSelected.Items.Add(item);
            }
            else if (lboxSelected.Items.Contains(item))
            {
                lboxSelected.Items.Remove(item);
                lboxUnSelected.Items.Add(item);
            }
        }

        #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.LoadRelation();
                        break;
                }
            }
        }

        //保存
        private void Save()
        {
            if (this.gridQuery.U_SelectedItem == null)
                return;

            if (MainApp._MessageDialog.ShowDialog("Save",null) == Sid.Windows.Controls.TaskDialogResult.Ok)
            {
                try
                {
                    DataRowView rowView = this.gridQuery.U_SelectedItem as DataRowView;
                    if (rowView == null)
                        return;

                    //获得关联的ID1
                    int intID1 = Convert.ToInt32(rowView[mSYS_RELATION.RELATION_ID1]);

                    //get all warehouses's id
                    int[] arRelationID2 = new int[this.lboxSelected.Items.Count];
                    for (int i = 0; i < lboxSelected.Items.Count; i++)
                    {
                        arRelationID2[i] = Convert.ToInt32((lboxSelected.Items[i] as ListBoxItem).Tag.ToString());
                    }

                    //Commit data
                    string strMessage = string.Empty;
                    bool boolResult = MainApp._I_SystemService.RELATION_LIST_Add(strRelationCode, intID1, arRelationID2, out strMessage);
                    MainApp._MessageDialog.ShowResult(boolResult, strMessage);
                }
                catch (Exception ex)
                {
                    MainApp._MessageDialog.ShowException(ex);
                }
            }
        }

        #endregion

        #region     ------上下文菜单-排序

        //上下文菜单事件
        private void ContextMenu_Click(object sender, RoutedEventArgs e)
        {
            MenuItem menuItem = e.OriginalSource as MenuItem;
            if (menuItem != null)
            {
                switch (menuItem.Name)
                {
                    case "menuItemUnSelectedOrder":
                        OrderListBoxItems(lboxUnSelected);
                        break;
                    case "menuItemSelectedOrder":
                        OrderListBoxItems(lboxSelected);
                        break;
                }
            }
        }

        /// <summary>
        /// 重新排序
        /// </summary>
        private void OrderListBoxItems(ListBox lsBox)
        {
            if (lsBox.HasItems)
            {
                IList<ListBoxItem> listItem = new List<ListBoxItem>();
                for (int i = lsBox.Items.Count - 1; i >= 0; i--)
                {
                    ListBoxItem item = lsBox.Items[i] as ListBoxItem;
                    lsBox.Items.Remove(item);

                    listItem.Add(item);
                }

                //排序添加
                foreach (ListBoxItem item in listItem.OrderBy(r => r.Content.ToString()))
                {
                    lsBox.Items.Add(item);
                }
            }
        }

        #endregion
    }
}