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.Shapes;
using System.ComponentModel;

using System.IO;
using System.Windows.Forms.DataVisualization.Charting;
using System.Drawing;

using FLY.Thick.Base.Common;

namespace ThickTcpUiInWindow
{
    /// <summary>
    /// Window_HistoryScan2.xaml 的交互逻辑
    /// </summary>
    public partial class Window_HistoryScan2 : Window, INotifyPropertyChanged, IWindowHistoryReader
    {
        #region 成员变量
        public List<string> Paths = new List<string>();//打开数据的路径
        List<FlyData_ScanHistory> mDatas = new List<FlyData_ScanHistory>();//所有数据
        class TrendData
        {
            public DateTime Time;
            public int Avg;
            public int Sigma2;
        }
        class ScanData
        {
            public int Avg;
            public int Sigma2;
        }
        List<TrendData> mTrendDatas = new List<TrendData>();

        private int mix = 6;
        public int Mix
        {
            get { return mix; }
            set
            {
                if (mix != value)
                {
                    mix = value;
                    NotifyPropertyChanged("Mix");
                }
            }
        }
        private int total = 0;
        public int Total
        {
            get { return total; }
            set
            {
                if (total != value)
                {
                    total = value;
                    NotifyPropertyChanged("Total");
                }
            }
        }
        private int index = 0;
        public int Index
        {
            get { return index; }
            set
            {
                if (index != value)
                {
                    index = value;
                    NotifyPropertyChanged("Index");
                }
            }
        }

        string productname;

        public string ProductName
        {
            get { return productname; }
            set
            {
                if (productname != value)
                {
                    productname = value;
                    NotifyPropertyChanged("ProductName");
                }
            }
        }



        DateTime timebegin;

        public DateTime TimeBegin
        {
            get { return timebegin; }
            set
            {
                if (timebegin != value)
                {
                    timebegin = value;
                    NotifyPropertyChanged("TimeBegin");
                }
            }
        }


        DateTime timeend;

        public DateTime TimeEnd
        {
            get { return timeend; }
            set
            {
                if (timeend != value)
                {
                    timeend = value;
                    NotifyPropertyChanged("TimeEnd");
                }
            }
        }



        int tempad;

        public int TempAD
        {
            get { return tempad; }
            set
            {
                if (tempad != value)
                {
                    tempad = value;
                    NotifyPropertyChanged("TempAD");
                }
            }
        }

        int samplead;

        public int SampleAD
        {
            get { return samplead; }
            set
            {
                if (samplead != value)
                {
                    samplead = value;
                    NotifyPropertyChanged("SampleAD");
                }
            }
        }


        double comp;

        public double Comp
        {
            get { return comp; }
            set
            {
                if (comp != value)
                {
                    comp = value;
                    NotifyPropertyChanged("Comp");
                }
            }
        }

        int shift;

        public int Shift
        {
            get { return shift; }
            set
            {
                if (shift != value)
                {
                    shift = value;
                    NotifyPropertyChanged("Shift");
                }
            }
        }


        DateTime time;

        public DateTime Time
        {
            get { return time; }
            set
            {
                if (time != value)
                {
                    time = value;
                    NotifyPropertyChanged("Time");
                }
            }
        }


        int target;

        public int Target
        {
            get { return target; }
            set
            {
                if (target != value)
                {
                    target = value;
                    NotifyPropertyChanged("Target");
                }
            }
        }


        int alarm;

        public int Alarm
        {
            get { return alarm; }
            set
            {
                if (alarm != value)
                {
                    alarm = value;
                    NotifyPropertyChanged("Alarm");
                }
            }
        }


        int avg;

        public int Avg
        {
            get { return avg; }
            set
            {
                if (avg != value)
                {
                    avg = value;
                    NotifyPropertyChanged("Avg");
                }
            }
        }

        int autotarget;

        public int AutoTarget
        {
            get { return autotarget; }
            set
            {
                if (autotarget != value)
                {
                    autotarget = value;
                    NotifyPropertyChanged("AutoTarget");
                }
            }
        }

        double yrangepercent = 1;

        public double YRangePercent
        {
            get { return yrangepercent; }
            set
            {
                if (yrangepercent != value)
                {
                    yrangepercent = value;
                    NotifyPropertyChanged("YRangePercent");
                }
            }
        }

        #endregion





        public Window_HistoryScan2()
        {
            InitializeComponent();
            InitializeComponent_chart_scan();
            InitializeComponent_chart_trend();
            InitializeComponent_chart_sigma();
            InitializeComponent_chart_ud();
            InitializeComponent_chart_convolution();
        }

        public bool? ShowDialog(IEnumerable<string> paths, string productName)
        {
            Paths.Clear();
            Paths.AddRange(paths);
            ProductName = productName;
            return ShowDialog();
        }
        void InitializeComponent_chart_scan()
        {
            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();

            // 
            // chart_scan
            // 

            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.IsMarksNextToAxis = false;

            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.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.AxisX.Interval = 5;
            //chartArea1.Position.Height = 100;// 42F;
            //chartArea1.Position.Width = 100;// 88F;
            //chartArea1.Position.X = 0;// 3F;
            //chartArea1.Position.Y = 0;// 10F;

            //chartArea1.ShadowColor = System.Drawing.Color.Transparent;
            chart_scan.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.chart1.Legends.Add(legend1);
            //this.chart1.Location = new System.Drawing.Point(16, 32);
            chart_scan.Name = "chart_scan";
            series1.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(180)))), ((int)(((byte)(26)))), ((int)(((byte)(59)))), ((int)(((byte)(105)))));
            series1.BorderWidth = 2;

            series1.ChartArea = "Default";
            //TODO
            series1.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Column;

            series1.Color = System.Drawing.Color.FromArgb(((int)(((byte)(220)))), ((int)(((byte)(65)))), ((int)(((byte)(140)))), ((int)(((byte)(240)))));

            series1.Legend = "Default";
            series1.MarkerSize = 6;
            //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.Double;


            chart_scan.Series.Add(series1);

            chart_scan.BackColor = System.Drawing.Color.Transparent;
        }
        void InitializeComponent_chart_trend()
        {
            System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend();
            System.Windows.Forms.DataVisualization.Charting.Legend legend2 = new System.Windows.Forms.DataVisualization.Charting.Legend();

            System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea_trend = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
            System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea_samplead = new System.Windows.Forms.DataVisualization.Charting.ChartArea();

            //纵向趋势
            System.Windows.Forms.DataVisualization.Charting.Series series_trend = new System.Windows.Forms.DataVisualization.Charting.Series();

            //纵向Range趋势
            System.Windows.Forms.DataVisualization.Charting.Series series_trendrange = new System.Windows.Forms.DataVisualization.Charting.Series();

            //温修AD
            System.Windows.Forms.DataVisualization.Charting.Series series_tempad = new System.Windows.Forms.DataVisualization.Charting.Series();
            //样品AD
            System.Windows.Forms.DataVisualization.Charting.Series series_samplead = new System.Windows.Forms.DataVisualization.Charting.Series();

            Chart chart = chart_trend;

            chart.Name = "chart_trend";
            // 
            // chartArea_trend
            // 
            chartArea_trend.Name = "Trend";
            chartArea_trend.AxisX.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            //chartArea_trend.AxisX.LabelStyle.Format = "HH:mm";
            chartArea_trend.AxisX.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea_trend.AxisX.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea_trend.AxisX.IsMarksNextToAxis = false;


            chartArea_trend.AxisY.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            chartArea_trend.AxisY.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea_trend.AxisY.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea_trend.AxisY.IsStartedFromZero = false;



            chartArea_trend.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea_trend.BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
            chart.ChartAreas.Add(chartArea_trend);
            //chartArea_trend.Position.Auto = true;

            chartArea_trend.Position.Height = 50;// 42F;
            chartArea_trend.Position.Width = 100;// 88F;
            chartArea_trend.Position.X = 0;// 3F;
            chartArea_trend.Position.Y = 0;// 10F;

            // 
            // chartArea_samplead
            // 
            chartArea_samplead.Name = "SampleAD";
            chartArea_samplead.AxisX.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            //chartArea_samplead.AxisX.LabelStyle.Format = "HH:mm";
            chartArea_samplead.AxisX.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea_samplead.AxisX.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea_samplead.AxisX.IsMarksNextToAxis = false;

            chartArea_samplead.AxisY.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            chartArea_samplead.AxisY.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea_samplead.AxisY.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea_samplead.AxisY.IsStartedFromZero = false;
            chartArea_samplead.AxisY2.IsStartedFromZero = false;

            chartArea_samplead.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea_samplead.BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
            chart.ChartAreas.Add(chartArea_samplead);
            chartArea_samplead.Position.Height = 50;// 42F;
            chartArea_samplead.Position.Width = 100;// 88F;
            chartArea_samplead.Position.X = 0;// 3F;
            chartArea_samplead.Position.Y = 50;// 10F;

            chartArea_samplead.AlignWithChartArea = chartArea_trend.Name;


            legend1.Name = "Default";
            legend1.BackColor = System.Drawing.Color.White;
            legend1.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            legend1.Enabled = true;
            legend1.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            legend1.IsTextAutoFit = true;
            chart.Legends.Add(legend1);
            legend1.Position.Auto = true;// false;
            legend1.IsDockedInsideChartArea = true;
            legend1.DockedToChartArea = chartArea_trend.Name;
            //legend1.Position.X = 0;// 3F;
            //legend1.Position.Y = 0;// 10F;


            legend2.Name = "Default2";
            legend2.BackColor = System.Drawing.Color.White;
            legend2.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            legend2.Enabled = true;
            legend2.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            legend2.IsTextAutoFit = true;
            chart.Legends.Add(legend2);
            legend2.Position.Auto = true;// false;
            legend2.IsDockedInsideChartArea = true;
            legend2.DockedToChartArea = chartArea_samplead.Name;
            //legend2.Position.X = 0;// 3F;
            //legend2.Position.Y = 50;// 10F;


            series_trendrange.Name = "TrendRange";
            series_trendrange.ChartArea = chartArea_trend.Name;
            series_trendrange.Legend = legend1.Name;
            series_trendrange.LegendText = "纵向极差";

            series_trendrange.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Range;
            series_trendrange.Color = System.Drawing.Color.FromArgb(((int)(((byte)(220)))), ((int)(((byte)(224)))), ((int)(((byte)(64)))), ((int)(((byte)(10)))));
            series_trendrange.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(180)))), ((int)(((byte)(26)))), ((int)(((byte)(59)))), ((int)(((byte)(105)))));
            series_trendrange.BorderWidth = 2;
            series_trendrange.ShadowColor = System.Drawing.Color.Black;
            series_trendrange.ShadowOffset = 2;
            series_trendrange.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
            series_trendrange.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Double;
            chart.Series.Add(series_trendrange);

            series_trend.Name = "Trend";
            series_trend.ChartArea = chartArea_trend.Name;
            series_trend.Legend = legend1.Name;
            series_trend.LegendText = "纵向趋势";

            series_trend.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Spline;
            series_trend.Color = System.Drawing.Color.FromArgb(((int)(((byte)(220)))), ((int)(((byte)(65)))), ((int)(((byte)(140)))), ((int)(((byte)(240)))));
            series_trend.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(180)))), ((int)(((byte)(26)))), ((int)(((byte)(59)))), ((int)(((byte)(105)))));
            series_trend.BorderWidth = 2;
            series_trend.ShadowColor = System.Drawing.Color.Black;
            series_trend.ShadowOffset = 2;
            series_trend.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
            series_trend.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Double;
            chart.Series.Add(series_trend);

            series_tempad.Name = "TempAD";
            series_tempad.ChartArea = chartArea_samplead.Name;
            series_tempad.Legend = legend2.Name;
            series_tempad.LegendText = "温修AD";
            series_tempad.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            series_tempad.Color = System.Drawing.Color.FromArgb(((int)(((byte)(220)))), ((int)(((byte)(224)))), ((int)(((byte)(64)))), ((int)(((byte)(10)))));
            series_tempad.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(180)))), ((int)(((byte)(26)))), ((int)(((byte)(59)))), ((int)(((byte)(105)))));
            series_tempad.BorderWidth = 2;
            series_tempad.ShadowColor = System.Drawing.Color.Black;
            series_tempad.ShadowOffset = 2;
            series_tempad.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
            series_tempad.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Double;
            series_samplead.YAxisType = System.Windows.Forms.DataVisualization.Charting.AxisType.Primary;
            chart.Series.Add(series_tempad);

            series_samplead.Name = "SampleAD";
            series_samplead.ChartArea = chartArea_samplead.Name;
            series_samplead.Legend = legend2.Name;
            series_samplead.LegendText = "样品AD";
            series_samplead.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            series_samplead.Color = System.Drawing.Color.FromArgb(((int)(((byte)(220)))), ((int)(((byte)(65)))), ((int)(((byte)(140)))), ((int)(((byte)(240)))));
            series_samplead.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(180)))), ((int)(((byte)(26)))), ((int)(((byte)(59)))), ((int)(((byte)(105)))));
            series_samplead.BorderWidth = 2;
            series_samplead.ShadowColor = System.Drawing.Color.Black;
            series_samplead.ShadowOffset = 2;
            series_samplead.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
            series_samplead.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Double;
            series_samplead.YAxisType = System.Windows.Forms.DataVisualization.Charting.AxisType.Secondary;
            chart.Series.Add(series_samplead);

            chart.BackColor = System.Drawing.Color.Transparent;
        }
        void InitializeComponent_chart_sigma()
        {
            System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend();

            System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea_sigma = new System.Windows.Forms.DataVisualization.Charting.ChartArea();


            //sigma
            System.Windows.Forms.DataVisualization.Charting.Series series_sigma = new System.Windows.Forms.DataVisualization.Charting.Series();

            Chart chart = chart_sigma;

            chart.Name = "chart_sigma";

            // 
            // chartArea_sigma
            // 
            chartArea_sigma.Name = "Sigma";
            chartArea_sigma.AxisX.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            //chartArea_sigma.AxisX.LabelStyle.Format = "HH:mm";
            chartArea_sigma.AxisX.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea_sigma.AxisX.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea_sigma.AxisX.IsMarksNextToAxis = false;

            chartArea_sigma.AxisY.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            chartArea_sigma.AxisY.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea_sigma.AxisY.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));

            chartArea_sigma.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea_sigma.BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
            chart.ChartAreas.Add(chartArea_sigma);

            chartArea_sigma.Position.Height = 100;// 42F;
            chartArea_sigma.Position.Width = 100;// 88F;
            chartArea_sigma.Position.X = 0;// 3F;
            chartArea_sigma.Position.Y = 0;// 10F;

            //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.chart1.Legends.Add(legend1);
            //this.chart1.Location = new System.Drawing.Point(16, 32);

            series_sigma.Name = "Sigma";
            series_sigma.ChartArea = chartArea_sigma.Name;
            //series_trend.Legend = "Default";
            series_sigma.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Range;
            series_sigma.Color = System.Drawing.Color.FromArgb(((int)(((byte)(220)))), ((int)(((byte)(224)))), ((int)(((byte)(64)))), ((int)(((byte)(10)))));
            series_sigma.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(180)))), ((int)(((byte)(26)))), ((int)(((byte)(59)))), ((int)(((byte)(105)))));
            series_sigma.BorderWidth = 2;
            series_sigma.ShadowColor = System.Drawing.Color.Black;
            series_sigma.ShadowOffset = 2;
            series_sigma.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
            series_sigma.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Double;
            chart.Series.Add(series_sigma);

            chart.BackColor = System.Drawing.Color.Transparent;
        }
        void InitializeComponent_chart_ud()
        {
            System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend();

            System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea_ud = new System.Windows.Forms.DataVisualization.Charting.ChartArea();

            //正态分布
            System.Windows.Forms.DataVisualization.Charting.Series series_ud = new System.Windows.Forms.DataVisualization.Charting.Series();

            Chart chart = chart_ud;

            chart.Name = "chart_ud";

            // 
            // chartArea_ud
            // 
            chartArea_ud.Name = "UD";
            chartArea_ud.AxisX.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            chartArea_ud.AxisX.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea_ud.AxisX.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea_ud.AxisX.IsMarksNextToAxis = false;

            chartArea_ud.AxisY.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            chartArea_ud.AxisY.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea_ud.AxisY.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));

            chartArea_ud.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea_ud.BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
            chart.ChartAreas.Add(chartArea_ud);

            chartArea_ud.Position.Height = 100;// 42F;
            chartArea_ud.Position.Width = 100;// 88F;
            chartArea_ud.Position.X = 0;// 3F;
            chartArea_ud.Position.Y = 0;// 10F;


            //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.chart1.Legends.Add(legend1);
            //this.chart1.Location = new System.Drawing.Point(16, 32);


            series_ud.Name = "UD";
            series_ud.ChartArea = chartArea_ud.Name;
            //series_ud.Legend = "Default";
            series_ud.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Column;
            series_ud.Color = System.Drawing.Color.FromArgb(((int)(((byte)(220)))), ((int)(((byte)(224)))), ((int)(((byte)(64)))), ((int)(((byte)(10)))));
            series_ud.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(180)))), ((int)(((byte)(26)))), ((int)(((byte)(59)))), ((int)(((byte)(105)))));
            series_ud.BorderWidth = 2;
            series_ud.ShadowColor = System.Drawing.Color.Black;
            series_ud.ShadowOffset = 2;
            series_ud.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Double;
            series_ud.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Double;
            chart.Series.Add(series_ud);




            chart.BackColor = System.Drawing.Color.Transparent;
        }
        void InitializeComponent_chart_convolution()
        {
            System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend();

            System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea_convolution = new System.Windows.Forms.DataVisualization.Charting.ChartArea();

            //卷积
            System.Windows.Forms.DataVisualization.Charting.Series series_convolution = new System.Windows.Forms.DataVisualization.Charting.Series();

            //混合
            System.Windows.Forms.DataVisualization.Charting.Series series_mix = new System.Windows.Forms.DataVisualization.Charting.Series();


            Chart chart = chart_convolution;

            chart.Name = "chart_convolution";



            // 
            // chartArea_convolution
            // 
            chartArea_convolution.Name = "Convolution";
            chartArea_convolution.AxisX.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            chartArea_convolution.AxisX.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea_convolution.AxisX.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea_convolution.AxisX.IsMarksNextToAxis = false;

            chartArea_convolution.AxisY.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            chartArea_convolution.AxisY.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea_convolution.AxisY.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));

            chartArea_convolution.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea_convolution.BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
            chart.ChartAreas.Add(chartArea_convolution);
            chartArea_convolution.Position.Height = 100;// 42F;
            chartArea_convolution.Position.Width = 100;// 88F;
            chartArea_convolution.Position.X = 0;// 3F;
            chartArea_convolution.Position.Y = 0;// 10F;

            //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.chart1.Legends.Add(legend1);
            //this.chart1.Location = new System.Drawing.Point(16, 32);

            series_convolution.Name = "Convolution";
            series_convolution.ChartArea = chartArea_convolution.Name;
            //series_samplead.Legend = "Default";
            series_convolution.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Range;
            series_convolution.Color = System.Drawing.Color.FromArgb(((int)(((byte)(220)))), ((int)(((byte)(224)))), ((int)(((byte)(64)))), ((int)(((byte)(10)))));
            series_convolution.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(180)))), ((int)(((byte)(26)))), ((int)(((byte)(59)))), ((int)(((byte)(105)))));
            series_convolution.BorderWidth = 2;
            series_convolution.ShadowColor = System.Drawing.Color.Black;
            series_convolution.ShadowOffset = 2;
            series_convolution.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
            series_convolution.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Double;
            chart.Series.Add(series_convolution);
            series_mix.Name = "Mix";
            series_mix.ChartArea = chartArea_convolution.Name;
            //series_trend.Legend = "Default";
            series_mix.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Spline;
            series_mix.Color = System.Drawing.Color.FromArgb(((int)(((byte)(220)))), ((int)(((byte)(65)))), ((int)(((byte)(140)))), ((int)(((byte)(240)))));
            series_mix.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(180)))), ((int)(((byte)(26)))), ((int)(((byte)(59)))), ((int)(((byte)(105)))));
            series_mix.BorderWidth = 2;
            series_mix.ShadowColor = System.Drawing.Color.Black;
            series_mix.ShadowOffset = 2;
            series_mix.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
            series_mix.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Double;
            chart.Series.Add(series_mix);








            chart.BackColor = System.Drawing.Color.Transparent;
        }
        void Load()
        {
            //打开csv文件
            foreach (string path in Paths)
            {
                StreamReader sr = new StreamReader(path, Encoding.GetEncoding("GB2312"));
                string header = sr.ReadLine();
                while (!sr.EndOfStream)
                {
                    string row = sr.ReadLine();
                    FlyData_ScanHistory fd = new FlyData_ScanHistory();
                    if (fd.TryParse(header, row))
                    {
                        mDatas.Add(fd);
                    }
                }
                sr.Close();
            }
            mDatas.Sort((t1, t2) => t1.Time.CompareTo(t2.Time));
            Index = 0;
            Total = mDatas.Count();

        }
        void UpdateScan()
        {
            if (Index < 0)
            {
                Index = 0;
                return;
            }
            if (Index >= Total)
            {
                Index = Total - 1;
                return;
            }
            FlyData_ScanHistory fd = mDatas[Index];
            TempAD = fd.SampleAD[0];
            SampleAD = fd.SampleAD[1];
            Comp = fd.Comp;
            Shift = fd.Shift;
            Time = fd.Time;
            Target = fd.Target;
            Alarm = fd.Alarm;
            Avg = fd.Avg;
            UpdateScan(fd);
            UpdateScan_AxisY(fd);
            UpdateScan_XRange(fd);
            UpdateScan_CalState(fd);
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.DataContext = this;
            //多线程。。。
            System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(
                delegate()
                {
                    //加载数据
                    Load();
                    TimeBegin = mDatas.First().Time;
                    TimeEnd = mDatas.Last().Time;

                    //转为平均值，放入纵向趋势图

                    chart_trend.Invoke(new System.Threading.ThreadStart(UpdateGraph));
                }));
            thread.Start();
        }
        void UpdateGraph()
        {
            UpdateScan();
            UpdateTrend(mDatas);
            UpdateSigma(mDatas);

            UpdateConvolution(mDatas);
            UpdateConvolution_AxisY(mDatas.Last());
            UpdateDistribution(mDatas);
            UpdateDistribution_XRange(mDatas.Last());
        }
        private void button_up_Click(object sender, RoutedEventArgs e)
        {
            Index--;
            UpdateScan();
        }

        private void button_down_Click(object sender, RoutedEventArgs e)
        {
            Index++;
            UpdateScan();
        }



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


        public event PropertyChangedEventHandler PropertyChanged;

        public bool IsAutoTarget = false;
        public bool IsPercent = false;
        public int TotalPointCnt = 500;
        #region 扫描图
        void UpdateScan(FlyData_ScanHistory fd)
        {
            double multi = 100.0;
            int emptyvalue = Misc.MyBase.NULL_VALUE;
            Chart chart = chart_scan;
            chart.Series["Series 1"].Points.Clear();
            int avg = Misc.MyMath.Avg(fd.Data);
            int autotarget = avg;
            int target;
            if (IsAutoTarget)
                target = autotarget;
            else
                target = fd.Target;
            int alarm = fd.Alarm;
            int threshold1;
            int threshold2;

            if ((!IsPercent) || (target == 0))
            {
                threshold1 = target + alarm;
                threshold2 = target - alarm;
            }
            else
            {
                threshold1 = (int)(target * (1 + (double)alarm / multi / 100.0));
                threshold2 = (int)(target * (1 - (double)alarm / multi / 100.0));
                if (threshold1 < threshold2)
                {
                    int t = threshold1;
                    threshold1 = threshold2;
                    threshold2 = t;
                }
            }

            for (int i = 0; i < fd.Data.Length; i++)
            {
                int data = fd.Data[i];
                chart.Series["Series 1"].Points.AddXY(
                    fd.BoltNo1st + i,
                    (double)data / multi);
                DataPoint point = chart.Series["Series 1"].Points[i];
                //设定空数据
                if (!Misc.MyBase.ISVALIDATA(data))
                    point.IsEmpty = true;
                System.Drawing.Color c;

                if (data > threshold1)
                {
                    c = System.Drawing.Color.Orange;
                }
                else if (data < threshold2)
                {
                    c = System.Drawing.Color.Red;
                }
                else
                {
                    c = System.Drawing.Color.Green;
                }
                //if (ChartType == SeriesChartType.Line)
                //{
                //    point.MarkerColor = c;
                //    point.BorderColor = chart1.Series["Series 1"].BorderColor;
                //    point.Color = chart1.Series["Series 1"].Color;
                //}
                //else
                //{
                point.MarkerColor = c;
                point.BorderColor = c;
                point.Color = c;
                //}
            }
        }

        void SetCustomLabel(Axis axisY, double p, GridTickTypes gt, System.Drawing.Color c)
        {
            double multi = 100;

            double r = axisY.Maximum - axisY.Minimum;
            double f, t;
            f = p + r / 2;
            t = p - r / 2;
            if (f > t)
            {
                double _f = f;
                f = t;
                t = _f;
            }

            double target;
            if (IsAutoTarget)
                target = AutoTarget / multi;
            else
                target = Target / multi;

            CustomLabel customLabel;
            if ((!IsPercent) || (target == 0) || (target == p))
            {
                customLabel = axisY.CustomLabels.Add(f, t, p.ToString("N1"));
            }
            else
            {
                double percent;

                percent = ((p - target) / target) * 100;

                if (target < 0)
                    percent = -percent;

                customLabel = axisY.CustomLabels.Add(f, t, percent.ToString("N1") + "%");
            }

            customLabel.GridTicks = gt;
            customLabel.ForeColor = c;

        }
        void UpdateScan_AxisY(FlyData_ScanHistory fd)
        {
            double multi = 100.0;
            int emptyvalue = Misc.MyBase.NULL_VALUE;
            Chart chart = chart_scan;
            //chart.Series["Series 1"].Points.Clear();
            int autotarget = avg;
            double target;
            if (IsAutoTarget)
                target = autotarget / multi;
            else
                target = fd.Target / multi;
            int YRange = fd.Alarm * 2;

            double yrange = (double)(YRange) / multi * YRangePercent;
            double alarm = (double)(fd.Alarm) / multi;


            if (AutoTarget < 0)
            {

            }

            if (alarm < 0.1)
                alarm = 0.1;

            if (yrange < 0.6)
                yrange = 0.6;

            Axis axisY = chart.ChartAreas["Default"].AxisY;

            //TODO
            axisY.Crossing = target;

            // Set manual minimum and maximum values.
            if ((!IsPercent) || (target == 0))
            {
                axisY.Minimum = target - yrange;
                axisY.Maximum = target + yrange;
            }
            else
            {
                if (target > 0)
                {
                    axisY.Minimum = target * (1 - yrange / 100);
                    axisY.Maximum = target * (1 + yrange / 100);
                }
                else
                {
                    axisY.Minimum = target * (1 + yrange / 100);
                    axisY.Maximum = target * (1 - yrange / 100);
                }
            }

            axisY.CustomLabels.Clear();

            SetCustomLabel(axisY, target, GridTickTypes.All, System.Drawing.Color.Black);

            if ((!IsPercent) || (target == 0))
            {
                SetCustomLabel(axisY, target + alarm, GridTickTypes.All, System.Drawing.Color.Red);
                SetCustomLabel(axisY, target - alarm, GridTickTypes.All, System.Drawing.Color.Blue);
            }
            else//% 
            {
                SetCustomLabel(axisY, target * (1 + alarm / 100), GridTickTypes.All, System.Drawing.Color.Red);
                SetCustomLabel(axisY, target * (1 - alarm / 100), GridTickTypes.All, System.Drawing.Color.Blue);
            }

            if (yrange != alarm)
            {
                SetCustomLabel(axisY, axisY.Minimum, GridTickTypes.TickMark, System.Drawing.Color.Black);
                SetCustomLabel(axisY, axisY.Maximum, GridTickTypes.TickMark, System.Drawing.Color.Black);
            }


            if (yrange <= alarm)
            {
                if ((!IsPercent) || (target == 0))
                {
                    SetCustomLabel(axisY, target - yrange / 2, GridTickTypes.All, System.Drawing.Color.Black);
                    SetCustomLabel(axisY, target + yrange / 2, GridTickTypes.All, System.Drawing.Color.Black);
                }
                else//% 
                {
                    SetCustomLabel(axisY, target * (1 - yrange / 200), GridTickTypes.All, System.Drawing.Color.Black);
                    SetCustomLabel(axisY, target * (1 + yrange / 200), GridTickTypes.All, System.Drawing.Color.Black);
                }
            }
        }
        void UpdateScan_XRange(FlyData_ScanHistory fd)
        {
            Chart chart = chart_scan;
            int firstBoltNo = fd.BoltNo1st;
            int first = 0;
            int last = fd.Data.Count() - 1;
            if (first >= last)
                last = first + 10;
            // Set manual minimum and maximum values.
            chart.ChartAreas["Default"].AxisX.Minimum = firstBoltNo + first;
            chart.ChartAreas["Default"].AxisX.Maximum = firstBoltNo + last;
        }
        void UpdateScan_CalState(FlyData_ScanHistory fd)
        {
            Chart chart = chart_scan;
            int emptyvalue = Misc.MyBase.NULL_VALUE;
            double multi = 100;
            int firstBoltNo = fd.BoltNo1st;
            int datafirst = 0;
            int datalast = fd.Data.Count() - 1;
            int datalen = datalast - datafirst + 1;


            int[] datlist = fd.Data;
            string title;

            var dats = from data in datlist where data != emptyvalue select data;
            if (dats.Count() == 0)
            {
                goto _err;
            }
            else
            {
                AutoTarget = (int)dats.Average();

                double avg = dats.Average() / multi;
                double max = dats.Max() / multi;
                double min = dats.Min() / multi;

                double sum = 0;
                foreach (int dat in dats)
                {
                    sum += Math.Pow(avg - (double)dat / multi, 2);
                }
                sum /= (dats.Count() - 1);
                double sigma = Math.Sqrt(sum);

                if (IsPercent)
                {


                    title = "Max:+" + ((max / avg * 100) - 100).ToString("N1") + "% " +
                        "Min:-" + (100 - (min / avg * 100)).ToString("N1") + "% " +
                        "Avg:" + avg.ToString("N1") + " " +
                        "2σ:" + (sigma / avg * 2 * 100).ToString("N1") + "%";
                }
                else
                {
                    title = "Max:" + max.ToString("N1") + " " +
                        "Min:" + min.ToString("N1") + " " +
                        "Avg:" + avg.ToString("N1") + " " +
                        "2σ:" + (sigma * 2).ToString("N1");
                }

            }
            goto _end;
        _err:
            //title = Properties.Resources.StrMax + ":" + "NULL " +
            //        Properties.Resources.StrMin+":"+"NULL "+
            //        Properties.Resources.StrAvg+":"+"NULL "+
            //        "3Sigma:"+"NULL ";
            title = "Max:null Min:null Avg:null 2σ:null";

        _end:


            System.Windows.Forms.DataVisualization.Charting.Axis axisX = chart.ChartAreas["Default"].AxisX;

            axisX.CustomLabels.Clear();

            System.Windows.Forms.DataVisualization.Charting.CustomLabel customlabel
                = new System.Windows.Forms.DataVisualization.Charting.CustomLabel(
                    datafirst + firstBoltNo, datalast + firstBoltNo, title, 1,
                System.Windows.Forms.DataVisualization.Charting.LabelMarkStyle.LineSideMark);

            axisX.CustomLabels.Add(customlabel);

        }

        #endregion
        #region 纵向趋势图
        void UpdateTrend(List<FlyData_ScanHistory> datas)
        {
            int boltcnt = datas.Last().BoltCnt;
            mTrendDatas.Clear();
            for (int i = 0; i < datas.Count(); i++)
            {
                int[] buf = new int[boltcnt];
                for (int j = 0; j < buf.Count(); j++)
                {

                    int cnt = 0;
                    int sum = 0;
                    for (int k = 0; k < Mix; k++)
                    {
                        int index = i - k;
                        if (index < 0)
                            break;
                        if (j < datas[index].Data.Count())
                        {
                            int d = datas[index].Data[j];
                            if (Misc.MyBase.ISVALIDATA(d))
                            {
                                sum += d;
                                cnt++;
                            }
                        }
                    }
                    if (cnt > 0)
                        buf[j] = sum / cnt;
                    else
                        buf[j] = Misc.MyBase.NULL_VALUE;
                }
                TrendData t = new TrendData();
                t.Avg = Misc.MyMath.Avg(buf);
                t.Sigma2 = Misc.MyMath.Sigma(buf) * 2;
                t.Time = datas[i].Time;
                mTrendDatas.Add(t);
            }

            Series series_trend = chart_trend.Series["Trend"];
            Series series_trendrange = chart_trend.Series["TrendRange"];
            //Series series_sigma = chart_trend.Series["Sigma"];
            series_trend.Points.Clear();
            series_trendrange.Points.Clear();
            //series_sigma.Points.Clear();


            //压缩显示。。。。最大1000个数据点
            int interval = mTrendDatas.Count() / TotalPointCnt;
            if (interval < 1)
                interval = 1;

            for (int i = 0; i < mTrendDatas.Count(); i += interval)
            {
                series_trend.Points.AddY(mTrendDatas[i].Avg / 100.0);
                series_trendrange.Points.AddY((mTrendDatas[i].Avg + mTrendDatas[i].Sigma2) / 100.0, (mTrendDatas[i].Avg - mTrendDatas[i].Sigma2) / 100.0);
                series_trend.Points.Last().AxisLabel = mTrendDatas[i].Time.ToString("HH:mm");
                //series_sigma.Points.AddXY(mTrendDatas[i].Time, mTrendDatas[i].Sigma2 / 100.0);
                if (!Misc.MyBase.ISVALIDATA(mTrendDatas[i].Avg))
                {
                    series_trend.Points.Last().IsEmpty = true;
                    series_trendrange.Points.Last().IsEmpty = true;
                    //series_sigma.Points[i].IsEmpty = true;
                }
            }

            UpdateSampleAD(datas);
        }
        void UpdateSigma(List<FlyData_ScanHistory> datas)
        {
            Series series_sigma = chart_sigma.Series["Sigma"];
            //压缩显示。。。。最大1000个数据点
            int interval = mTrendDatas.Count() / TotalPointCnt;
            if (interval < 1)
                interval = 1;
            for (int i = 0; i < mTrendDatas.Count(); i += interval)
            {
                series_sigma.Points.AddY(mTrendDatas[i].Sigma2 / 100.0, -mTrendDatas[i].Sigma2 / 100.0);
                series_sigma.Points.Last().AxisLabel = mTrendDatas[i].Time.ToString("HH:mm");
                if (!Misc.MyBase.ISVALIDATA(mTrendDatas[i].Avg))
                {
                    series_sigma.Points.Last().IsEmpty = true;
                }
            }


        }
        #endregion
        #region 卷积图
        void UpdateConvolution(List<FlyData_ScanHistory> datas)
        {
            int boltcnt = datas.Last().BoltCnt;
            ScanData[] scandatas = new ScanData[boltcnt];
            for (int i = 0; i < scandatas.Count(); i++)
            {
                int[] buf = new int[datas.Count()];
                for (int j = 0; j < buf.Count(); j++)
                {
                    if (i < datas[j].Data.Count())
                        buf[j] = datas[j].Data[i];
                    else
                        buf[j] = Misc.MyBase.NULL_VALUE;
                }
                int avg = Misc.MyMath.Avg(buf);
                int sigma = Misc.MyMath.Sigma(buf);
                scandatas[i] = new ScanData() { Avg = avg, Sigma2 = sigma * 2 };
            }

            Series series_convolution = chart_convolution.Series["Convolution"];
            Series series_mix = chart_convolution.Series["Mix"];
            series_convolution.Points.Clear();
            series_mix.Points.Clear();
            int boltno1st = datas[0].BoltNo1st;

            for (int i = 0; i < scandatas.Count(); i++)
            {
                series_mix.Points.AddXY(boltno1st + i, scandatas[i].Avg / 100.0);
                series_convolution.Points.AddXY(boltno1st + i, (scandatas[i].Avg + scandatas[i].Sigma2) / 100.0, (scandatas[i].Avg - scandatas[i].Sigma2) / 100.0);

                if (!Misc.MyBase.ISVALIDATA(scandatas[i].Avg))
                {
                    series_mix.Points[i].IsEmpty = true;
                    series_convolution.Points[i].IsEmpty = true;
                }
            }
        }
        void UpdateConvolution_AxisY(FlyData_ScanHistory fd)
        {
            double multi = 100.0;
            int emptyvalue = Misc.MyBase.NULL_VALUE;
            Chart chart = chart_convolution;
            //chart.Series["Series 1"].Points.Clear();
            int autotarget = avg;
            double target;
            if (IsAutoTarget)
                target = autotarget / multi;
            else
                target = fd.Target / multi;
            int YRange = fd.Alarm * 2;

            double yrange = (double)(YRange) / multi * YRangePercent;
            double alarm = (double)(fd.Alarm) / multi;


            if (AutoTarget < 0)
            {

            }

            if (alarm < 0.1)
                alarm = 0.1;

            if (yrange < 0.6)
                yrange = 0.6;

            Axis axisY = chart.ChartAreas["Convolution"].AxisY;

            //TODO
            axisY.Crossing = target;

            // Set manual minimum and maximum values.
            if ((!IsPercent) || (target == 0))
            {
                axisY.Minimum = target - yrange;
                axisY.Maximum = target + yrange;
            }
            else
            {
                if (target > 0)
                {
                    axisY.Minimum = target * (1 - yrange / 100);
                    axisY.Maximum = target * (1 + yrange / 100);
                }
                else
                {
                    axisY.Minimum = target * (1 + yrange / 100);
                    axisY.Maximum = target * (1 - yrange / 100);
                }
            }

            axisY.CustomLabels.Clear();

            SetCustomLabel(axisY, target, GridTickTypes.All, System.Drawing.Color.Black);

            if ((!IsPercent) || (target == 0))
            {
                SetCustomLabel(axisY, target + alarm, GridTickTypes.All, System.Drawing.Color.Red);
                SetCustomLabel(axisY, target - alarm, GridTickTypes.All, System.Drawing.Color.Blue);
            }
            else//% 
            {
                SetCustomLabel(axisY, target * (1 + alarm / 100), GridTickTypes.All, System.Drawing.Color.Red);
                SetCustomLabel(axisY, target * (1 - alarm / 100), GridTickTypes.All, System.Drawing.Color.Blue);
            }

            if (yrange != alarm)
            {
                SetCustomLabel(axisY, axisY.Minimum, GridTickTypes.TickMark, System.Drawing.Color.Black);
                SetCustomLabel(axisY, axisY.Maximum, GridTickTypes.TickMark, System.Drawing.Color.Black);
            }


            if (yrange <= alarm)
            {
                if ((!IsPercent) || (target == 0))
                {
                    SetCustomLabel(axisY, target - yrange / 2, GridTickTypes.All, System.Drawing.Color.Black);
                    SetCustomLabel(axisY, target + yrange / 2, GridTickTypes.All, System.Drawing.Color.Black);
                }
                else//% 
                {
                    SetCustomLabel(axisY, target * (1 - yrange / 200), GridTickTypes.All, System.Drawing.Color.Black);
                    SetCustomLabel(axisY, target * (1 + yrange / 200), GridTickTypes.All, System.Drawing.Color.Black);
                }
            }
        }
        #endregion
        #region 正态分布图
        void UpdateDistribution(List<FlyData_ScanHistory> datas)
        {
            List<double> sampleData = new List<double>();
            for (int i = 0; i < datas.Count(); i++)
            {
                for (int j = 0; j < datas[i].Data.Count(); j++)
                {
                    int d = datas[i].Data[j];
                    if (Misc.MyBase.ISVALIDATA(d))
                    {
                        sampleData.Add(d / 100.0);
                    }
                }
            }

            Distribution distrbution = new Distribution();
            distrbution.Interval = 1;
            distrbution.To(sampleData);



            Series series_ud = chart_ud.Series["UD"];
            series_ud.Points.Clear();

            for (int i = 0; i < distrbution.Result.Count(); i++)
            {
                double y = (double)(distrbution.Result.ElementAt(i).Value) / distrbution.Total;
                double x = distrbution.Result.ElementAt(i).Key;
                series_ud.Points.AddXY(x, y);
            }
        }
        void UpdateDistribution_XRange(FlyData_ScanHistory fd)
        {
            Chart chart = chart_ud;

            chart.ChartAreas["UD"].AxisX.Minimum = (fd.Target - fd.Alarm * 4) / 100.0;
            chart.ChartAreas["UD"].AxisX.Maximum = (fd.Target + fd.Alarm * 4) / 100.0;
        }
        #endregion
        #region 温修，样品AD 变化图
        void UpdateSampleAD(List<FlyData_ScanHistory> datas)
        {
            Series series_samplead = chart_trend.Series["SampleAD"];
            Series series_tempad = chart_trend.Series["TempAD"];
            series_samplead.Points.Clear();
            series_tempad.Points.Clear();

            //压缩显示。。。。最大1000个数据点
            int interval = datas.Count() / TotalPointCnt;
            if (interval < 1)
                interval = 1;
            for (int i = 0; i < datas.Count(); i += interval)
            {
                series_tempad.Points.AddY(datas[i].SampleAD[0]);
                series_samplead.Points.AddY(datas[i].SampleAD[1]);
                series_tempad.Points.Last().AxisLabel = datas[i].Time.ToString("HH:mm");

                if (datas[i].SampleAD[0] <= 0)
                {
                    series_tempad.Points.Last().IsEmpty = true;
                }

                if (datas[i].SampleAD[1] <= 0)
                {
                    series_samplead.Points.Last().IsEmpty = true;
                }
            }
            double tempad_max = series_tempad.Points.Max(p => p.YValues[0]);
            double tempad_min = series_tempad.Points.Min(p => p.YValues[0]);
            double samplead_max = series_samplead.Points.Max(p => p.YValues[0]);
            double samplead_min = series_samplead.Points.Min(p => p.YValues[0]);
            if (samplead_max == samplead_min)
            {
                chart_trend.ChartAreas["SampleAD"].AxisY2.Maximum = 10;
                chart_trend.ChartAreas["SampleAD"].AxisY2.Minimum = 0;
            }
            if (tempad_max == tempad_min)
            {
                chart_trend.ChartAreas["SampleAD"].AxisY.Maximum = 10;
                chart_trend.ChartAreas["SampleAD"].AxisY.Minimum = 0;
            }
            chart_trend.ChartAreas["SampleAD"].AxisX.Interval = 100;
        }

        #endregion
    }
    /// <summary>
    ///  数据频率统计
    /// </summary>
    public class Distribution
    {
        /// <summary>
        /// 间隔
        /// </summary>
        public double Interval = 1;
        Dictionary<double, int> Datas = new Dictionary<double, int>();
        public IOrderedEnumerable<KeyValuePair<double, int>> Result;
        /// <summary>
        /// 总出现次数
        /// </summary>
        public int Total = 0;
        public void To(List<double> sampleData)
        {
            foreach (double d in sampleData)
            {
                double key = (int)(d / Interval) * Interval;
                if (Datas.ContainsKey(key))
                {
                    Datas[key]++;
                }
                else
                {
                    Datas.Add(key, 1);
                }
                Total++;
            }
            Result = Datas.OrderBy((kv) => kv.Key);
        }
        public void Clear()
        {
            Datas.Clear();
            Total = 0;
            Result = null;
        }
    }
    class NormalDistribution
    {
        /// <summary>
        /// 获取数据序列的最大精度 (即小数点后面的位数长度)
        /// </summary>
        /// <param name="sampleData">样本数据</param>
        /// <returns></returns>
        public static int GetMostPrecision(List<double> sampleData)
        {
            if (sampleData == null || sampleData.Count == 0)
            {
                return 0;
            }

            int mostPrecision = 0;
            int tempValue = 0;

            foreach (double value in sampleData)
            {
                string data = Math.Abs(value).ToString();
                int dateLength = data.Length;
                int dotIndex = data.IndexOf(".");

                if (dotIndex > 0)
                {
                    tempValue = dateLength - (dotIndex + 1);
                }

                if (tempValue > mostPrecision) //取更大的精度
                {
                    mostPrecision = tempValue;
                }
            }

            return mostPrecision;
        }
        /// <summary>
        /// 缩放倍数
        /// </summary>
        /// <param name="mostPrecision"></param>
        /// <returns></returns>
        public static double ZoomMultiple(ref int mostPrecision)
        {
            double zoomMultiple = Math.Pow(10, mostPrecision - 1);

            if (mostPrecision <= 2) //保证精度大于二的数据序列图形的平滑
            {
                mostPrecision = 4;
                zoomMultiple = 100;
            }

            return zoomMultiple;
        }
        /// <summary>
        /// 4.XBAR：这个大家好理解，也很好计算。即是所有样本数据之和的平均值。 
        /// </summary>
        /// <param name="sampleData"></param>
        /// <param name="mostPrecision"></param>
        /// <returns></returns>
        public static double XBAR(List<double> sampleData, int mostPrecision)
        {
            double xbar = Math.Round(sampleData.Average(), mostPrecision);
            return xbar;
        }

        /// <summary>
        /// 计算Sigma
        /// </summary>
        /// <param name="sampleData">样本数据</param>
        /// <param name="xbar">平均值</param>
        /// <returns></returns>
        public static double CalculateSigma(List<double> sampleData, double xbar)
        {
            double sigma = 0;
            int sampleCount = sampleData.Count;
            double powSum = 0;

            if (sampleData == null || sampleCount <= 2
) //样本个数大于2计算才有意思
            {
                return sigma;
            }

            foreach (double value in sampleData)
            {
                powSum += Math.Pow(value - xbar, 2); //样本值减去均值2的次幂相加。
            }

            sigma = Math.Sqrt(powSum / (sampleCount - 1));

            return sigma;
        }


        /// <summary>
        /// USL和LSL一般是抽样人员事先设置好的，也可以用公式得到
        /// </summary>
        /// <param name="xbar"></param>
        /// <param name="sigma"></param>
        /// <returns></returns>
        public static double USL(double xbar, double sigma)
        {
            double usl = xbar + 3 * sigma;//均值加3sigma
            return usl;
        }

        public static double LSL(double xbar, double sigma)
        {
            double lsl = xbar - 3 * sigma;//均值减3sigma
            return lsl;
        }

        public static void Paint(Series series, ChartArea chartArea, List<double> sampleData)
        {
            series.Points.Clear();

            int mostPrecision = GetMostPrecision(sampleData);
            double zoomMultiple = ZoomMultiple(ref mostPrecision);
            double xbar = XBAR(sampleData, mostPrecision);
            double sigma = CalculateSigma(sampleData, xbar);
            double lsl = LSL(xbar, sigma);
            double usl = USL(xbar, sigma);

            int positiveLimit = (int)((xbar + 6 * sigma) * zoomMultiple); //X轴的正界限
            int minusLimit = (int)((xbar - 6 * sigma) * zoomMultiple); //X轴的负界限
            double coefficient = Math.Round(1 / Math.Sqrt(2 * Math.PI) / sigma, mostPrecision); //系数；如果计算需要精确，就不要四舍五入；建议：为了提高运算

            List<double> xValues = new List<double>();
            List<double> yValues = new List<double>();

            for (int x = minusLimit; x <= positiveLimit; x++)
            {
                //x轴缩小zoomMultiple倍x每隔1/zoomMultiple变化曲线变平滑
                double xValue = x / zoomMultiple;
                double yValue = coefficient * Math.Exp(Math.Pow((xValue - xbar), 2) / (-2 * Math.Pow(sigma, 2)));
                xValue = Math.Round(xValue, mostPrecision);
                yValue = Math.Round(yValue, mostPrecision);
                if (yValue > 0.0001)//可设为yValue > 0
                {
                    xValues.Add(xValue);
                    yValues.Add(yValue);
                }
            }

            //为MSChart绑定数据值
            series.Points.DataBindXY(xValues, yValues);




            //if (yValues.Count > 0)
            //{
            //    yAxisMax = 0;
            //    return;

            //}
            //将Y轴最大值放大倍作为
            double yMax = Math.Round(yValues.Max() * 1.1, mostPrecision);
            double xMin = xValues.Min();
            double xMax = xValues.Max();
            double yMin = yValues.Min();
            double yAxisMax = yValues.Max();

            if (xMin > lsl)
            {
                xMin = lsl;
            }
            if (xMax < usl)
            {
                xMax = usl;
            }
            //设置轴值x轴加减极大极小值的1/zoomMultiple倍是为了图形能全部绘制出来
            chartArea.AxisX.Minimum = (double)Math.Round(xMin - xMin * 1 / zoomMultiple, mostPrecision);
            chartArea.AxisX.Maximum = (double)Math.Round(xMax + xMax * 1 / zoomMultiple, mostPrecision);
            chartArea.AxisY.Minimum = (double)Math.Round(yMin, mostPrecision);
            chartArea.AxisY.Maximum = (double)Math.Round(yMax, mostPrecision);
        }

        /// <summary>
        /// 添加阈值线
        /// </summary>
        /// <param name="chartArea">图形Area</param>
        /// <param name="lineName">在线显示的名子</param>
        /// <param name="lineOffset">线在图上的位置</param>
        /// <param name="lineWidth">线宽</param>
        /// <param name="lineColor">线的颜色</param>
        public void AddStripLine(ChartArea chartArea, string lineName, double lineOffset, double lineWidth, System.Drawing.Color lineColor)
        {
            StripLine stripLine = new StripLine
            {
                BackColor = lineColor,
                StripWidth = lineWidth,
                BackHatchStyle = ChartHatchStyle.DarkVertical,
                Text = lineName,
                TextAlignment = StringAlignment.Far,
                TextLineAlignment = StringAlignment.Center,
                IntervalOffset = lineOffset
            };

            chartArea.AxisY.StripLines.Add(stripLine);
        }
        /// <summary>
        /// 根据sampleData的最大和最小值重设X轴的最大和最小刻度
        /// </summary>
        /// <param name="queueValue"></param>
        public static void ResetAxisBySampleData(List<double> sampleData, Chart chart)
        {

            double max = (double)sampleData.Max();
            double min = (double)sampleData.Min();
            double xMax = chart.ChartAreas[0].AxisX.Maximum;
            double xMin = chart.ChartAreas[0].AxisX.Minimum;

            if (xMin > xMax)
            {
                chart.ChartAreas[0].AxisX.Minimum = min;
                chart.ChartAreas[0].AxisX.Maximum = max;
            }
        }
    }
}
