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 FlyADBase;
using FObjBase;

using System.Net;
using System.ComponentModel;
using Misc;
using System.Threading;
using System.Windows.Threading;
using System.Windows.Forms.DataVisualization.Charting;
using Microsoft.Win32;
using System.IO;
using System.Threading.Tasks;
using Unity;

namespace Flyad7_WPF
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window,INotifyPropertyChanged
    {
        IUnityContainer Container;
        FlyAD7 flyad;
        DebugAppParam param;
        AutoForwBackw autofb;
        FlyADClientUI flyad_clientui;
        AutoSync mAutoSync;
        AutoGetGridAdv autoGetGridAdv;
        GridAdvVm gridAdvVm;
         public MainWindow()
         {
            InitializeComponent();
            InitializeComponent2();
            InitializeComponent3();
            InitializeComponent4();
            Init();
        }

        public void Init() 
        {
            Container = App.Current.Properties["Container"] as IUnityContainer;
            param = Container.Resolve<DebugAppParam>();
            flyad = Container.Resolve<FlyAD7>();
            autofb = Container.Resolve<AutoForwBackw>();
            flyad_clientui = Container.Resolve<FlyADClientUI>();
            autoGetGridAdv = Container.Resolve<AutoGetGridAdv>();
            mAutoSync = Container.Resolve<AutoSync>();
            gridAdvVm = Container.Resolve<GridAdvVm>();
            gridAdvVm.Init(chart3);
            

            this.DataContext = flyad;
            this.grid_viewModel.DataContext = this;
            this.grid_param.DataContext = param;
            this.groupBox_fb.DataContext = autofb;
            this.groupBox_adpos.DataContext = flyad_clientui;
            this.gbAutoGetGridAdv.DataContext = autoGetGridAdv;
            this.gbTimeGridAdv.DataContext = gridAdvVm;

            flyad.GridEvent += flyad_GridEvent;
            flyad.TimeGridEvent += flyad_TimeGridEvent;


            FObjBase.PollModule.Current.Start();
        }

        /// <summary>
        /// grid图
        /// </summary>
        void InitializeComponent2()
        {
            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();
            System.Windows.Forms.DataVisualization.Charting.Series series1 = new System.Windows.Forms.DataVisualization.Charting.Series();
            System.Windows.Forms.DataVisualization.Charting.Series series2 = new System.Windows.Forms.DataVisualization.Charting.Series();

            // 
            // chart1
            // 

            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.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.BackColor = System.Drawing.Color.OldLace;
            //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.BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
            chartArea1.Name = "Default";
            chartArea1.ShadowColor = System.Drawing.Color.Transparent;
            //对数坐标
            //chartArea1.AxisY.IsLogarithmic = true;
            //chartArea1.AxisY.LogarithmBase = Math.E;
            this.chart1.ChartAreas.Add(chartArea1);



            legend1.BackColor = System.Drawing.Color.Transparent;
            legend1.Enabled = true;
            legend1.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            legend1.Alignment = System.Drawing.StringAlignment.Near;
            legend1.Docking = System.Windows.Forms.DataVisualization.Charting.Docking.Right;
            legend1.IsDockedInsideChartArea = true;
            legend1.DockedToChartArea = chartArea1.Name;
            //legend1.IsTextAutoFit = false;
            legend1.Name = "Default";
            chart1.Legends.Add(legend1);

            series1.Name = "Series 1";
            series1.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(180)))), ((int)(((byte)(26)))), ((int)(((byte)(59)))), ((int)(((byte)(105)))));
            series1.BorderWidth = 3;
            series1.ChartArea = chartArea1.Name;
            series1.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            series1.Color = System.Drawing.Color.FromArgb(((int)(((byte)(220)))), ((int)(((byte)(65)))), ((int)(((byte)(140)))), ((int)(((byte)(240)))));
            series1.Legend = legend1.Name;
            series1.LegendText = "正向";
            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.Int32;
            chart1.Series.Add(series1);

            series2.Name = "Series 2";
            series2.BorderColor = System.Drawing.Color.Pink;
            series2.BorderWidth = 3;
            series2.ChartArea = chartArea1.Name;
            series2.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            series2.Color = System.Drawing.Color.Red;
            series2.Legend = legend1.Name;
            series2.LegendText = "反向";
            series2.ShadowColor = System.Drawing.Color.Black;
            series2.ShadowOffset = 2;
            series2.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
            series2.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
            chart1.Series.Add(series2);

            //this.chart1.Location = new System.Drawing.Point(16, 32);
            chart1.Name = "chart1";

            chart1.BackColor = System.Drawing.Color.Transparent;
        }
        void InitializeComponent3()
        {
            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();
            System.Windows.Forms.DataVisualization.Charting.Series series1 = new System.Windows.Forms.DataVisualization.Charting.Series();

            // 
            // chart1
            // 

            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.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.BackColor = System.Drawing.Color.OldLace;
            //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.BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
            chartArea1.Name = "Default";
            chartArea1.ShadowColor = System.Drawing.Color.Transparent;
            //对数坐标
            //chartArea1.AxisY.IsLogarithmic = true;
            //chartArea1.AxisY.LogarithmBase = Math.E;
            this.chart2.ChartAreas.Add(chartArea1);



            legend1.BackColor = System.Drawing.Color.Transparent;
            legend1.Enabled = false;
            legend1.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            legend1.IsTextAutoFit = false;
            legend1.Name = "Default";
            this.chart2.Legends.Add(legend1);
            //this.chart2.Location = new System.Drawing.Point(16, 32);
            this.chart2.Name = "chart2";
            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 = System.Drawing.Color.FromArgb(((int)(((byte)(220)))), ((int)(((byte)(65)))), ((int)(((byte)(140)))), ((int)(((byte)(240)))));
            series1.Legend = "Default";
            //series1.MarkerSize = 8;
            //series1.MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Circle;
            series1.Name = "Series 1";
            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.Int32;

            this.chart2.Series.Add(series1);

            this.chart2.BackColor = System.Drawing.Color.Transparent;
        }

        void InitializeComponent4()
        {
            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();
            System.Windows.Forms.DataVisualization.Charting.Series series1 = new System.Windows.Forms.DataVisualization.Charting.Series();
            System.Windows.Forms.DataVisualization.Charting.Series series2 = new System.Windows.Forms.DataVisualization.Charting.Series();

            // 
            // chart1
            // 

            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.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.BackColor = System.Drawing.Color.OldLace;
            //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.BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
            chartArea1.Name = "Default";
            chartArea1.ShadowColor = System.Drawing.Color.Transparent;
            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.AxisY.IsLogarithmic = true;
            //chartArea1.AxisY.LogarithmBase = Math.E;
            chart3.ChartAreas.Add(chartArea1);



            legend1.BackColor = System.Drawing.Color.Transparent;
            legend1.Enabled = true;
            legend1.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            legend1.Alignment = System.Drawing.StringAlignment.Near;
            legend1.Docking = System.Windows.Forms.DataVisualization.Charting.Docking.Right;
            legend1.IsDockedInsideChartArea = true;
            legend1.DockedToChartArea = chartArea1.Name;
            //legend1.IsTextAutoFit = false;
            legend1.Name = "Default";
            chart3.Legends.Add(legend1);

            series1.Name = "Series 1";
            series1.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(180)))), ((int)(((byte)(26)))), ((int)(((byte)(59)))), ((int)(((byte)(105)))));
            series1.BorderWidth = 3;
            series1.ChartArea = chartArea1.Name;
            series1.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            series1.Color = System.Drawing.Color.FromArgb(((int)(((byte)(220)))), ((int)(((byte)(65)))), ((int)(((byte)(140)))), ((int)(((byte)(240)))));
            series1.Legend = legend1.Name;
            series1.LegendText = "Series 1";
            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.Int32;
            chart3.Series.Add(series1);

            series2.Name = "Series 2";
            series2.BorderColor = System.Drawing.Color.Pink;
            series2.BorderWidth = 3;
            series2.ChartArea = chartArea1.Name;
            series2.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            series2.Color = System.Drawing.Color.Red;
            series2.Legend = legend1.Name;
            series2.LegendText = "Series 2";
            series2.ShadowColor = System.Drawing.Color.Black;
            series2.ShadowOffset = 2;
            series2.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
            series2.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
            chart3.Series.Add(series2);

            //this.chart1.Location = new System.Drawing.Point(16, 32);
            chart3.Name = "chart3";

            chart3.BackColor = System.Drawing.Color.Transparent;
        }
        #region grid
        void flyad_GridEvent(object sender, MiniGridEventArgs e)
        {
            if (!param.HasGrid)
                return;

            run_gridmarker.Text = e.marker.ToString();

            System.Windows.Forms.DataVisualization.Charting.Series series_forw = chart1.Series["Series 1"];
            System.Windows.Forms.DataVisualization.Charting.Series series_backw = chart1.Series["Series 2"];
            System.Windows.Forms.DataVisualization.Charting.Series series;
            
            series = (e.direction == DIRECTION.FORWARD) ? series_forw : series_backw;

            series.Points.Clear();

            int gridLen = flyad.PosLen / flyad.PosOfGrid;



            for (int i = 0; i < e.buf.Length; i++)
            {
                int pos = (e.grid_start + i) * flyad.PosOfGrid;
                int ad = e.buf[i];
                series.Points.AddXY(pos, ad);
                if (ad == Misc.MyBase.NULL_VALUE)
                    series.Points[i].IsEmpty = true;
            }
                
            chart1.ChartAreas[0].AxisX.Minimum = 0;
            chart1.ChartAreas[0].AxisX.Maximum = flyad.PosLen;
            
        }


        private void button_cleargrid_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.DataVisualization.Charting.Series series_forw = chart1.Series["Series 1"];
            System.Windows.Forms.DataVisualization.Charting.Series series_backw = chart1.Series["Series 2"];
            
            series_forw.Points.Clear();
            series_backw.Points.Clear();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            GetGrid(Misc.DIRECTION.FORWARD);
        }
        private void GetGrid(Misc.DIRECTION dir)
        {
            System.Windows.Forms.DataVisualization.Charting.Series series_forw = chart1.Series["Series 1"];
            System.Windows.Forms.DataVisualization.Charting.Series series_backw = chart1.Series["Series 2"];
            System.Windows.Forms.DataVisualization.Charting.Series series;

            if (dir == DIRECTION.FORWARD)
                series = series_forw;
            else
                series = series_backw;
            int[] data;
            int gridLen = flyad.PosLen / flyad.PosOfGrid;
            flyad.GetGrid(dir, 0, gridLen, out data);
            series.Points.Clear();
            for (int i = 0; i < data.Length; i++)
            {
                int ad = data[i];
                int pos = i * flyad.PosOfGrid;
                series.Points.AddXY(pos, ad);
                if (ad == Misc.MyBase.NULL_VALUE)
                    series.Points[i].IsEmpty = true;
                else
                    series.Points[i].IsEmpty = false;
            }
            series.Points.Add(30000);

            int max = Misc.MyMath.Max(data, 0, data.Length - 1);
            int min = Misc.MyMath.Min(data, 0, data.Length - 1);
            if (max == Misc.MyBase.NULL_VALUE)
            {
                max = 60000;
                min = 0;
            }

            int mid = max;
            max += 10;
            min -= 10;
            chart1.ChartAreas[0].AxisY.Maximum = max;
            chart1.ChartAreas[0].AxisY.Minimum = min;

            chart1.ChartAreas[0].AxisX.Minimum = 0;
            chart1.ChartAreas[0].AxisX.Maximum = flyad.PosLen;
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            GetGrid(Misc.DIRECTION.BACKWARD);
        }
        #endregion

        int timecnt = 0;
        class MaxMin 
        {
            /// <summary>
            /// 最大值
            /// </summary>
            public int max;
            /// <summary>
            /// 最小值
            /// </summary>
            public int min;
            /// <summary>
            /// 数量
            /// </summary>
            public int len;
        }
        List<MaxMin> mMMList = new List<MaxMin>();

        public event PropertyChangedEventHandler PropertyChanged;

        void flyad_TimeGridEvent(object sender, TimeGridEventArgs e)
        {
            if (!param.HasTimeGrid)
                return;
            MaxMin mm;
            while (timecnt > 5000)
            {
                //被删除对象
                mm = mMMList.First();
                for (int i = 0; i < mm.len; i++)
                {
                    chart2.Series["Series 1"].Points.RemoveAt(0);
                }
                timecnt -= mm.len;
                mMMList.RemoveAt(0);
            }
            mMMList.Add(
                new MaxMin(){
                    len = e.Data.Length, 
                    min = e.Data.Min(),
                    max = e.Data.Max()});

            for (int i = 0; i < mMMList.Last().len; i++)
            {
                int ad = e.Data[i];
                chart2.Series["Series 1"].Points.Add(ad);
            }

            int max = (from i in mMMList select i.max).Max();
            int min = (from i in mMMList select i.min).Min();

            if (max == min)
            {
                min -= 10;
                max += 10;
            }
            chart2.ChartAreas[0].AxisY.Maximum = max;
            chart2.ChartAreas[0].AxisY.Minimum = min;
            timecnt += mMMList.Last().len;
        }




        private void button_connect1_Click(object sender, RoutedEventArgs e)
        {
            IPEndPoint result = Misc.StringConverter.ToIPEndPoint(param.EPStr);
            
            flyad.Connect(result);
            button_connect.IsEnabled = false;
            textbox_ip.IsEnabled = false;
        }

        private void button_output_Click(object sender, RoutedEventArgs e)
        {
            string output = textbox_output.Text;
            flyad.SetOutput(UInt16.MaxValue, Convert.ToUInt16(output, 2));
        }

        private void button_runto_Click(object sender, RoutedEventArgs e)
        {
            int pos;

            if (int.TryParse(textBox_to.Text, out pos)) 
            {
                flyad.Runto(pos);
            }
        }

        private void button_org_Click(object sender, RoutedEventArgs e)
        {
            flyad.Origin();
        }

        private void button_stop_Click(object sender, RoutedEventArgs e)
        {
            flyad.Stop();
        }

        private void button_backw_Click(object sender, RoutedEventArgs e)
        {
            flyad.Backward();
        }

        private void button_forw_Click(object sender, RoutedEventArgs e)
        {
            flyad.Forward();
        }
        



        private void button_initarea_Click(object sender, RoutedEventArgs e)
        {
            
            Window_InitArea w = new Window_InitArea();
            w.Init(flyad);
            w.Show();
        }

        private void button_setaccess_Click(object sender, RoutedEventArgs e)
        {
            
            Window_setAccess w = new Window_setAccess();
            w.Init(flyad);
            w.Show();
        }

        private void button_sync_Click(object sender, RoutedEventArgs e)
        {
            if (!Window_sync.HasOpen)
            {
                Window_sync w = new Window_sync();
                w.Init(flyad, mAutoSync);
                w.Show();
            }
        }

        private void button_save_velocity_Click(object sender, RoutedEventArgs e)
        {
            param.Velocity = flyad.Velocity;
            param.SVelocity = flyad.SVelocity;
            param.ATime = flyad.ATime;
            param.DTime = flyad.DTime;
            param.HVelocity1 = flyad.HVelocity1;
            param.HVelocity2 = flyad.HVelocity2;
            param.PosLen = flyad.PosLen;
            param.ADLag = flyad.ADLag;
            MessageBox.Show("保存成功");
        }

        private void button_load_velocity_Click(object sender, RoutedEventArgs e)
        {
            param.Load();
            flyad.Velocity = param.Velocity;
            flyad.SVelocity = param.SVelocity;
            flyad.ATime = param.ATime;
            flyad.DTime = param.DTime;
            flyad.HVelocity1 = param.HVelocity1;
            flyad.HVelocity2 = param.HVelocity2;
            flyad.PosLen = param.PosLen;
            flyad.ADLag = param.ADLag;

            MessageBox.Show("加载成功");
        }

        private void button_setbit_Click(object sender, RoutedEventArgs e)
        {
            var btn = sender as Button;
            if (!int.TryParse((btn.Tag as string), out int index))
                return;

            if (Misc.MyBase.CHECKBIT(flyad.OStatus, index))
                flyad.SetOutputBit(index, false);
            else
                flyad.SetOutputBit(index, true);
            
        }

        private void button_runto0_Click(object sender, RoutedEventArgs e)
        {
            flyad.RuntoMin();
        }

        private void button_runtoPosLen_Click(object sender, RoutedEventArgs e)
        {
            flyad.RuntoMax();
        }

        private void button_gridSave_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.DataVisualization.Charting.Series series_forw = chart1.Series["Series 1"];
            System.Windows.Forms.DataVisualization.Charting.Series series_backw = chart1.Series["Series 2"];

            string strDesktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            string path = System.IO.Path.Combine(strDesktopPath, $"grid_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.csv");
            StreamWriter sw = new StreamWriter(path);
            //int count = Math.Max(series_forw.Points.Count(), series_backw.Points.Count());
            sw.WriteLine($"Index,Forw,Backw");
            int gridLen = flyad.PosLen / flyad.PosOfGrid;
            for (int i = 0; i < gridLen; i++)
            {
                int f_v = Misc.MyBase.NULL_VALUE;
                int b_v = Misc.MyBase.NULL_VALUE;
                if (i < series_forw.Points.Count)
                    f_v = (int)(series_forw.Points[i].YValues[0]);
                if (i < series_backw.Points.Count)
                    b_v = (int)(series_backw.Points[i].YValues[0]);

                sw.WriteLine($"{i},{f_v},{b_v}");
            }
            sw.Flush();
            sw.Close();

            MessageBox.Show($"成功保存到 {path}");

        }


        DispatcherTimer timer = new DispatcherTimer();
        bool isTimerInited = false;
        public int OutIdx { get; private set; }
        public bool IsAutoOutRunning { get; private set; }
        void TimerInit() {
            timer.Tick += (s, e) =>
            {
                flyad.SetOutputBit(OutIdx, true);
                OutIdx += 1;
                if (OutIdx > 7)
                    OutIdx = 0;
                flyad.SetOutputBit(OutIdx, false);
            };
            timer.Interval = TimeSpan.FromSeconds(1);
        }

        private void btnAutoOutClick(object sender, RoutedEventArgs e)
        {
            if (!isTimerInited) {
                TimerInit();
            }
            if (timer.IsEnabled)
            {
                timer.Stop();
                IsAutoOutRunning = false;
            }
            else {
                timer.Start();
                IsAutoOutRunning = true;
                    
            }
        }
    }

}
