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.ComponentModel;

using System.IO;

using System.Net;

using FLY.Thick.Base.Common;
using FLY.Thick.Base.Client;
using FLY.Thick.Base.IService;
using FObjBase;

namespace ThickTcpUiInWindow
{
    /// <summary>
    /// Page_Grid.xaml 的交互逻辑
    /// </summary>
    public partial class Page_Grid : Page, INotifyPropertyChanged
    {
        FlyADService flyad;
        ITDGageService gage;
        IInitParamService initparam;
        DynArea dynarea;

        private Misc.DIRECTION _direction;

        public Misc.DIRECTION Direction
        {
            get { return _direction; }
            set
            {
                if (value != Misc.DIRECTION.FIX)
                {
                    _direction = value;
                    NotifyPropertyChanged("Direction");
                }
            }
        }
        private bool autochange;

        public bool AutoChange
        {
            get { return autochange; }
            set
            {
                if (value != autochange)
                {
                    autochange = value;
                    NotifyPropertyChanged("AutoChange");
                }
            }
        }
        private int _seriescnt = 4;

        public int SeriesCnt
        {
            get { return _seriescnt; }
            set
            {
                if (value < 1)
                {
                    value = 1;
                }
                if (_seriescnt != value)
                {
                    _seriescnt = value;

                    NotifyPropertyChanged("SeriesCnt");
                }
            }
        }

        private int serieIndex = 0;

        public int SerieIndex
        {
            get { return serieIndex; }
            set
            {
                if (serieIndex != value)
                {
                    if (value < 0)
                    {
                        serieIndex = 0;
                    }
                    else if (value >= SeriesCnt)
                    {
                        serieIndex = SeriesCnt - 1;
                    }
                    else
                    {
                        serieIndex = value;
                    }
                    NotifyPropertyChanged("SerieIndex");
                }
            }
        }
        private int _seriesname = 0;

        private int adlag = 0;
        public int ADLag
        {
            get { return adlag; }
            protected set
            {
                if (adlag != value)
                {
                    adlag = value;
                    NotifyPropertyChanged("ADLag");
                }
            }
        }

        private int ppdistance = 0;
        public int PPDistance
        {
            get { return ppdistance; }
            set
            {
                if (ppdistance != value)
                {
                    ppdistance = value;
                    NotifyPropertyChanged("PPDistance");
                }
            }
        }


        public Page_Grid()
        {
            InitializeComponent();
            InitializeComponent2();

            this.DataContext = this;

            SetSeriesCnt(chart1);
            PropertyChanged += new PropertyChangedEventHandler(Page_grid_PropertyChanged);
        }


        void Page_grid_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "SeriesCnt")
            {
                SerieIndex = 0;
                SetSeriesCnt(chart1);
            }
            else if (e.PropertyName == "PPDistance")
            {
                UInt32 outspeed = initparam.VJOG;
                double mmpp = initparam.Encoder1_mmpp;
                double inpout = initparam.Speed1Scale;


                double mpmin = outspeed * inpout * mmpp / 1000 * 60;
                int ms = (int)((PPDistance * mmpp) / mpmin * 60);
                ADLag = ms / 2;
            }
        }
        class SeriesColor
        {
            static List<System.Drawing.Color> c = new List<System.Drawing.Color>();
            static int color_index = 0;
            static SeriesColor()
            {
                c.Add(System.Drawing.Color.Blue);
                c.Add(System.Drawing.Color.Red);
                c.Add(System.Drawing.Color.Green);
                c.Add(System.Drawing.Color.Orange);
                c.Add(System.Drawing.Color.Olive);
                c.Add(System.Drawing.Color.Pink);
                c.Add(System.Drawing.Color.Purple);
                c.Add(System.Drawing.Color.SeaGreen);
                c.Add(System.Drawing.Color.Tomato);
            }
            public static System.Drawing.Color GetColor()
            {
                System.Drawing.Color color = c[color_index];
                color_index++;
                if (color_index >= c.Count)
                    color_index = 0;

                return color;
            }
        }
        void SetSeriesCnt(System.Windows.Forms.DataVisualization.Charting.Chart Chart1)
        {
            while (SeriesCnt < Chart1.Series.Count)
            {
                Chart1.Series.RemoveAt(0);
            }
            //Random r = new Random();
            while (SeriesCnt > Chart1.Series.Count)
            {
                System.Windows.Forms.DataVisualization.Charting.Series series1 = new System.Windows.Forms.DataVisualization.Charting.Series();
                //series1
                series1.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(180)))), ((int)(((byte)(26)))), ((int)(((byte)(59)))), ((int)(((byte)(105)))));
                series1.BorderWidth = 3;

                series1.ChartArea = "Default";
                series1.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;


                series1.Color = SeriesColor.GetColor();

                series1.Legend = "Default";
                //series1.MarkerSize = 6;
                //series1.MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Circle;
                series1.Name = "Series" + _seriesname.ToString();
                _seriesname++;

                series1.ShadowColor = System.Drawing.Color.Black;
                series1.ShadowOffset = 2;
                //series1.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
                //series1.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Double;

                Chart1.Series.Add(series1);
            }

        }
        void InitializeComponent_chart2(System.Windows.Forms.DataVisualization.Charting.Chart Chart1)
        {
            System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
            System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend();
            // 
            // Chart1
            // 
            Chart1.BackColor = System.Drawing.Color.Transparent;
            //Chart1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(211)))), ((int)(((byte)(223)))), ((int)(((byte)(240)))));
            //Chart1.BackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.TopBottom;
            //Chart1.BackSecondaryColor = System.Drawing.Color.White;
            //Chart1.BorderlineColor = System.Drawing.Color.FromArgb(((int)(((byte)(26)))), ((int)(((byte)(59)))), ((int)(((byte)(105)))));
            //Chart1.BorderlineDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
            //Chart1.BorderlineWidth = 2;
            //Chart1.BorderSkin.SkinStyle = System.Windows.Forms.DataVisualization.Charting.BorderSkinStyle.Emboss;
            //下面3D设置都是没有------------------------------------            
            chartArea1.Area3DStyle.Inclination = 15;
            chartArea1.Area3DStyle.IsClustered = true;
            chartArea1.Area3DStyle.IsRightAngleAxes = false;
            chartArea1.Area3DStyle.Perspective = 10;
            chartArea1.Area3DStyle.Rotation = 10;
            chartArea1.Area3DStyle.WallWidth = 0;
            //-------------------------------------------------------

            chartArea1.AxisX.IsLabelAutoFit = false;
            chartArea1.AxisX.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            chartArea1.AxisX.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.AxisX.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.AxisX.ScrollBar.BackColor = System.Drawing.Color.AliceBlue;
            chartArea1.AxisX.ScrollBar.ButtonColor = System.Drawing.SystemColors.Control;
            chartArea1.AxisX.ScrollBar.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));



            chartArea1.AxisY.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            chartArea1.AxisY.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.AxisY.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.AxisY.ScrollBar.BackColor = System.Drawing.Color.AliceBlue;
            chartArea1.AxisY.ScrollBar.ButtonColor = System.Drawing.SystemColors.Control;
            chartArea1.AxisY.ScrollBar.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));



            chartArea1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(165)))), ((int)(((byte)(191)))), ((int)(((byte)(228)))));
            chartArea1.BackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.TopBottom;
            chartArea1.BackSecondaryColor = System.Drawing.Color.White;
            chartArea1.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));


            chartArea1.CursorX.IsUserEnabled = true;
            chartArea1.CursorX.IsUserSelectionEnabled = true;
            chartArea1.CursorX.SelectionColor = System.Drawing.SystemColors.Highlight;
            chartArea1.CursorY.IsUserEnabled = true;
            chartArea1.CursorY.IsUserSelectionEnabled = true;
            chartArea1.CursorY.SelectionColor = System.Drawing.SystemColors.Highlight;
            //chartArea1.InnerPlotPosition.Auto = false;
            //chartArea1.InnerPlotPosition.Height = 75F;
            //chartArea1.InnerPlotPosition.Width = 86.32634F;
            //chartArea1.InnerPlotPosition.X = 11.21863F;
            //chartArea1.InnerPlotPosition.Y = 3.96004F;
            chartArea1.Name = "Default";
            chartArea1.Position.Auto = false;
            chartArea1.Position.Height = 100;
            chartArea1.Position.Width = 100;
            chartArea1.Position.X = 0;// 9.267409F;
            chartArea1.Position.Y = 0;// 10F;
            chartArea1.ShadowColor = System.Drawing.Color.Transparent;
            Chart1.ChartAreas.Add(chartArea1);

            legend1.Name = "Default";
            legend1.BackColor = System.Drawing.Color.Transparent;
            legend1.Enabled = true;
            legend1.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            legend1.IsTextAutoFit = true;
            legend1.Position.Auto = true;// = 0;// 100 - legend1.Position.Width;
            //legend1.Position.Y = 0;
            Chart1.Legends.Add(legend1);
            //Chart1.Location = new System.Drawing.Point(16, 48);
            Chart1.Name = "Chart1";
        }
        void InitializeComponent2()
        {
            InitializeComponent_chart2(chart1);
        }
        public void Init(IPEndPoint serverep, DynArea dynarea, ITDGageService gage, IInitParamService initparam)
        {
            this.gage = gage;
            this.dynarea = dynarea;
            this.initparam = initparam;
            flyad = new FlyADService();
            FObjBase.FObjSys.Current.Connect_to_Another_OBJSys(
                serverep, flyad.ID);
            textblock_position.DataContext = dynarea;
        }
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {


        }

        private void Page_Unloaded(object sender, RoutedEventArgs e)
        {
            flyad.Dispose();
        }


        void DataBindAll(System.Windows.Forms.DataVisualization.Charting.Series series, int[] grid, int posOfGrid)
        {
            series.Points.Clear();
            for (int i = 0; i < grid.Length; i++)
            {
                series.Points.AddXY(i * posOfGrid, grid[i]);
                if (!Misc.MyBase.ISVALIDATA(grid[i]))
                {
                    series.Points[i].IsEmpty = true;
                }
            }
        }
        void SetAxisYRange(System.Windows.Forms.DataVisualization.Charting.Chart chart, int[] grid)
        {
            var gr = from g in grid where Misc.MyBase.ISVALIDATA(g) select g;
            if (gr.Count() > 0)
            {
                double max = gr.Max();
                double min = gr.Min();
                chart1.ChartAreas[0].AxisY.Maximum = max;
                chart1.ChartAreas[0].AxisY.Minimum = min;
            }
        }

        private void button_back_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.GoBack();
        }


        private void button_get_Click(object sender, RoutedEventArgs e)
        {
            flyad.GetGrid(Direction,
                new AsyncCBHandler(
                    delegate(object AsyncState, object retData)
                    {
                        GridInfo g = (GridInfo)retData;
                        DataBindAll(chart1.Series[SerieIndex], g.data, flyad.PosOfGrid);
                        SetAxisYRange(chart1, g.data);
                    }), null);
            if (AutoChange)
            {
                SerieIndex++;
                if (SerieIndex >= SeriesCnt)
                    SerieIndex = 0;
                if (Direction == Misc.DIRECTION.FORWARD)
                {
                    Direction = Misc.DIRECTION.BACKWARD;
                }
                else
                {
                    Direction = Misc.DIRECTION.FORWARD;
                }
            }

        }
        protected void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }


        public event PropertyChangedEventHandler PropertyChanged;

        private void button_save_Click(object sender, RoutedEventArgs e)
        {

            System.Windows.Forms.SaveFileDialog fbd = new System.Windows.Forms.SaveFileDialog();
            fbd.AddExtension = true;
            fbd.DefaultExt = "csv";
            fbd.Filter = "*.csv|csv";
            fbd.FileName = DateTime.Now.ToString("yyyyMMdd_HHmmss");
            if (fbd.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                return;

            string output_path = fbd.FileName;

            string filepath = output_path;
            {
                StreamWriter sw = new StreamWriter(filepath, false, Encoding.GetEncoding("GB2312"));
                for (int j = 0; j < flyad.PosLen / flyad.PosOfGrid; j++)
                {
                    string s = "";
                    s = chart1.Series[0].Points[j].XValue.ToString();
                    for (int i = 0; i < chart1.Series.Count; i++)
                    {
                        s += ",";
                        if (j < chart1.Series[i].Points.Count)
                        {
                            if (Misc.MyBase.ISVALIDATA((int)(chart1.Series[i].Points[j].YValues[0])))
                                s += chart1.Series[i].Points[j].YValues[0].ToString();
                        }
                    }
                    sw.WriteLine(s);
                }
                sw.Flush();
                sw.Close();
            }

            //完成
            FLY.ControlLibrary.Window_Tip.Show("成功", "保存到路径 " + filepath, TimeSpan.FromSeconds(2));
            return;
        }

        private void button_stop_Click(object sender, RoutedEventArgs e)
        {
            gage.StartP2(STARTP2_MODE.STOP);
        }

        private void button_org_Click(object sender, RoutedEventArgs e)
        {
            gage.StartP2(STARTP2_MODE.ORG);
        }

        private void button_forw_Click(object sender, RoutedEventArgs e)
        {
            gage.StartP2(STARTP2_MODE.FORW_UNTIL_STOP);
        }

        private void button_backw_Click(object sender, RoutedEventArgs e)
        {
            gage.StartP2(STARTP2_MODE.BACKW_UNTIL_STOP);
        }

    }
}
