using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;

using System.Net;

using FLY.Thick.Base.IService;
using FLY.Thick.Base.Client;
using FLY.Thick.Base.Common;
using System.IO;
using Unity;
using GalaSoft.MvvmLight.Command;

namespace FLY.Thick.Base.UI
{
    /// <summary>
    /// Page_ScanCorr.xaml 的交互逻辑
    /// </summary>
    public partial class PgScanCorr : Page
    {
        PgScanCorrVm viewModel;
        public PgScanCorr()
        {
            InitializeComponent();
            InitializeComponent2();
           


            //stackpanel_groupindex.DataContext = this;
        }

        void InitializeComponent_chart2(System.Windows.Forms.DataVisualization.Charting.Chart Chart1)
        {
            System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
            System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend();
            System.Windows.Forms.DataVisualization.Charting.Series series1 = new System.Windows.Forms.DataVisualization.Charting.Series();
            System.Windows.Forms.DataVisualization.Charting.Series series2 = new System.Windows.Forms.DataVisualization.Charting.Series();

            // 
            // Chart1
            // 
            Chart1.BackColor = System.Drawing.Color.Transparent;

            chartArea1.Area3DStyle.Inclination = 15;
            chartArea1.Area3DStyle.IsClustered = true;
            chartArea1.Area3DStyle.IsRightAngleAxes = false;
            chartArea1.Area3DStyle.Perspective = 10;
            chartArea1.Area3DStyle.Rotation = 10;
            chartArea1.Area3DStyle.WallWidth = 0;
            chartArea1.AxisX.IsLabelAutoFit = false;
            chartArea1.AxisX.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            chartArea1.AxisX.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.AxisX.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.AxisX.ScrollBar.BackColor = System.Drawing.Color.AliceBlue;
            chartArea1.AxisX.ScrollBar.ButtonColor = System.Drawing.SystemColors.Control;
            chartArea1.AxisX.ScrollBar.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.AxisY.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            chartArea1.AxisY.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.AxisY.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.AxisY.ScrollBar.BackColor = System.Drawing.Color.AliceBlue;
            chartArea1.AxisY.ScrollBar.ButtonColor = System.Drawing.SystemColors.Control;
            chartArea1.AxisY.ScrollBar.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(165)))), ((int)(((byte)(191)))), ((int)(((byte)(228)))));
            chartArea1.BackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.TopBottom;
            chartArea1.BackSecondaryColor = System.Drawing.Color.White;
            chartArea1.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.CursorX.IsUserEnabled = true;
            chartArea1.CursorX.IsUserSelectionEnabled = true;
            chartArea1.CursorX.SelectionColor = System.Drawing.SystemColors.Highlight;
            chartArea1.CursorY.IsUserEnabled = true;
            chartArea1.CursorY.IsUserSelectionEnabled = true;
            chartArea1.CursorY.SelectionColor = System.Drawing.SystemColors.Highlight;
            chartArea1.InnerPlotPosition.Auto = false;
            chartArea1.InnerPlotPosition.Height = 75F;
            chartArea1.InnerPlotPosition.Width = 86.32634F;
            chartArea1.InnerPlotPosition.X = 11.21863F;
            chartArea1.InnerPlotPosition.Y = 3.96004F;
            chartArea1.Name = "Default";
            chartArea1.Position.Auto = false;// true;
            chartArea1.Position.Height = 100;//
            chartArea1.Position.Width = 100;// 81.46518F;
            chartArea1.Position.X = 0;// 9.267409F;
            chartArea1.Position.Y = 0;// 10F;

            chartArea1.ShadowColor = System.Drawing.Color.Transparent;
            Chart1.ChartAreas.Add(chartArea1);
            legend1.BackColor = System.Drawing.Color.Transparent;
            legend1.Enabled = true;
            legend1.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            legend1.IsTextAutoFit = false;
            legend1.Name = "Default";
            Chart1.Legends.Add(legend1);
            //Chart1.Location = new System.Drawing.Point(16, 48);
            Chart1.Name = "Chart1";
         

            //series1
            series1.BorderColor = System.Drawing.Color.DarkBlue;
            series1.BorderWidth = 3;

            series1.ChartArea = "Default";
            series1.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            series1.Color = System.Drawing.Color.Blue;// 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 = "正向";
            series1.ShadowColor = System.Drawing.Color.Black;
            series1.ShadowOffset = 2;
            //series1.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
            //series1.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Double;
            Chart1.Series.Add(series1);


            //series2
            series2.BorderColor = System.Drawing.Color.DarkRed;
            series2.BorderWidth = 3;

            series2.ChartArea = "Default";
            series2.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            series2.Color = System.Drawing.Color.Red; //System.Drawing.Color.FromArgb(((int)(((byte)(220)))), ((int)(((byte)(65)))), ((int)(((byte)(140)))), ((int)(((byte)(240)))));

            series2.Legend = "Default";
            //series2.MarkerSize = 6;
            //series2.MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Circle;
            series2.Name = "反向";
            series2.ShadowColor = System.Drawing.Color.Black;
            series2.ShadowOffset = 2;
            //series2.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
            //series2.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Double;

            Chart1.Series.Add(series2);
        }
        void InitializeComponent2()
        {
            InitializeComponent_chart2(chart1);
        }

        [InjectionMethod]
        public void Init(
            IUnityContainer container,
            IScanCorrService scanCorrService, 
            IInitParamService initParamService
            ) 
        {
            viewModel = new PgScanCorrVm();
            viewModel.Init(scanCorrService, initParamService,chart1);
            this.DataContext = viewModel;

            container.BuildUp(mircoGage);
        }
    }

    public class PgScanCorrVm : INotifyPropertyChanged 
    {
        #region
        [PropertyChanged.DoNotCheckEquality]
        public int GroupIndex { get; set; } = 0;

        /// <summary>
        /// 使能修正
        /// </summary>
        public bool Enable { set; get; }

        /// <summary>
        /// 来回次数
        /// </summary>
        public int ScanTimer { get; set; }

        /// <summary>
        /// 平滑,移动窗口
        /// </summary>
        public int SmoothFactor { get; set; }

        /// <summary>
        /// 有效范围.开始,单位脉冲
        /// </summary>
        public int ValidBegin { get; set; }
        /// <summary>
        /// 有效范围.结束,单位脉冲
        /// </summary>
        public int ValidEnd { get; set; } = 8000;
        #endregion
        public int AvgAD { get; private set; }

        public RelayCommand ApplyCmd { get; }
        public RelayCommand StartCmd { get; }

        public RelayCommand ClearCmd { get; }

        public RelayCommand SmoothCmd { get; }



        public IScanCorrService ScanCorrService { get; private set; }
        public IInitParamService InitParamService { get; private set; }
        System.Windows.Forms.DataVisualization.Charting.Chart chart1;

        public PgScanCorrVm() 
        {
            ApplyCmd = new RelayCommand(Apply);
            StartCmd = new RelayCommand(Start);
            ClearCmd = new RelayCommand(Clear);
            SmoothCmd = new RelayCommand(Smooth);
        }
        public void Init(
            IScanCorrService scanCorrService,
            IInitParamService initParamService,
            System.Windows.Forms.DataVisualization.Charting.Chart chart
            )
        {
            this.chart1 = chart;
            this.ScanCorrService = scanCorrService;
            this.InitParamService = initParamService;

            Misc.BindingOperations.SetBinding(this.ScanCorrService, "Enable", this, "Enable");
            Misc.BindingOperations.SetBinding(this.ScanCorrService, "ScanTimer", this, "ScanTimer");
            Misc.BindingOperations.SetBinding(this.ScanCorrService, "SmoothFactor", this, "SmoothFactor");
            Misc.BindingOperations.SetBinding(this.ScanCorrService, "ValidBegin", this, "ValidBegin");
            Misc.BindingOperations.SetBinding(this.ScanCorrService, "ValidEnd", this, "ValidEnd");

            this.ScanCorrService.Group0.PropertyChanged += new PropertyChangedEventHandler(Group_PropertyChanged);
            this.ScanCorrService.Group1.PropertyChanged += new PropertyChangedEventHandler(Group_PropertyChanged);
            this.PropertyChanged += PgScanCorrVm_PropertyChanged;
            update_validrange();
            update_avgAd();
        }

        private void PgScanCorrVm_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "GroupIndex")
            {
                update_avgAd();
                update_chart();
            }
            else if ((e.PropertyName == "ValidBegin") || (e.PropertyName == "ValidEnd"))
            {
                update_validrange();
            }
        }

        void update_avgAd() 
        {
            if (GroupIndex == 0)
            {
                AvgAD = ScanCorrService.Group0.AvgAD;
            }
            else 
            {
                AvgAD = ScanCorrService.Group1.AvgAD;
            }
        }
        void update_chart() 
        {
            if (GroupIndex == 0)
            {
                DataBindAll(chart1, ScanCorrService.Group0);
            }
            else
            {
                DataBindAll(chart1, ScanCorrService.Group1);
            }
        }

        private void Apply()
        {
            ScanCorrService.Enable = this.Enable;
            ScanCorrService.ValidBegin = this.ValidBegin;
            ScanCorrService.ValidEnd = this.ValidEnd;
            ScanCorrService.Apply();
        }

        void Group_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (sender == this.ScanCorrService.Group0 && GroupIndex == 0)
            {

            }
            else if (sender == this.ScanCorrService.Group1 && GroupIndex == 1)
            {

            }
            else 
            {
                return;
            }

            if ((e.PropertyName == "ForwDatas") || (e.PropertyName == "BackwDatas"))
            {
                update_chart();
            }
            else if (e.PropertyName == "AvgAD") 
            {
                update_avgAd();
            }
        }


        #region INotifyPropertyChanged 成员

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

        void DataBindAll(
            System.Windows.Forms.DataVisualization.Charting.Chart chart,
            IScanCorrGroup group)
        {
            string[] series = new string[2] { "正向", "反向" };
            if (ScanCorrService.PosOfGrid <= 0)
                return;
            int datadatasize = group.ForwDatas.Count();

            chart.Series[0].Points.Clear();

            chart.Series[1].Points.Clear();

            int max = Misc.MyBase.NULL_VALUE, min = Misc.MyBase.NULL_VALUE;


            for (int i = 0; i < group.ForwDatas.Count(); i++)
            {
                int data = group.ForwDatas[i];
                int pos = i * ScanCorrService.PosOfGrid;

                chart1.Series[0].Points.AddXY(pos, data);

                if (!Misc.MyBase.ISVALIDATA(data))
                {

                    chart1.Series[0].Points[i].IsEmpty = true;
                }
                else
                {
                    if (!Misc.MyBase.ISVALIDATA(max))
                    {
                        max = data;
                        min = data;
                    }
                    if (max < data)
                        max = data;
                    if (min > data)
                        min = data;
                }
            }

            for (int i = 0; i < group.BackwDatas.Count(); i++)
            {
                int data = group.BackwDatas[i];
                int pos = i * ScanCorrService.PosOfGrid;

                chart1.Series[1].Points.AddXY(pos, data);
                if (!Misc.MyBase.ISVALIDATA(data))
                {
                    chart1.Series[1].Points[i].IsEmpty = true;
                }
                else
                {
                    if (!Misc.MyBase.ISVALIDATA(max))
                    {
                        max = data;
                        min = data;
                    }
                    if (max < data)
                        max = data;
                    if (min > data)
                        min = data;
                }
            }
            //set max min
            if (max != min)
            {
                chart1.ChartAreas[0].AxisY.Maximum = max;
                chart1.ChartAreas[0].AxisY.Minimum = min;
            }
            chart1.ChartAreas[0].AxisX.Minimum = 0;
            chart1.ChartAreas[0].AxisX.Maximum = ScanCorrService.PosLen;
        }


        void update_validrange()
        {
            int validBegin = this.ValidBegin;
            int validEnd = this.ValidEnd;

            System.Windows.Forms.DataVisualization.Charting.StripLinesCollection stripLines = chart1.ChartAreas[0].AxisX.StripLines;
            stripLines.Clear();
            System.Windows.Forms.DataVisualization.Charting.StripLine stripline = new System.Windows.Forms.DataVisualization.Charting.StripLine();
            stripline.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(191)))), ((int)(((byte)(191)))), ((int)(((byte)(191)))));
            stripline.Interval = 0;
            stripline.IntervalOffset = validBegin;
            stripline.StripWidth = validEnd - validBegin + 1;
            stripLines.Add(stripline);
        }


        private void Start()
        {
            ScanCorrService.ScanTimer = this.ScanTimer;
            ScanCorrService.SmoothFactor = this.SmoothFactor;
            ScanCorrService.Start(GroupIndex);
        }

        private void Clear()
        {
            ScanCorrService.Clear(GroupIndex);
        }

        private void Smooth()
        {
            ScanCorrService.SmoothFactor = this.SmoothFactor;
            ScanCorrService.Smooth(GroupIndex);
        }
    }
    
    public class Group2boolConverter : IValueConverter
    {

        #region IValueConverter 成员

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            int groupindex = (int)value;

            if (groupindex == 0)
                return false;
            else
                return true;
        }


        #endregion

        #region IValueConverter 成员


        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            bool b = (bool)value;
            if (b == false)
                return 0;
            else
                return 1;
        }

        #endregion
    }
}