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 ThickTcpUiInWindow.MainEdit
{
    /// <summary>
    /// Page_MainEditGraph.xaml 的交互逻辑
    /// </summary>
    public partial class PgMainEditGraph : Page
    {
        FLYLayoutManager mManager;
        UIModule.FLYLayout mLayout;
        

        ObservableCollection<GraphTabItem> Items;
        ObservableCollection<GraphComponentType> ToolboxItems;
        public PgMainEditGraph()
        {
            InitializeComponent();

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

        public void Init(FLYLayoutManager manager)
        {
            mManager = manager;
            mLayout = mManager.mLayout;
            ToolboxItems = GraphConverter.GetToolboxItems(mManager, true);
            Items = GraphConverter.GetTabItems(mLayout.Items);

            itemsControl_toolbox.ItemsSource = ToolboxItems;
            UpdateTabControl();
        }
        void DefaultData()
        {
            Items = new ObservableCollection<GraphTabItem>();
            //测试
            GraphTabItem item1 = new GraphTabItem() { Title = "扫描" };
            item1.RefreshRC(3, 1);
            item1.Components.Add(
                new GraphComponent()
                {
                    TypeID = "GraphScan",
                    Rect = new System.Drawing.Rectangle(0, 0, 1, 1),
                    mItem = item1
                });
            item1.Components.Add(
                new GraphComponent()
                {
                    TypeID = "GraphScan",
                    Rect = new System.Drawing.Rectangle(0, 1, 1, 1),
                    mItem = item1
                });

            item1.Components.Add(
                new GraphComponent()
                {
                    TypeID = "GraphTrend",
                    Rect = new System.Drawing.Rectangle(0, 2, 1, 1),
                    mItem = item1
                });

            Items.Add(item1);

            GraphTabItem item2 = new GraphTabItem() { Title = "定点" };
            item2.RefreshRC(2, 1);

            item2.Components.Add(
                new GraphComponent()
                {
                    TypeID = "GraphFix",
                    Rect = new System.Drawing.Rectangle(0, 0, 1, 1),
                    mItem = item2
                });
            Items.Add(item2);


        }
        void DefaultToolbox()
        {
            ToolboxItems = new ObservableCollection<GraphComponentType>();
            ToolboxItems.Add(new GraphComponentType()
            {
                ID = "GraphScan",
                Background = new SolidColorBrush(Colors.Gray),
            //Background = new ImageBrush()
            //{
            //    ImageSource = new BitmapImage(new Uri(@"pack://application:,,,/FLY.Thick.Casting.UI.Client;component/Images/graphcomponent03.jpg", UriKind.Absolute))
            //},
            Header = "扫描图"
            });
            ToolboxItems.Add(new GraphComponentType()
            {
                ID = "GraphTrend",
                Background = new SolidColorBrush(Colors.Gray),
                //Background = new ImageBrush()
                //{
                //    ImageSource = new BitmapImage(new Uri(@"pack://application:,,,/FLY.Thick.Casting.UI.Client;component/Images/graphcomponent02.jpg", UriKind.Absolute))
                //},
                Header = "趋势图"
            });
            ToolboxItems.Add(new GraphComponentType()
            {
                ID = "GraphFix",
                Background = new SolidColorBrush(Colors.Gray),
                //Background = new ImageBrush()
                //{
                //    ImageSource = new BitmapImage(new Uri(@"pack://application:,,,/FLY.Thick.Casting.UI.Client;component/Images/graphcomponent01.jpg", UriKind.Absolute))
                //},
                Header = "定点图",
                IsUnique = true
            });
        }

        private void Page_MainEditGraph_RCChanged(GraphTabItem 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 (GraphTabItem 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(GraphTabItem 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, GraphTabItem 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++)
            {
                GraphComponent c = item.Components[i];
                //加入统计
                try
                {
                    GraphComponentType ct = ToolboxItems.First((_ct) =>
                      {
                          if (_ct.ID == c.TypeID)
                              return true;
                          else
                              return false;
                      });
                    //ct.Count++;
                    c.Type = ct;
                }
                catch
                {
                    //异常
                    continue;
                }

                ButtonComponentAdd(grid, c);
            }
        }
        void UpdateComponentTypeCount()
        {
            foreach (GraphComponentType type in ToolboxItems)
            {
                type.Count = Items.Sum(((item) => {
                    return item.Components.Count((c) => { return c.Type == type; });
                }));
            }
        }
        void ButtonComponentAdd(Grid grid, GraphComponent 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(GraphComponent 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")
            {
                GraphComponent c = sender as GraphComponent;
                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 GraphTabItem);
            if (idx < 0)
            {
                //异常
                return;
            }
            //提示是否删除
            string strTipTabItemDel = Application.Current.FindResource("strTipTabItemDel") as string;
            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 GraphTabItem);
            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)
        {
            GraphTabItem item = new GraphTabItem();
            Items.Add(item);
        }

        private void button_componentNew_Click(object sender, RoutedEventArgs e)
        {
            TabItem tabitem = tabcontrol.SelectedItem as TabItem;
            if (tabitem == null)
            {
                string strError = Application.Current.FindResource("strError") as string;
                string strTipNoTabItem = Application.Current.FindResource("strTipNoTabItem") as string;
                FLY.ControlLibrary.Window_WarningTip.Show(strError, strTipNoTabItem);
                return;
            }
            GraphTabItem item = tabitem.Tag as GraphTabItem;

            System.Drawing.Point p = item.GetFreeLocal();
            if (p.X == -1)
            {
                string strError = Application.Current.FindResource("strError") as string;
                string strTipNoSize = Application.Current.FindResource("strTipNoSize") as string;
                FLY.ControlLibrary.Window_WarningTip.Show(strError, strTipNoSize);
                return;
            }
            Button button = sender as Button;
            GraphComponentType gct = button.Tag as GraphComponentType;

            if (!gct.IsEnable)
            {
                string strTipCantAddAgain = Application.Current.FindResource("strTipCantAddAgain") as string;
                FLY.ControlLibrary.MyMessageBox.Show(strTipCantAddAgain);
                return;
            }


            GraphComponent c = new GraphComponent()
            {
                TypeID = gct.ID,
                Type = gct,
                Rect = new System.Drawing.Rectangle(p.X, p.Y, 1, 1)
            };

            WdGraphConfig w = new WdGraphConfig();
            w.Init(c);
            w.Owner = FLY.ControlLibrary.COMMON.GetWindow(this);
            if (w.ShowDialog() == true)
            {
                //检测位置是否合法
                if (!item.IsComponentRectVaild(w.Result.Rect))
                {
                    string strError = Application.Current.FindResource("strError") as string;
                    string strTipErrorComponentAdd = Application.Current.FindResource("strTipErrorComponentAdd") as string;
                    FLY.ControlLibrary.Window_WarningTip.Show(strError, strTipErrorComponentAdd);
                    return;
                }
                c.Rect = w.Result.Rect;

                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 = Application.Current.FindResource("strTipComponentDel") as string;
            if (FLY.ControlLibrary.MyMessageBox.Show(strTipComponentDel) == true)
            {
                GraphComponent c = button.Tag as GraphComponent;
                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;
            GraphComponent c = button.Tag as GraphComponent;

            WdGraphConfig w = new WdGraphConfig();
            w.Init(c);
            w.Owner = FLY.ControlLibrary.COMMON.GetWindow(this);
            if (w.ShowDialog() == true)
            {
                //检测位置是否合法
                if (!c.mItem.IsComponentRectVaild(w.Result.Rect, c))
                {
                    string strError = Application.Current.FindResource("strError") as string;
                    string strTipErrorComponentAdd = Application.Current.FindResource("strTipErrorComponentAdd") as string;
                    FLY.ControlLibrary.Window_WarningTip.Show(strError, strTipErrorComponentAdd);
                    return;
                }
                c.Rect = w.Result.Rect;
            }
        }

        private void button_ok_Click(object sender, RoutedEventArgs e)
        {
            GraphConverter.ToTabItems(Items, mLayout.Items);
            mLayout.Save();
            mManager.MatchParam();
            string strTipRebootForExecute = Application.Current.FindResource("strTipRebootForExecute") as string;
            if (FLY.ControlLibrary.MyMessageBox.Show(strTipRebootForExecute) ==true)
            {
                System.Windows.Forms.Application.Restart();
                Application.Current.Shutdown();
            }
            return;
        }

    }


}
