using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net;
using System.Collections.ObjectModel;
using System.Windows.Forms.DataVisualization.Charting;
using System.ComponentModel;
using FObjBase;
using System.Windows.Threading;
using System.Diagnostics;
using FLY.FeedbackRenZiJia.IService;

namespace FLY.FeedbackRenZiJia.UI.Client.UIModule
{
    /// <summary>
    /// Page_Graph.xaml 的交互逻辑
    /// </summary>
    public partial class Page_Graph : Page, INotifyPropertyChanged
    {
        public SysParam sysparam;
        FLY.FeedbackRenZiJia.Client.FeedbackHeatServiceClient mFeedback;
        FLY.FeedbackRenZiJia.Client.HeatBufServiceClient mHeatBuf;
        FLY.FeedbackRenZiJia.Client.HeatCellServiceClient mHeatCell;

        /// <summary>
        /// 当前选择加热通道
        /// </summary>
        public int SelectBoltNo { get; set; }


        public Page_Graph()
        {
            InitializeComponent();

            InitializeChart();
            
        }
        public void Init(int id)
        {
            sysparam = SysParam.Current;

            UpdateChartArea();

            sysparam.PropertyChanged += (s,e) =>
            {
                UpdateChartArea();
            };


            //把 FeedbackHeat 共享。 1个程序,只能有一个 FeedbackHeat
            mFeedback = TDGage.Current.mFeedback;
            mHeatBuf = TDGage.Current.mHeatBuf;
            mHeatCell = TDGage.Current.mHeatCell;

            IPEndPoint ep = sysparam.ServerEP;

            mFeedback.PropertyChanged += mFeedbackHeatService_PropertyChanged;
            mHeatCell.PropertyChanged += MHeatCell_PropertyChanged;
            mHeatBuf.PropertyChanged += MHeatBuf_PropertyChanged;
            UpdateAxisX(mFeedback.ChannelCnt);

            MHeatCell_PropertyChanged(mFeedback, new PropertyChangedEventArgs("Kp"));

            this.DataContext = mFeedback;
            lpress.Init(button_clear_h);
            lpress.LongClick += (s, e) => {
                mHeatCell.ClearPreHeats();
            };
            grid_longpress.DataContext = lpress;
        }

        void InitializeChart() 
        {
            System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
            System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea2 = 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.Legend legend2 = new System.Windows.Forms.DataVisualization.Charting.Legend();

            System.Windows.Forms.DataVisualization.Charting.Series series_heatoffsets = new System.Windows.Forms.DataVisualization.Charting.Series();
            System.Windows.Forms.DataVisualization.Charting.Series series_thicks = new System.Windows.Forms.DataVisualization.Charting.Series();
            System.Windows.Forms.DataVisualization.Charting.Series series_currs = new System.Windows.Forms.DataVisualization.Charting.Series();
            System.Windows.Forms.DataVisualization.Charting.Series series_heats = new System.Windows.Forms.DataVisualization.Charting.Series();
            
            // 
            // chart1
            // 
            //this.chart1.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(211)), ((System.Byte)(223)), ((System.Byte)(240)));
            //this.chart1.BackSecondaryColor = System.Drawing.Color.White;
            //this.chart1.BackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.TopBottom;
            //this.chart1.BorderlineColor = System.Drawing.Color.FromArgb(((System.Byte)(26)), ((System.Byte)(59)), ((System.Byte)(105)));
            //this.chart1.BorderlineDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
            //this.chart1.BorderlineWidth = 2;
            //this.chart1.BorderSkin.SkinStyle = System.Windows.Forms.DataVisualization.Charting.BorderSkinStyle.Emboss;
            #region chartArea
            #region chartArea1
            //下面3D设置都是没有------------------------------------
            chartArea1.Area3DStyle.IsClustered = true;
            chartArea1.Area3DStyle.Perspective = 10;
            chartArea1.Area3DStyle.IsRightAngleAxes = false;
            chartArea1.Area3DStyle.WallWidth = 0;
            chartArea1.Area3DStyle.Inclination = 15;
            chartArea1.Area3DStyle.Rotation = 10;
            //-------------------------------------------------------

            chartArea1.AxisX.IsLabelAutoFit = true;
            chartArea1.AxisX.LabelAutoFitStyle = LabelAutoFitStyles.DecreaseFont;
            chartArea1.AxisX.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            chartArea1.AxisX.LabelStyle.IsEndLabelVisible = false;
            chartArea1.AxisX.LineColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            chartArea1.AxisX.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            chartArea1.AxisX.Interval = 5;

            chartArea1.AxisY.IsLabelAutoFit = true;// false;
            chartArea1.AxisY.LabelAutoFitStyle = LabelAutoFitStyles.DecreaseFont;
            chartArea1.AxisY.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            chartArea1.AxisY.LineColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            chartArea1.AxisY.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            chartArea1.AxisY.IsStartedFromZero = true;

            chartArea1.AxisY.Maximum = 50;
            chartArea1.AxisY.Minimum = -50;
            //chartArea1.AxisY.Interval = 10;

            chartArea1.AxisY2.IsLabelAutoFit = true;// false;
            chartArea1.AxisY2.LabelAutoFitStyle = LabelAutoFitStyles.DecreaseFont;
            chartArea1.AxisY2.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            chartArea1.AxisY2.LineColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            chartArea1.AxisY2.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            chartArea1.AxisY2.IsStartedFromZero = false;


            chartArea1.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(165)), ((System.Byte)(191)), ((System.Byte)(228)));
            chartArea1.BackSecondaryColor = System.Drawing.Color.White;
            chartArea1.BackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.TopBottom;
            chartArea1.BorderColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            chartArea1.BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
            chartArea1.Name = "HeatOffsets";
            chartArea1.Position.Auto = false;
            chartArea1.Position.Height = 50F;
            chartArea1.Position.Width = 100F;
            chartArea1.Position.X = 0;
            chartArea1.Position.Y = 0;
            chartArea1.ShadowColor = System.Drawing.Color.Transparent;
            chartArea1.AxisY2.IntervalAutoMode = IntervalAutoMode.FixedCount;


            chartArea1.CursorX.IsUserEnabled = true;
            chartArea1.CursorX.Position = 2;
            chartArea1.CursorX.SelectionColor = System.Drawing.Color.Gray;
            


            #endregion

            #region chartArea2
            
            //下面3D设置都是没有------------------------------------
            chartArea2.Area3DStyle.IsClustered = true;
            chartArea2.Area3DStyle.Perspective = 10;
            chartArea2.Area3DStyle.IsRightAngleAxes = false;
            chartArea2.Area3DStyle.WallWidth = 0;
            chartArea2.Area3DStyle.Inclination = 15;
            chartArea2.Area3DStyle.Rotation = 10;
            //------------------------------------------------------
            
            chartArea2.AxisX.IsLabelAutoFit = true;
            chartArea2.AxisX.LabelAutoFitStyle = LabelAutoFitStyles.DecreaseFont;
            chartArea2.AxisX.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            chartArea2.AxisX.LabelStyle.IsEndLabelVisible = false;
            chartArea2.AxisX.LineColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            chartArea2.AxisX.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            chartArea2.AxisX.Interval = 5;
            
            chartArea2.AxisY.IsLabelAutoFit = true;
            chartArea2.AxisY.LabelAutoFitStyle = LabelAutoFitStyles.DecreaseFont;
            chartArea2.AxisY.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            chartArea2.AxisY.LineColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            chartArea2.AxisY.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            chartArea2.AxisY.IsStartedFromZero = false;

            chartArea2.AxisY.Maximum = 100;
            chartArea2.AxisY.Minimum = 0;
            //chartArea2.AxisY.Interval = 20;

            chartArea2.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(165)), ((System.Byte)(191)), ((System.Byte)(228)));
            chartArea2.BackSecondaryColor = System.Drawing.Color.White;
            chartArea2.BackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.TopBottom;
            chartArea2.BorderColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            chartArea2.BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
            chartArea2.Name = "Heats";

            chartArea2.AlignWithChartArea = chartArea1.Name;
            chartArea2.Position.Auto = false;
            chartArea2.Position.Height = chartArea1.Position.Height;
            chartArea2.Position.Width = chartArea1.Position.Width;
            chartArea2.Position.X = chartArea1.Position.X;
            chartArea2.Position.Y = 50F;
            chartArea2.ShadowColor = System.Drawing.Color.Transparent;

            chartArea2.CursorX.IsUserEnabled = true;
            chartArea2.CursorX.Position = 2;
            #endregion

            this.chart1.ChartAreas.Add(chartArea1);
            this.chart1.ChartAreas.Add(chartArea2);
            #endregion

            #region legend
            #region legend1
            legend1.Name = "legend1";
            legend1.Alignment = System.Drawing.StringAlignment.Near;
            legend1.IsTextAutoFit = false;
            legend1.BackColor = System.Drawing.Color.Transparent;
            legend1.Docking = Docking.Right;
            legend1.IsDockedInsideChartArea = true;
            legend1.DockedToChartArea = chartArea1.Name;
            legend1.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            legend1.LegendStyle = System.Windows.Forms.DataVisualization.Charting.LegendStyle.Column;
            legend1.Position.Auto = true;
            #endregion

            #region legend2
            legend2.Name = "legend2";
            legend2.Alignment = System.Drawing.StringAlignment.Near;
            legend2.IsTextAutoFit = false;
            legend2.BackColor = System.Drawing.Color.Transparent;
            legend2.Docking = Docking.Right;
            legend2.IsDockedInsideChartArea = true;
            legend2.DockedToChartArea = chartArea2.Name;
            legend2.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            legend2.LegendStyle = System.Windows.Forms.DataVisualization.Charting.LegendStyle.Column;
            legend2.Position.Auto = true;
            #endregion
            chart1.Legends.Add(legend1);
            chart1.Legends.Add(legend2);
            #endregion

            #region series
            series_heatoffsets.Name = "HeatOffsets";
            series_heatoffsets.BorderColor = System.Drawing.Color.FromArgb(((System.Byte)(180)), ((System.Byte)(26)), ((System.Byte)(59)), ((System.Byte)(105)));
            series_heatoffsets.BorderWidth = 2;
            series_heatoffsets.ChartArea = chartArea1.Name;
            series_heatoffsets.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Column;
            series_heatoffsets.Color = System.Drawing.Color.FromArgb(((int)(((byte)(220)))), ((int)(((byte)(65)))), ((int)(((byte)(140)))), ((int)(((byte)(240)))));
            
            //series_heatoffsets.IsVisibleInLegend = true;
            series_heatoffsets.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
            series_heatoffsets.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;

            //series_heatoffsets.MarkerSize = 6;
            //series_heatoffsets.MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Circle;
            series_heatoffsets.ShadowColor = System.Drawing.Color.Black;
            series_heatoffsets.ShadowOffset = 2;
            series_heatoffsets.Legend = legend1.Name;
            series_heatoffsets.LegendText = "加热增量";


            series_thicks.Name = "Thicks";
            series_thicks.BorderColor = System.Drawing.Color.Red;
            series_thicks.BorderWidth = 2;
            series_thicks.ChartArea = chartArea1.Name;
            series_thicks.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            series_thicks.Color = System.Drawing.Color.HotPink;

            //series_thicks.IsVisibleInLegend = true;
            series_thicks.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
            series_thicks.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Double;
            series_thicks.YAxisType = System.Windows.Forms.DataVisualization.Charting.AxisType.Secondary;

            series_thicks.MarkerColor = series_thicks.Color;
            series_thicks.MarkerSize = 12;
            //series_thicks.MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Circle;
            series_thicks.ShadowColor = System.Drawing.Color.Black;
            series_thicks.ShadowOffset = 2;
            series_thicks.Legend = legend1.Name;
            series_thicks.LegendText = "厚度%";



            series_heats.Name = "Heats";
            series_heats.BorderColor = System.Drawing.Color.FromArgb(((System.Byte)(180)), ((System.Byte)(26)), ((System.Byte)(59)), ((System.Byte)(105)));
            series_heats.BorderWidth = 2;
            series_heats.ChartArea = chartArea2.Name;
            series_heats.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Column;
            series_heats.Color = System.Drawing.Color.FromArgb(((int)(((byte)(220)))), ((int)(((byte)(65)))), ((int)(((byte)(140)))), ((int)(((byte)(240)))));
            
            //series_heats.IsVisibleInLegend = true;
            series_heats.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
            series_heats.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
            //series_heats.MarkerSize = 6;
            //series_heats.MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Circle;
            series_heats.ShadowColor = System.Drawing.Color.Black;
            series_heats.ShadowOffset = 2;
            series_heats.Legend = legend2.Name;
            series_heats.LegendText = "加热目标总量";


            series_currs.Name = "Currs";
            series_currs.BorderColor = System.Drawing.Color.DarkSeaGreen;
            series_currs.BorderWidth = 2;
            series_currs.ChartArea = chartArea2.Name;
            series_currs.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            series_currs.Color = System.Drawing.Color.GreenYellow;
            //series_currs.IsVisibleInLegend = true;
            series_currs.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
            series_currs.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
            
            //series_currs.MarkerSize = 6;
            //series_currs.MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Circle;
            series_currs.ShadowColor = System.Drawing.Color.Black;
            series_currs.ShadowOffset = 2;
            series_currs.Legend = legend2.Name;
            series_currs.LegendText = "加热当前总量";


            chart1.Series.Add(series_heatoffsets);
            chart1.Series.Add(series_thicks);
            chart1.Series.Add(series_heats);
            chart1.Series.Add(series_currs);
            #endregion

            chart1.Name = "chart1";
            chart1.Palette = System.Windows.Forms.DataVisualization.Charting.ChartColorPalette.BrightPastel;
            chart1.Location = new System.Drawing.Point(0, 0);


            chart1.CursorPositionChanging += new EventHandler<CursorEventArgs>(chart1_CursorPositionChanging);

            //??????????????????????????????????????
            //((System.ComponentModel.ISupportInitialize)(this.chart1)).EndInit();

        }

        public void UpdateChartArea() 
        {

            System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = chart1.ChartAreas["HeatOffsets"];
            System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea2 = chart1.ChartAreas["Heats"];

            
            chartArea1.InnerPlotPosition.X = (float)sysparam.InnerPlotPositionX;
            chartArea1.InnerPlotPosition.Width = (float)sysparam.InnerPlotPositionWidth;
            chartArea1.InnerPlotPosition.Y = (float)sysparam.InnerPlotPositionY;
            chartArea1.InnerPlotPosition.Height = (float)sysparam.InnerPlotPositionHeight;

            chartArea1.Position.Height = 50F;
            chartArea1.Position.Width= (float)sysparam.PositionWidth;
            chartArea1.Position.X = (float)sysparam.PositionX;
            chartArea1.Position.Y = 0;

                
            chartArea2.Position.Height = chartArea1.Position.Height;
            chartArea2.Position.Width = chartArea1.Position.Width; 
            chartArea2.Position.X = chartArea1.Position.X;
            chartArea2.Position.Y = 50F;

            chartArea2.InnerPlotPosition.X = chartArea1.InnerPlotPosition.X;
            chartArea2.InnerPlotPosition.Width = chartArea1.InnerPlotPosition.Width;
            chartArea2.InnerPlotPosition.Y = chartArea1.InnerPlotPosition.Y;
            chartArea2.InnerPlotPosition.Height = chartArea1.InnerPlotPosition.Height;
        }
        

        void chart1_CursorPositionChanging(object sender, CursorEventArgs e)
        {
            //e.ChartArea == chartarea1
            //e.Axis = AxisX
            int idx = (int)e.NewPosition;
            SelectBoltNo = idx;
        }


        private void MHeatBuf_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "BoltIsStable")
            {
                DataBindAll_Thicks();
            }
        }

        private void MHeatCell_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "Kp")
            {
                chart1.ChartAreas["HeatOffsets"].AxisY2.Maximum = Math.Round(chart1.ChartAreas["HeatOffsets"].AxisY.Maximum / mHeatCell.Kp);
                chart1.ChartAreas["HeatOffsets"].AxisY2.Minimum = Math.Round(chart1.ChartAreas["HeatOffsets"].AxisY.Minimum / mHeatCell.Kp);
            }
            else if (e.PropertyName == "ThickPercents")
            {

                DataBindAll_Thicks();

            }
            else if (e.PropertyName == "Heats")
            {
                DataBindAll("Currs", mHeatCell.Heats );

            }
            else if (e.PropertyName == "Offsets")
            {
                DataBindAll("HeatOffsets", mHeatCell.Offsets);

            }
            else if ((e.PropertyName == "PreHeats") || (e.PropertyName == "Bads"))
            {
                DataBindAll_Heats();
            }
        }

        void mFeedbackHeatService_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if ((e.PropertyName == "ChannelCnt"))
            {
                UpdateAxisX(mFeedback.ChannelCnt);
            }

        }


        void DataBindAll(string series_string, int[] datas)
        {

            int emptyvalue = Misc.MyBase.NULL_VALUE;
            double multi = 1;
            chart1.Series[series_string].Points.Clear();

            for (int i = 0; i < datas.Count(); i++)
            {
                chart1.Series[series_string].Points.AddXY(
                    1 + i,
                    (double)datas[i] / multi);
                DataPoint point = chart1.Series[series_string].Points[i];

                //设定空数据
                if (datas[i] == emptyvalue)
                    point.IsEmpty = true;
                else
                    point.IsEmpty = false;
            }
        }

        void DataBindAll_Thicks()
        {
            Series series = chart1.Series["Thicks"];
            series.Points.Clear();

            if (mHeatCell.ThickPercents == null)
                return;

            if (mHeatCell.ThickPercents.Count() != mFeedback.NBolts)
                return;

            int bpc = mFeedback.NBolts / mFeedback.ChannelCnt;

            for (int i = 0; i < mFeedback.ChannelCnt; i++)
            {
                //有任何一个稳定,它都是稳定的
                bool isStable = false;
                if (mHeatBuf.BoltIsStable != null)
                {
                    for (int j = 0; j < bpc; j++)
                    {
                        int idx = i * bpc + j;
                        if (idx < mHeatBuf.BoltIsStable.Count())
                        {
                            if (mHeatBuf.BoltIsStable[idx])
                            {
                                isStable = true;
                                break;
                            }
                        }
                    }
                }
                //计算平均值
                int avg = Misc.MyMath.Avg(mHeatCell.ThickPercents, i * bpc, (i + 1) * bpc - 1);

                series.Points.AddXY(1 + i, avg);
                
                DataPoint point = series.Points[i];
                if (Misc.MyBase.ISVALIDATA(avg))
                    point.IsEmpty = false;
                else
                    point.IsEmpty = true;

                if (!isStable)
                {
                    point.MarkerStyle = MarkerStyle.Cross;
                }
                else
                {
                    point.MarkerStyle = MarkerStyle.None;
                }

            }
        }
        void DataBindAll_Heats()
        {
            Series series = chart1.Series["Heats"];
            series.Points.Clear();
            
            if (mFeedback.Bads == null)
                return;
            if (mFeedback.Bads.Count() != mFeedback.ChannelCnt)
                return;
            if (mHeatCell.PreHeats.Count() != mFeedback.ChannelCnt)
                return;


            for (int i = 0; i < mFeedback.ChannelCnt; i++)
            {
                if (mFeedback.Bads[i] && mHeatCell.PreHeats[i] == 0)
                {
                    series.Points.AddXY(1 + i,
                        100);
                }
                else
                {
                    series.Points.AddXY(1 + i,
                        mHeatCell.PreHeats[i]);
                }

                DataPoint point = series.Points[i];
                if (mFeedback.Bads[i] && mHeatCell.PreHeats[i] == 0)
                {
                    point.Color = System.Drawing.Color.Red;
                }
                else if (!mFeedback.Bads[i])
                {
                    point.Color = System.Drawing.Color.FromArgb(((int)(((byte)(65)))), ((int)(((byte)(140)))), ((int)(((byte)(240)))));
                }
                else
                {
                    point.Color = System.Drawing.Color.Violet;
                    
                }
    
            }
        }
        void UpdateAxisX(int cnt) 
        {
            chart1.ChartAreas["Heats"].AxisX.Minimum = 0;
            chart1.ChartAreas["Heats"].AxisX.Maximum = cnt+1;

            chart1.ChartAreas["HeatOffsets"].AxisX.Minimum = 0;
            chart1.ChartAreas["HeatOffsets"].AxisX.Maximum = cnt+1;
        }

        private void button_info_click(object sender, RoutedEventArgs e)
        {

        }

        private void button_add_click(object sender, RoutedEventArgs e)
        {
            //获取chart1 当前选择
            mHeatCell.ModifyOffset(SelectBoltNo-1, mFeedback.Step);
        }

        private void button_sub_click(object sender, RoutedEventArgs e)
        {
            mHeatCell.ModifyOffset(SelectBoltNo-1, -mFeedback.Step);
        }

        private void button_undo_click(object sender, RoutedEventArgs e)
        {
            mFeedback.Undo();
        }

        private void button_cal_click(object sender, RoutedEventArgs e)
        {
            mHeatCell.Cal();
        }

        private void button_baseup_click(object sender, RoutedEventArgs e)
        {
            mHeatCell.ModifyBase(mFeedback.Step);
        }

        private void button_basedown_click(object sender, RoutedEventArgs e)
        {
            mHeatCell.ModifyBase( -mFeedback.Step);
        }

        private void button_apply_click(object sender, RoutedEventArgs e)
        {
            mHeatCell.HeatApply();
        }

        private void button_save_click(object sender, RoutedEventArgs e)
        {
            Window_Save w = new Window_Save();
            w.Owner = FLY.ControlLibrary.COMMON.GetWindow(this);
            w.FileName = mFeedback.HeatsProductName;

            if (w.ShowDialog() == true)
            {
                if (string.IsNullOrEmpty(w.FileName))
                {
                    FLY.ControlLibrary.Window_WarningTip.Show("异常",
                        "产品名称 为空",
                        TimeSpan.FromSeconds(2));
                    return;
                }
                char[] invalids = System.IO.Path.GetInvalidFileNameChars();
                
                foreach (char invalidChar in invalids)
                {
                    if (w.FileName.Contains(invalidChar)) 
                    {
                        FLY.ControlLibrary.Window_WarningTip.Show("异常",
                            "产品名称 含有非法字符 "+invalidChar,
                            TimeSpan.FromSeconds(2));
                        return;
                    }
                }

                if (w.FileName.Length > 30)
                {
                    FLY.ControlLibrary.Window_WarningTip.Show("异常",
                       "产品名称 > 30字符",
                       TimeSpan.FromSeconds(2));
                    return;                   
                }

                mFeedback.SaveHeats(w.FileName);
                FLY.ControlLibrary.Window_Tip.Show("加载成功",
                    w.FileName,
                    TimeSpan.FromSeconds(2));
            }
        }

        private void button_load_click(object sender, RoutedEventArgs e)
        {
            Window_Load w = new Window_Load();
            w.Owner = FLY.ControlLibrary.COMMON.GetWindow(this);
            w.Init(mFeedback);
            w.ShowDialog();
        }
        private void button_enable_click(object sender, RoutedEventArgs e)
        {
            mFeedback.SetEnable(!mFeedback.IsAuto);
        }
        private void button_checkenable_click(object sender, RoutedEventArgs e)
        {
            mFeedback.SetCheckEnable(!mFeedback.CheckEnable);
        }
        private void Page_Unloaded(object sender, RoutedEventArgs e)
        {

        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {

        }


        #region INotifyPropertyChanged 成员

        public event PropertyChangedEventHandler PropertyChanged;
        protected void NotifyPropertyChanged(string propertyname)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyname));
            }
        }
        #endregion

        private void button_graphset_click(object sender, RoutedEventArgs e)
        {
            NavigationService ns = Application.Current.Properties["NavigationService"] as NavigationService;
            if (ns != null)
            {
                Page_Setup p = new Page_Setup();
                ns.Navigate(p);
            }
        }



        public LongPress lpress = new LongPress();


        private void button_clear_h_click(object sender, RoutedEventArgs e)
        {
            Button b = sender as Button;
            
            if (!lpress.IsOK)
                mHeatCell.ClearOffsets();
        }

        private void button_smooth_click(object sender, RoutedEventArgs e)
        {
            mHeatCell.Smooth();
        }
    }
    public class LongPress : INotifyPropertyChanged
    {


        /// <summary>
        /// 满9
        /// </summary>
        public int Progress { get; set; }

        public bool IsOK => (Progress == Max);

        public bool IsRunning => (Progress > 0);

        /// <summary>
        /// Progress 最大值
        /// </summary>
        public int Max { get; set; } = 360;

        /// <summary>
        /// 时间间隔
        /// </summary>
        public int IntervalMs { get; set; } = 2000;

        public RoutedEventHandler LongClick;

        private Stopwatch stopwatch = new Stopwatch();
        DispatcherTimer t = new DispatcherTimer();
        DispatcherTimer t_reset = new DispatcherTimer();

        public LongPress()
        {
            t.Tick += T_Tick;
            t.Interval = TimeSpan.FromSeconds(0.1);

            t_reset.Tick += T_reset_Tick;
            t.Interval = TimeSpan.FromSeconds(0.1);
        }

        private void T_reset_Tick(object sender, EventArgs e)
        {
            Reset();
            t_reset.Stop();
        }

        UIElement element;
        public void Init(UIElement element)
        {

            element.PreviewMouseDown += (s, e) => { button_MouseDown(); };
            element.PreviewTouchDown += (s, e) => { button_MouseDown(); };
            element.PreviewMouseUp += (s, e) => { button_MouseUp(); };
            element.PreviewTouchUp += (s, e) => { button_MouseUp(); };

            this.element = element;
        }

        public void button_MouseDown()
        {
            //必须点3秒
            Progress = 0;
            stopwatch.Restart();
            t.Start();
        }
        public void button_MouseUp()
        {
            t.Stop();
            t_reset.Start();
        }
        private void T_Tick(object sender, EventArgs e)
        {
            TimeSpan ts = stopwatch.Elapsed;

            double p = (double)(Max) * ts.TotalMilliseconds / IntervalMs;
            if (p >= Max)
            {
                Progress = Max;
                stopwatch.Stop();
                t.Stop();
                LongClick?.Invoke(element, null);
            }
            else
            {
                Progress = (int)p;
            }
        }



        public void Reset()
        {
            Progress = 0;
        }

        #region INotifyPropertyChanged 成员

        public event PropertyChangedEventHandler PropertyChanged;
        #endregion
    }





    public class UIModule_GraphFB : FLY.UI.Module.IUIModule
    {
        /// <summary>
        /// 控件标题
        /// 它的值取决于culture
        /// </summary>
        public string Title
        {
            get
            {
                return "自动风环调节";
            }
        }

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

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


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