using FLY.ControlLibrary;
using FLY.Thick.BulkDataModule;
using FLY.UI.Module;
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.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.UIModule
{
    /// <summary>
    /// TrendGraph.xaml 的交互逻辑
    /// </summary>
    public partial class TrendGraph : Page
    {
        TrendGraphItemParam graphparam;
        public TrendGraph()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        public void Init(int id)
        {
            graphparam = TrendGraphParams.Current.Items.Find(p => p.ID == id);
            if (graphparam == null)
            {
                graphparam = new TrendGraphItemParam() { ID = id };
                TrendGraphParams.Current.Items.Add(graphparam);
                TrendGraphParams.Current.Save();
            }

            //获取设备
            TDGage gage = Application.Current.Properties["Gage"] as TDGage;

            GraphRange graph = graphrange;
            graph.DataContext = graphparam;
            //graph.SetValue(GraphRange.MarginProperty, new Thickness(5));

            graph.SetBinding(Grid.ColumnProperty, new Binding("Column"));
            graph.SetBinding(Grid.RowProperty, new Binding("Row"));
            graph.SetBinding(Grid.ColumnSpanProperty, new Binding("ColumnSpan"));
            graph.SetBinding(Grid.RowSpanProperty, new Binding("RowSpan"));

            graph.SetBinding(GraphRange.DataCntProperty, new Binding("Len"));
            graph.SetBinding(GraphRange.TitleProperty, new Binding("Title"));
            graph.SetBinding(GraphRange.IsAutoTargetProperty, new Binding("IsAutoTarget"));
            graph.SetBinding(GraphRange.IsPercentProperty, new Binding("IsPercent"));
            graph.SetBinding(GraphRange.YRangePercentProperty, new Binding("YRangePercent"));
            graph.SetBinding(GraphRange.TypeProperty, new Binding("Type"));
            graph.SetBinding(GraphRange.XAxisTypeProperty, new Binding("XType"));

            graph.SetBinding(GraphRange.TargetProperty, new Binding("Target") { Source = gage.mDynAreaService.mDynArea });
            graph.SetBinding(GraphRange.AlarmProperty, new Binding("Alarm") { Source = gage.mDynAreaService.mDynArea });


            BulkDataServiceClientAdv.BulkDataGraphTrend bulkdata_client = new BulkDataServiceClientAdv.BulkDataGraphTrend();

            Misc.BindingOperations.SetBinding(graphparam, "BM", bulkdata_client, "BM", Misc.BindingOperations.BindingMode.OneWay);
            Misc.BindingOperations.SetBinding(graphparam, "Mix", bulkdata_client, "Mix", Misc.BindingOperations.BindingMode.OneWay);
            Misc.BindingOperations.SetBinding(graphparam, "Len", bulkdata_client, "Len", Misc.BindingOperations.BindingMode.OneWay);

            Misc.BindingOperations.SetBinding(graphparam, new string[] { "BeginNo", "IsAll" }, delegate ()
            {
                if (graphparam.IsAll)
                    bulkdata_client.FromBoltNo = Misc.MyBase.NULL_VALUE;
                else
                    bulkdata_client.FromBoltNo = graphparam.BeginNo;
            });

            Misc.BindingOperations.SetBinding(graphparam, "EndNo", bulkdata_client, "ToBoltNo", Misc.BindingOperations.BindingMode.OneWay);

            GraphRangeDataValueChanged vc = new GraphRangeDataValueChanged();
            vc.Init(bulkdata_client.Frame, graph);

            graph.SetBinding(GraphRange.Title2Property, new Binding("Info") { Source = bulkdata_client });


            graph.ShowSettingDialogEvent += new EventHandler(delegate (object sender, EventArgs e)
            {
                TrendGraphConfig w = new TrendGraphConfig();

                TrendGraphItemParam graphparam_src = (sender as GraphRange).DataContext as TrendGraphItemParam;

                w.DataContext = graphparam_src;
                w.SaveEvent += (s, ea) =>
                {
                    TrendGraphParams.Current.Save();
                };
                w.Owner = FLY.ControlLibrary.COMMON.GetWindow(graph);
                w.ShowDialog();
            });

            //BulkDataServiceClientAdv mBulkDataClient;
            //if (mBulkDataClients.ContainsKey(graphparam.BulkData))
            //    mBulkDataClient = mBulkDataClients[graphparam.BulkData];
            //else
            //    mBulkDataClient = mBulkDataClients.First().Value;

            gage.mBulkDataClient.Add(bulkdata_client);
        }


        public class GraphRangeDataValueChanged
        {
            ObservableCollection<GraphRangeData> rangedata = new ObservableCollection<GraphRangeData>();

            public void Init(ObservableCollection<TrendDataCell> Frame, GraphRange graph)
            {
                Frame.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(trenddata_CollectionChanged);
                graph.DataSource = rangedata;
            }
            void trenddata_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
            {
                switch (e.Action)
                {
                    case System.Collections.Specialized.NotifyCollectionChangedAction.Add:
                        foreach (TrendDataCell v in e.NewItems)
                        {
                            rangedata.Add(
                                new GraphRangeData()
                                {
                                    Avg = v.Avg,
                                    Sigma = v.Sigma,
                                    Time = v.Time,
                                    InCtrl = (v.Type == FR_DATA_TYPE.VALID)
                                });
                        }
                        break;
                    case System.Collections.Specialized.NotifyCollectionChangedAction.Reset:
                        {
                            rangedata.Clear();
                        }
                        break;
                    case System.Collections.Specialized.NotifyCollectionChangedAction.Replace:
                        {
                            for (int i = 0; i < e.OldItems.Count; i++)
                            {
                                TrendDataCell v = (TrendDataCell)e.NewItems[i];
                                rangedata[i + e.OldStartingIndex] = new GraphRangeData()
                                {
                                    Avg = v.Avg,
                                    Sigma = v.Sigma,
                                    Time = v.Time,
                                    InCtrl = (v.Type == FR_DATA_TYPE.VALID)
                                };
                            }
                        }
                        break;
                    case System.Collections.Specialized.NotifyCollectionChangedAction.Remove:
                        {
                            for (int i = 0; i < e.OldItems.Count; i++)
                            {
                                rangedata.RemoveAt(i + e.OldStartingIndex);
                            }
                        }
                        break;
                }
            }


        }
    }

    /// <summary>
    /// 趋势图的参数
    /// </summary>
    public class TrendGraphItemParam : UIModuleParam
    {
        private int len = 120;
        /// <summary>
        /// 数据量
        /// </summary>
        public int Len
        {
            get { return len; }
            set
            {
                if (len != value)
                {
                    len = value;
                    NotifyPropertyChanged("Len");
                }
            }
        }

        private int beginno = 0;
        /// <summary>
        /// 统计开始数据序号
        /// </summary>
        public int BeginNo
        {
            get
            {
                return beginno;
            }
            set
            {

                if (beginno != value)
                {
                    beginno = value;
                    NotifyPropertyChanged("BeginNo");
                }
            }
        }
        private int endno = 20;
        /// <summary>
        /// 统计结束数据序号
        /// </summary>
        public int EndNo
        {
            get { return endno; }
            set
            {
                if (endno != value)
                {
                    endno = value;
                    NotifyPropertyChanged("EndNo");
                }
            }
        }
        private bool isall = true;
        /// <summary>
        /// 全部数据
        /// </summary>
        public bool IsAll
        {
            get { return isall; }
            set
            {
                if (isall != value)
                {
                    isall = value;
                    NotifyPropertyChanged("IsAll");
                }
            }
        }

        private FLY.ControlLibrary.GraphRangeType type = FLY.ControlLibrary.GraphRangeType.Avg;
        /// <summary>
        /// 曲线类型
        /// </summary>
        public FLY.ControlLibrary.GraphRangeType Type
        {
            get { return type; }
            set
            {
                if (type != value)
                {
                    type = value;
                    NotifyPropertyChanged("Type");
                }
            }
        }

        private FLY.ControlLibrary.GraphRangeXAxisType xtype = FLY.ControlLibrary.GraphRangeXAxisType.Time;
        /// <summary>
        /// X轴类型
        /// </summary>
        public FLY.ControlLibrary.GraphRangeXAxisType XType
        {
            get { return xtype; }
            set
            {
                if (xtype != value)
                {
                    xtype = value;
                    NotifyPropertyChanged("XType");
                }
            }
        }

        private int bm = 0;
        /// <summary>
        /// 记录点
        /// </summary>
        public int BM
        {
            get
            {
                return bm;
            }
            set
            {
                if (bm != value)
                {
                    bm = value;
                    NotifyPropertyChanged("BM");
                }
            }
        }

        private double _yrangepercent = 3;
        /// <summary>
        /// Y轴比例
        /// </summary>
        public double YRangePercent
        {
            get
            {
                return _yrangepercent;
            }
            set
            {
                _yrangepercent = value;
                NotifyPropertyChanged("YRangePercent");
            }
        }

        private string title = "趋势图";
        /// <summary>
        /// 标题
        /// </summary>
        public string Title
        {
            get { return title; }
            set
            {
                if (title != value)
                {
                    title = value;
                    NotifyPropertyChanged("Title");
                }
            }
        }

        private int mix = 1;
        /// <summary>
        /// 混合图
        /// </summary>
        public int Mix
        {
            get
            {
                return mix;
            }
            set
            {
                if (mix != value)
                {
                    mix = value;
                    NotifyPropertyChanged("Mix");
                }
            }
        }


        private bool isautotarget = false;
        /// <summary>
        /// 自动目标值
        /// </summary>
        public bool IsAutoTarget
        {
            get
            {
                return isautotarget;
            }
            set
            {
                if (isautotarget != value)
                {
                    isautotarget = value;
                    NotifyPropertyChanged("IsAutoTarget");
                }
            }
        }

        private bool ispercent = false;
        /// <summary>
        /// % 显示
        /// </summary>
        public bool IsPercent
        {
            get
            {
                return ispercent;
            }
            set
            {
                if (ispercent != value)
                {
                    ispercent = value;
                    NotifyPropertyChanged("IsPercent");
                }
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override string[] GetSavePropertyNames()
        {
            List<string> names = new List<string>(base.GetSavePropertyNames());
            names.AddRange(new string[]{
                "Len", "BeginNo", "EndNo","IsAll","Type","XType",
                "Title","BM","Mix","YRangePercent","IsAutoTarget","IsPercent"
            });
            return names.ToArray();
        }
    }

    /// <summary>
    /// 全部扫描图的参数
    /// </summary>
    public class TrendGraphParams : UIModuleParams<TrendGraphItemParam>
    {

        static TrendGraphParams()
        {
            Misc.SaveToXmlHepler.Regist(typeof(TrendGraphParams));
        }
        public TrendGraphParams()
        {
            string path = System.IO.Path.Combine(FLYLayout.BasePath, "trendgraph.xml");
            FilePath = path;
        }

        static TrendGraphParams current = null;
        public static TrendGraphParams Current
        {
            get
            {
                if (current == null)
                {
                    current = new TrendGraphParams();
                    current.Load();
                }
                return current;
            }
        }
    }

    /// <summary>
    /// 扫描图控件模块
    /// </summary>
    public class UIModule_TrendGraph : IUIModule
    {

        /// <summary>
        /// 控件标题
        /// 它的值取决于culture
        /// </summary>
        public string Title
        {
            get
            {
                return Application.Current.FindResource("strTrendGraph") as string;
            }
        }

        /// <summary>
        /// 控件
        /// 创建时，需要给它唯一ID，让加载自己的数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public FrameworkElement GetComponent(int id)
        {
            TrendGraph graph = new TrendGraph();
            graph.Init(id);
            return graph;
        }

        /// <summary>
        /// 控件缩略图，用于编辑界面时，大致看看
        /// 创建时，需要给它唯一ID，让加载自己的数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public FrameworkElement GetThumbnail(int id)
        {
            return new Grid();
        }

        /// <summary>
        /// 给出全部控件ID, 控件自行删除没有的参数
        /// </summary>
        /// <param name="IDs"></param>
        public void MatchParam(int[] IDs)
        {
            TrendGraphParams.Current.MatchParam(IDs);
        }
    }
}
