using MultiLayout.UiModule;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
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;

namespace MultiLayout.MainEdit
{
    /// <summary>
    /// Page_MainEditGraph.xaml 的交互逻辑
    /// </summary>
    public partial class PgMainEditGraph : Page
    {
        FlyLayoutManager manager;
        FlyLayout layout;
        GageTabItem gageTabItem;

        ObservableCollection<MeGraphTabItem> Items;
        ObservableCollection<MeComponentType> ToolboxItems;
        public PgMainEditGraph()
        {
            InitializeComponent();

            //测试
            //DefaultToolbox();
            //DefaultData();
        }

        public void Init(GageTabItem gageTabItem, FlyLayoutManager manager)
        {
            this.manager = manager;
            layout = this.manager.layout;
            this.gageTabItem = gageTabItem;
            ToolboxItems = GraphConverter.GetToolboxItems(this.manager, ComponentType.Graph);
            Items = GraphConverter.GetMeGraphTabItems(gageTabItem, ToolboxItems);
            this.DataContext = gageTabItem;
            itemsControl_toolbox.ItemsSource = ToolboxItems;
            UpdateTabControl();
        }

        private void Page_MainEditGraph_RCChanged(MeGraphTabItem obj)
        {
            //查找对应的TabItem
            Grid g = obj.mTabItem.Content as Grid;
            if (g == null)
                return;
            UpdateGrid(g, obj);
            UpdateComponentTypeCount();
        }

        void UpdateTabControl()
        {
            tabcontrol.Items.Clear();
            for (int i = 0; i < Items.Count(); i++)
            {
                TabControlAdd(Items[i]);
            }
            Items.CollectionChanged += Items_CollectionChanged;
            UpdateComponentTypeCount();
        }

        private void Items_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            switch (e.Action)
            {
                case System.Collections.Specialized.NotifyCollectionChangedAction.Add:
                    {
                        foreach (MeGraphTabItem item in e.NewItems)
                        {
                            TabControlAdd(item);
                        }
                        tabcontrol.SelectedIndex = tabcontrol.Items.Count - 1;
                    }
                    break;
                case System.Collections.Specialized.NotifyCollectionChangedAction.Move:
                    {
                        TabItem ti_old = tabcontrol.Items[e.OldStartingIndex] as TabItem;
                        if (tabcontrol.SelectedItem == ti_old)
                        {
                            tabcontrol.Items.RemoveAt(e.OldStartingIndex);
                            tabcontrol.Items.Insert(e.NewStartingIndex, ti_old);
                            tabcontrol.SelectedItem = ti_old;
                        }
                        else
                        {
                            tabcontrol.Items.RemoveAt(e.OldStartingIndex);
                            tabcontrol.Items.Insert(e.NewStartingIndex, ti_old);
                        }
                        
                    }
                    break;
                case System.Collections.Specialized.NotifyCollectionChangedAction.Remove:
                    {
                        tabcontrol.Items.RemoveAt(e.OldStartingIndex);
                    }
                    break;
            }
        }

        void TabControlAdd(MeGraphTabItem item)
        {
            TabItem ti = new TabItem()
            {
                Tag = item
            };
            ti.SetBinding(TabItem.HeaderProperty, new Binding("Title") { Source = item });
            item.mTabItem = ti;

            Grid g = new Grid();
            g.Style = this.Resources["GridStyle_grid"] as Style;
            UpdateGrid(g, item);
            ti.Content = g;

            tabcontrol.Items.Add(ti);
            item.RCChanged += Page_MainEditGraph_RCChanged;
        }
        void UpdateGrid(Grid grid, MeGraphTabItem item)
        {
            grid.RowDefinitions.Clear();
            {
                RowDefinition rd = new RowDefinition();
                rd.Height = new GridLength(20);
                grid.RowDefinitions.Add(rd);
            }

            for (int i = 0; i < item.RowDefinitions.Count(); i++)
            {
                RowDefinition rd = new RowDefinition();
                grid.RowDefinitions.Add(rd);
            }

            grid.ColumnDefinitions.Clear();
            {
                ColumnDefinition cd = new ColumnDefinition();
                cd.Width = new GridLength(20);
                grid.ColumnDefinitions.Add(cd);
            }
            for (int i = 0; i < item.ColumnDefinitions.Count(); i++)
            {
                ColumnDefinition cd = new ColumnDefinition();
                grid.ColumnDefinitions.Add(cd);
            }



            grid.Children.Clear();
            //添加Definitions标示
            for (int x = 0; x < item.ColumnDefinitions.Count(); x++)
            {
                ToggleButton tb = new ToggleButton();
                tb.SetValue(Grid.ColumnProperty, x + 1);
                tb.Style = this.Resources["ToggleButtonStyle_auto"] as Style;
                tb.SetBinding(CheckBox.IsCheckedProperty,
                    new Binding("ColumnDefinitions[" + x.ToString() + "]") { Source = item});
                grid.Children.Add(tb);
            }

            for (int y = 0; y < item.RowDefinitions.Count(); y++)
            {
                ToggleButton tb = new ToggleButton();
                tb.SetValue(Grid.RowProperty, y + 1);
                tb.Style = this.Resources["ToggleButtonStyle_auto"] as Style;
                tb.SetBinding(CheckBox.IsCheckedProperty,
                    new Binding("RowDefinitions[" + y.ToString() + "]") { Source = item });
                grid.Children.Add(tb);
            }

            //添加 表格线
            for (int x = 0; x < item.ColumnDefinitions.Count() - 1; x++)
            {
                Border b = new Border();
                b.SetValue(Grid.ColumnProperty, x + 1);
                b.SetValue(Grid.RowSpanProperty, item.RowDefinitions.Count() + 1);
                b.Style = this.Resources["BorderStyle_vGridLine"] as Style;
                grid.Children.Add(b);
            }
            for (int y = 0; y < item.RowDefinitions.Count() - 1; y++)
            {
                Border b = new Border();
                b.SetValue(Grid.RowProperty, y + 1);
                b.SetValue(Grid.ColumnSpanProperty, item.ColumnDefinitions.Count() + 1);
                b.Style = this.Resources["BorderStyle_hGridLine"] as Style;
                grid.Children.Add(b);
            }

            //添加 控件
            for (int i = 0; i < item.Components.Count(); i++)
            {
                MeGraphComponent c = item.Components[i];
                //加入统计
                ButtonComponentAdd(grid, c);
            }
        }
        void UpdateComponentTypeCount()
        {
            foreach (MeComponentType type in ToolboxItems)
            {
                type.Count = Items.Sum(((item) => {
                    return item.Components.Count((c) => { return c.Type == type; });
                }));
            }
        }
        void ButtonComponentAdd(Grid grid, MeGraphComponent c)
        {
            Button b = new Button();
            c.mButton = b;
            b.Name = "button_component";
            b.Style = this.Resources["ButtonStyle_component"] as Style;
            b.Background = c.Type.Background;
            b.Click += button_componentEdit_Click;
            SetButtonComponentRect(c);
            c.PropertyChanged += C_PropertyChanged;
            b.DataContext = c;
            b.Tag = c;
            grid.Children.Add(b);
        }
        void SetButtonComponentRect(MeGraphComponent c)
        {
            Button b = c.mButton;
            b.SetValue(Grid.ColumnProperty, c.Rect.X + 1);
            b.SetValue(Grid.RowProperty, c.Rect.Y + 1);
            b.SetValue(Grid.ColumnSpanProperty, c.Rect.Width);
            b.SetValue(Grid.RowSpanProperty, c.Rect.Height);
        }
        private void C_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "Rect")
            {
                var c = sender as MeGraphComponent;
                if (c.Rect.IsEmpty)
                {
                    Grid g = c.mItem.mTabItem.Content as Grid;
                    g.Children.Remove(c.mButton);
                }
                else
                {
                    SetButtonComponentRect(c);
                }
            }
        }

        private void button_itemDel_Click(object sender, RoutedEventArgs e)
        {
            e.Handled = true;
            //向上找TabItem
            TabItem tabitem = FLY.ControlLibrary.COMMON.GetParent<TabItem>(sender as DependencyObject);
            if (tabitem == null)
            {
                //异常
                return;
            }
            int idx = Items.IndexOf(tabitem.Tag as MeGraphTabItem);
            if (idx < 0)
            {
                //异常
                return;
            }
            //提示是否删除
            string strTipTabItemDel = "页面将要被删除, 是否确定？";
            if (FLY.ControlLibrary.MyMessageBox.Show(strTipTabItemDel) == true)
            {
                Items.RemoveAt(idx);
            }
            
            
        }

        private void button_itemEdit_Click(object sender, RoutedEventArgs e)
        {
            //向上找TabItem
            TabItem tabitem = FLY.ControlLibrary.COMMON.GetParent<TabItem>(sender as DependencyObject);
            if (tabitem == null)
            {
                //异常
                return;
            }
            int idx = Items.IndexOf( tabitem.Tag as MeGraphTabItem);
            if (idx < 0)
            {
                //异常
                return;
            }
            
            WdGraphTabItemConfig w = new WdGraphTabItemConfig();
            w.Init(Items, idx);
            w.Owner = FLY.ControlLibrary.COMMON.GetWindow(this);
            w.ShowDialog();
        }

        private void button_itemAdd_Click(object sender, RoutedEventArgs e)
        {
            MeGraphTabItem item = new MeGraphTabItem();
            Items.Add(item);
        }

        private void button_componentNew_Click(object sender, RoutedEventArgs e)
        {
            TabItem tabitem = tabcontrol.SelectedItem as TabItem;
            if (tabitem == null)
            {
                string strError = "错误";
                string strTipNoTabItem = "没有选择图表页面";
                FLY.ControlLibrary.Window_WarningTip.Show(strError, strTipNoTabItem);
                return;
            }
            var item = tabitem.Tag as MeGraphTabItem;

            System.Drawing.Point p = item.GetFreeLocal();
            if (p.X == -1)
            {
                string strError = "错误";
                string strTipNoSize = "没有空间放置组件";
                FLY.ControlLibrary.Window_WarningTip.Show(strError, strTipNoSize);
                return;
            }
            Button button = sender as Button;
            var gct = button.Tag as MeComponentType;

            if (!gct.IsEnable)
            {
                string strError = "错误";
                string strTipCantAddAgain = "不能重复放置组件";
                FLY.ControlLibrary.Window_WarningTip.Show(strError, strTipCantAddAgain);
                return;
            }


            var c = new MeGraphComponent()
            {
                Type = gct,
                Rect = new System.Drawing.Rectangle(p.X, p.Y, 1, 1),
                ServiceContainerName = gageTabItem.ServiceContainerName
            };

            WdGraphConfig w = new WdGraphConfig();
            w.Init(c, manager.serviceNames);
            w.Owner = FLY.ControlLibrary.COMMON.GetWindow(this);
            if (w.ShowDialog() == true)
            {
                //检测位置是否合法
                if (!item.IsComponentRectVaild(w.Result.Rect))
                {
                    string strError = "错误";
                    string strTipErrorComponentAdd = " 组件位置尺寸出错,不能添加";
                    FLY.ControlLibrary.Window_WarningTip.Show(strError, strTipErrorComponentAdd);
                    return;
                }
                c.Rect = w.Result.Rect;
                c.ServiceContainerName = w.Result.ServiceContainerName;
                item.Components.Add(c);
                c.mItem = item;
                gct.Count++;
                ButtonComponentAdd(tabitem.Content as Grid, c);
            }
        }

        private void button_componentDel_Click(object sender, RoutedEventArgs e)
        {
            e.Handled = true;
            //向上找TabItem
            Button button = FLY.ControlLibrary.COMMON.GetParent<Button>(sender as DependencyObject, "button_component" );
            if (button == null)
            {
                //异常
                return;
            }
            string strTipComponentDel = " 组件将要被删除,是否确定";
            if (FLY.ControlLibrary.MyMessageBox.Show(strTipComponentDel) == true)
            {
                var c = button.Tag as MeGraphComponent;
                c.mItem.Components.Remove(c);
                c.Type.Count--;

                Grid g = c.mItem.mTabItem.Content as Grid;
                g.Children.Remove(button);
            }
        }

        private void button_componentEdit_Click(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            var c = button.Tag as MeGraphComponent;

            WdGraphConfig w = new WdGraphConfig();
            w.Init(c, manager.serviceNames);
            w.Owner = FLY.ControlLibrary.COMMON.GetWindow(this);
            if (w.ShowDialog() == true)
            {
                //检测位置是否合法
                if (!c.mItem.IsComponentRectVaild(w.Result.Rect, c))
                {
                    string strError = "错误";
                    string strTipErrorComponentAdd = "组件添加出错";
                    FLY.ControlLibrary.Window_WarningTip.Show(strError, strTipErrorComponentAdd);
                    return;
                }
                c.Rect = w.Result.Rect;
                c.ServiceContainerName = w.Result.ServiceContainerName;
            }
        }



        private void btnBackClick(object sender, RoutedEventArgs e)
        {
            GraphConverter.ToGraphTabItems(Items, gageTabItem);
            NavigationService.GoBack();
        }
    }


}
