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.Windows.Forms.DataVisualization.Charting;
using System.Net;

using System.Threading;
using System.IO;

using FLY.Thick.Base.IService;
using FLY.Thick.Base.Client;
using FObjBase;
using Unity;
using GalaSoft.MvvmLight.Command;

namespace FLY.Thick.Base.UI
{
    /// <summary>
    /// Page_Reject.xaml 的交互逻辑
    /// </summary>
    public partial class PgReject : Page
    {
        IRejectService rejectService;
        IInitParamService initParamService;
        PgRejectVm viewModel;

        public PgReject()
        {
            InitializeComponent();
            InitializeChart();
        }


        void InitializeChart()
        {
            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 series_orgthicks = new System.Windows.Forms.DataVisualization.Charting.Series();
            System.Windows.Forms.DataVisualization.Charting.Series series_currthicks = new System.Windows.Forms.DataVisualization.Charting.Series();
            System.Windows.Forms.DataVisualization.Charting.Series series_sigma = 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 = false;
            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.Title = "位置(脉冲)";

            chartArea1.AxisY.IsLabelAutoFit = false;
            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 = false;

            chartArea1.AxisY2.IsLabelAutoFit = false;
            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.AxisY2.Title = "剔除系数 / 变化量";

            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.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.Name = "chartArea1";
            chartArea1.Position.Auto = true;
            chartArea1.ShadowColor = System.Drawing.Color.Transparent;
            //chartArea1.AxisY2.IntervalAutoMode = IntervalAutoMode.FixedCount;

            #endregion


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

            #region legend
            legend1.Alignment = System.Drawing.StringAlignment.Near;
            legend1.IsTextAutoFit = false;
            legend1.BackColor = System.Drawing.Color.Transparent;
            legend1.Docking = System.Windows.Forms.DataVisualization.Charting.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.Row;
            legend1.Name = "Default";
            legend1.Position.Auto = true;
            chart1.Legends.Add(legend1);
            #endregion

            #region series
            series_orgthicks.BorderColor = System.Drawing.Color.FromArgb(((System.Byte)(180)), ((System.Byte)(26)), ((System.Byte)(59)), ((System.Byte)(105)));
            series_orgthicks.BorderWidth = 2;
            series_orgthicks.ChartArea = chart1.Name;
            series_orgthicks.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            series_orgthicks.Color = System.Drawing.Color.FromArgb(((int)(((byte)(220)))), ((int)(((byte)(65)))), ((int)(((byte)(140)))), ((int)(((byte)(240)))));
            series_orgthicks.Name = "OrgThicks";
            series_orgthicks.LegendText = "原始数据";
            //series_heatoffsets.IsVisibleInLegend = true;
            series_orgthicks.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
            series_orgthicks.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Double;

            series_orgthicks.ShadowColor = System.Drawing.Color.Black;
            series_orgthicks.ShadowOffset = 2;

            series_currthicks.BorderColor = System.Drawing.Color.Red;
            series_currthicks.BorderWidth = 2;
            series_currthicks.ChartArea = chart1.Name;
            series_currthicks.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            series_currthicks.Color = System.Drawing.Color.HotPink;
            series_currthicks.Name = "CurrThicks";
            series_currthicks.LegendText = "剔除后";
            //series_thicks.IsVisibleInLegend = true;
            series_currthicks.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
            series_currthicks.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Double;


            series_currthicks.ShadowColor = System.Drawing.Color.Black;
            series_currthicks.ShadowOffset = 2;


            series_sigma.BorderColor = System.Drawing.Color.DarkSeaGreen;
            series_sigma.BorderWidth = 2;
            series_sigma.ChartArea = chart1.Name;
            series_sigma.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            series_sigma.Color = System.Drawing.Color.DarkSeaGreen;
            series_sigma.Name = "Sigma";
            series_sigma.LegendText = "变化量";
            //series_thicks.IsVisibleInLegend = true;
            series_sigma.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
            series_sigma.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Double;
            series_sigma.YAxisType = System.Windows.Forms.DataVisualization.Charting.AxisType.Secondary;

            //series_thicks.MarkerSize = 6;
            //series_thicks.MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Circle;
            series_sigma.ShadowColor = System.Drawing.Color.Black;
            series_sigma.ShadowOffset = 2;









            chart1.Series.Add(series_orgthicks);
            chart1.Series.Add(series_currthicks);
            chart1.Series.Add(series_sigma);
            #endregion

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

        [InjectionMethod]
        public void Init(
            IRejectService rejectService, 
            IInitParamService initParamService)
        {
            viewModel = new PgRejectVm();
            viewModel.Init(rejectService, initParamService, chart1, this);
            this.DataContext = this.viewModel;
        }
    }
    public class RejectSaveManager : SaveManager
    {
        IRejectService mRejectService;
        int[] FilterDatas;
        int[] SigmaDatas;
        int[] RejectDatas;
        int posOfGrid;

        public void Init(IRejectService reject)
        {
            mRejectService = reject;
        }

        protected override void Output()
        {
            string path = SavePath;
            try
            {
                using (StreamWriter sw = new StreamWriter(path, false, Encoding.GetEncoding("GB2312")))
                {
                    sw.WriteLine("位置(脉冲),滤波数据,sigma,剔除后");

                    for (int i = 0; i < FilterDatas.Count(); i++)
                    {
                        sw.Write((i * posOfGrid).ToString());
                        sw.Write(",");
                        if (Misc.MyBase.ISVALIDATA(FilterDatas[i]))
                        {
                            sw.Write((FilterDatas[i] / 100.0).ToString("N1"));
                        }
                        sw.Write(",");
                        if (Misc.MyBase.ISVALIDATA(SigmaDatas[i]))
                        {
                            sw.Write((SigmaDatas[i] / 100.0).ToString("N1"));
                        }
                        sw.Write(",");
                        if (Misc.MyBase.ISVALIDATA(RejectDatas[i]))
                        {
                            sw.Write((RejectDatas[i] / 100.0).ToString("N1"));
                        }
                        sw.WriteLine();
                    }
                    sw.Flush();
                    sw.Close();
                }
                Return(true);
            }
            catch (Exception e)
            {
                Return(false);
            }
        }

        protected override bool Backup()
        {
            if ((mRejectService.FilterDatas == null) ||
                (mRejectService.SigmaDatas == null) ||
                (mRejectService.RejectDatas == null)
                )
            {
                return false;
            }
            FilterDatas = mRejectService.FilterDatas.Clone() as int[];
            SigmaDatas = mRejectService.SigmaDatas.Clone() as int[];
            RejectDatas = mRejectService.RejectDatas.Clone() as int[];
            posOfGrid = mRejectService.PosOfGrid;
            return true;
        }
    }

    public class PgRejectVm : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// 使能
        /// </summary>
        public bool Enable { get; set; }
        /// <summary>
        /// 剔除阈值,低于 ThresholdRatio*Target 都要被删除
        /// </summary>
        public double ThresholdRatio { get; set; }

        /// <summary>
        /// 当前Sigma 大于 设置Sigma, 剔除
        /// </summary>
        public int Sigma { get; set; }

        /// <summary>
        /// 滤波范围,单位脉冲
        /// </summary>
        public int Range1 { get; set; }
        /// <summary>
        /// 当前数据需要剔除,那么它的前后Range2个脉冲的数据都是删除,单位脉冲
        /// </summary>
        public int Range2 { get; set; }

        public RelayCommand ApplyCmd { get; }
        public RelayCommand SaveCmd { get; }

        IRejectService rejectService;
        public IInitParamService InitParamService { get; private set; }
        System.Windows.Forms.DataVisualization.Charting.Chart chart1;
        Page page;
        public PgRejectVm() 
        {
            ApplyCmd = new RelayCommand(Apply);
            SaveCmd = new RelayCommand(Save);
        }
        public void Init(
            IRejectService rejectService,
            IInitParamService initParamService,
            System.Windows.Forms.DataVisualization.Charting.Chart chart,
            Page page)
        {
            this.rejectService = rejectService;
            this.InitParamService = initParamService;
            this.chart1 = chart;
            this.page = page;

            Misc.BindingOperations.SetBinding(rejectService, "Enable", this, "Enable");
            Misc.BindingOperations.SetBinding(rejectService, "ThresholdRatio", this, "ThresholdRatio");
            Misc.BindingOperations.SetBinding(rejectService, "Sigma", this, "Sigma");
            Misc.BindingOperations.SetBinding(rejectService, "Range1", this, "Range1");
            Misc.BindingOperations.SetBinding(rejectService, "Range2", this, "Range2");


            UpdateStripLineY();
            UpdateStripLineY2();
            UpdateX();

            this.rejectService.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(mRejectService_PropertyChanged);
            this.InitParamService.PropertyChanged += new PropertyChangedEventHandler(mInitParamService_PropertyChanged);
            this.PropertyChanged += PgRejectVm_PropertyChanged;
        }

        private void PgRejectVm_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "ThresholdRatio")
            {
                UpdateStripLineY();
            }
            else if (e.PropertyName == "Sigma")
            {
                UpdateStripLineY2();
            }
        }

        private void Save()
        {

            //mFixGraphManager.PreSave();
            RejectSaveManager rsm = new RejectSaveManager();
            rsm.Init(rejectService);
            rsm.PreSave();
            WdSaveDatas w = new WdSaveDatas();
            w.Init(rsm);
            w.Owner = FLY.ControlLibrary.COMMON.GetWindow(page);
            w.ShowDialog();
        }

        private void Apply()
        {
            if (!WdPassword.Authorize("Reject"))
                return;

            rejectService.Enable = this.Enable;
            rejectService.ThresholdRatio = this.ThresholdRatio;
            rejectService.Sigma = this.Sigma;
            rejectService.Range1 = this.Range1;
            rejectService.Range2 = this.Range2;

            rejectService.Apply();
            FLY.ControlLibrary.Window_Tip.Show("应用成功",
                null,
                TimeSpan.FromSeconds(2));
            
        }

        void UpdateStripLineY()
        {
            double thresholdRatio = this.ThresholdRatio;
            int target = rejectService.Target;
            StripLine stripLine = new StripLine();

            // Set Strip lines interval
            stripLine.Interval = 0;
            stripLine.IntervalOffset = target * thresholdRatio / 100.0;
            // Set Strip Border Line Color
            stripLine.BorderColor = System.Drawing.Color.Red;

            // Set Strip Width
            stripLine.StripWidth = 0.1;

            // Set Strip Back Color
            stripLine.BackColor = System.Drawing.Color.Red;


            // Add the strip line to the collection.
            chart1.ChartAreas[0].AxisY.StripLines.Clear();
            chart1.ChartAreas[0].AxisY.StripLines.Add(stripLine);
        }
        void UpdateStripLineY2()
        {
            int sigma = this.Sigma;
            StripLine stripLine = new StripLine();

            // Set Strip lines interval
            stripLine.Interval = 0;
            stripLine.IntervalOffset = sigma / 100.0;
            // Set Strip Border Line Color
            stripLine.BorderColor = System.Drawing.Color.Orange;

            // Set Strip Width
            stripLine.StripWidth = 0.01;

            // Set Strip Back Color
            stripLine.BackColor = System.Drawing.Color.Orange;


            // Add the strip line to the collection.
            chart1.ChartAreas[0].AxisY2.StripLines.Clear();
            chart1.ChartAreas[0].AxisY2.StripLines.Add(stripLine);
        }
        void DataBindAll(System.Windows.Forms.DataVisualization.Charting.Series series, int[] grid, int posOfGrid)
        {
            series.Points.Clear();
            for (int i = 0; i < grid.Length; i++)
            {
                series.Points.AddXY(i * posOfGrid, grid[i] / 100.0);
                if (!Misc.MyBase.ISVALIDATA(grid[i]))
                {
                    series.Points[i].IsEmpty = true;
                }
            }
        }

        void UpdateX()
        {
            chart1.ChartAreas[0].AxisX.Minimum = 0;
            chart1.ChartAreas[0].AxisX.Maximum = InitParamService.PosLength;

            chart1.ChartAreas[0].AxisX2.Minimum = 0;
            chart1.ChartAreas[0].AxisX2.Maximum = InitParamService.Encoder1_mmpp * InitParamService.PosLength;
        }
        void mInitParamService_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if ((e.PropertyName == "PosLength") || (e.PropertyName == "Encoder1_mmpp"))
            {
                UpdateX();
            }
        }


        void DrawBorder(System.Windows.Forms.DataVisualization.Charting.Series series, int pos)
        {
            if (rejectService.FilterDatas == null)
            {
                return;
            }

            int posOfGrid = rejectService.PosOfGrid;
            int grid = pos / posOfGrid;
            if (grid < rejectService.FilterDatas.Count())
            {
                int thick = rejectService.FilterDatas[grid];
                if (Misc.MyBase.ISVALIDATA(thick))
                {
                    series.Points.AddXY(pos, thick / 100.0);
                }
            }
        }

        void mRejectService_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "FilterDatas")
            {
                DataBindAll(chart1.Series["OrgThicks"], rejectService.FilterDatas, rejectService.PosOfGrid);
            }
            else if (e.PropertyName == "RejectDatas")
            {
                DataBindAll(chart1.Series["CurrThicks"], rejectService.RejectDatas, rejectService.PosOfGrid);
            }
            else if (e.PropertyName == "SigmaDatas")
            {
                DataBindAll(chart1.Series["Sigma"], rejectService.SigmaDatas, rejectService.PosOfGrid);
            }
            else if (e.PropertyName == "Target")
            {
                UpdateStripLineY();
            }

        }


    }
}