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 FLY.Thick.Base.Common;
using System.Windows.Threading;
using FLY.Thick.Base.Client;
using Unity;
using FLY.Thick.Base.IService;
using System.ComponentModel;
using GalaSoft.MvvmLight.Command;

namespace FLY.Thick.Base.UI
{
    /// <summary>
    /// Page_Curve.xaml 的交互逻辑
    /// </summary>
    public partial class PgCurveModify : Page
    {
        PgCurveModifyVm viewModel;

        public PgCurveModify()
        {
            InitializeComponent();
            InitializeComponent2();
        }



        void InitializeComponent2()
        {
            System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
            System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend();

            System.Windows.Forms.DataVisualization.Charting.Series series_orgad = new System.Windows.Forms.DataVisualization.Charting.Series();

            System.Windows.Forms.DataVisualization.Charting.Series series_revisead = new System.Windows.Forms.DataVisualization.Charting.Series();

            chart1.Name = "chart1";
            chart1.BackColor = System.Drawing.Color.Transparent;
            // 
            // chart1
            // 
            chartArea1.Name = "Default";
            chartArea1.AxisX.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            chartArea1.AxisX.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.AxisX.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.AxisY.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            chartArea1.AxisY.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.AxisY.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.BackColor = System.Drawing.Color.OldLace;
            //chartArea1.BackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.TopBottom;
            //chartArea1.BackSecondaryColor = System.Drawing.Color.White;
            chartArea1.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
            chartArea1.ShadowColor = System.Drawing.Color.Transparent;
            //对数坐标
            //chartArea1.AxisY.IsLogarithmic = true;
            //chartArea1.AxisY.LogarithmBase = Math.E;
            this.chart1.ChartAreas.Add(chartArea1);


            legend1.Name = "Default";
            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;

            this.chart1.Legends.Add(legend1);
            //this.chart1.Location = new System.Drawing.Point(16, 32);

            series_orgad.Name = "series_orgad";
            series_orgad.BorderColor = System.Drawing.Color.LightSkyBlue;
            series_orgad.BorderWidth = 3;
            series_orgad.ChartArea = chartArea1.Name;
            series_orgad.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            series_orgad.Color = System.Drawing.Color.Blue;
            series_orgad.Legend = legend1.Name;
            series_orgad.MarkerSize = 8;
            series_orgad.MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Circle;

            series_orgad.ShadowColor = System.Drawing.Color.Black;
            series_orgad.ShadowOffset = 2;
            series_orgad.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Double;
            series_orgad.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;

            series_orgad.LegendText = "原始曲线";

            this.chart1.Series.Add(series_orgad);

            series_revisead.Name = "series_revisead";
            series_revisead.BorderColor = System.Drawing.Color.LightPink;
            series_revisead.BorderWidth = 3;
            series_revisead.ChartArea = chartArea1.Name;
            series_revisead.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            series_revisead.Color = System.Drawing.Color.Red;
            series_revisead.Legend = legend1.Name;
            series_revisead.MarkerSize = 8;
            series_revisead.MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Circle;

            series_revisead.ShadowColor = System.Drawing.Color.Black;
            series_revisead.ShadowOffset = 2;
            series_revisead.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Double;
            series_revisead.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;

            series_revisead.LegendText = "样品修正后曲线";
            this.chart1.Series.Add(series_revisead);
        }

        [InjectionMethod]
        public void Init(ICurveService curveService)
        {
            viewModel = new PgCurveModifyVm();
            viewModel.Init(curveService, chart1, this);
            this.DataContext = viewModel;
        }
    }

    public class PgCurveModifyVm : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        #region Command
        public RelayCommand ApplyCmd { get; }
        public RelayCommand ScaleCmd { get; }

        public RelayCommand SetRevisedCmd { get; }
        #endregion

        CurveCore curveCore = new CurveCore();
        ICurveService curveService;
        System.Windows.Forms.DataVisualization.Charting.Chart chart1;
        Page page;

        public PgCurveModifyVm() 
        {
            ApplyCmd = new RelayCommand(Apply);
            ScaleCmd = new RelayCommand(Scale);
            SetRevisedCmd = new RelayCommand(SetRevised);
        }

        public void Init(ICurveService curveService,
            System.Windows.Forms.DataVisualization.Charting.Chart chart1,
            Page page)
        {
            this.curveService = curveService;
            this.chart1 = chart1;
            this.page = page;

            update_curves();
            curveService.PropertyChanged += mCurveService_PropertyChanged;
        }

        void update_curves()
        {
            curveCore.Flag = curveService.Flag;
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(curveService.Curves);
            curveCore.Curves = Newtonsoft.Json.JsonConvert.DeserializeObject<List<CurveCell>>(json);
            DataBindAll();
        }
        void mCurveService_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "Flag")
            {
                curveCore.Flag = curveService.Flag;
                DataBindAll();
            }
            else if (e.PropertyName == "Curves")
            {
                string json = Newtonsoft.Json.JsonConvert.SerializeObject(curveService.Curves);
                curveCore.Curves = Newtonsoft.Json.JsonConvert.DeserializeObject<List<CurveCell>>(json);
                DataBindAll();
            }
        }

        #region DataBindAll

        void DataBindAll()
        {
            DataBindAll_OrgAD();
            DataBindAll_RevisedAD();
        }

        void DataBindAll_OrgAD()
        {
            var curves = curveCore.Curves;
            chart1.Series["series_orgad"].Points.Clear();
            for (int i = 0; i < curves.Count(); i++)
            {
                int ad = curves[i].AD;
                int thick = curves[i].Value;

                chart1.Series["series_orgad"].Points.AddXY(thick / 100.0, ad);

                if ((i + 1) <= (curves.Count() - 1))
                {
                    //补齐点， 以thick=100 步进
                    int step = 100;
                    bool isDescending = true;//降序排列
                    if (curves[i].AD < curves[i + 1].AD)
                        isDescending = false;

                    while (true)
                    {
                        if (isDescending)
                        {
                            ad -= step;
                            if (ad <= curves[i + 1].AD)
                                break;
                        }
                        else
                        {
                            ad += step;
                            if (ad >= curves[i + 1].AD)
                                break;
                        }

                        thick = curveCore.AD2Value(ad, AD2ValueFlag.NoRevised);
                        chart1.Series["series_orgad"].Points.AddXY(thick / 100.0, ad);
                        chart1.Series["series_orgad"].Points.Last().MarkerStyle =
                            System.Windows.Forms.DataVisualization.Charting.MarkerStyle.None;
                    }
                }
            }
        }
        void DataBindAll_RevisedAD()
        {
            var curves = curveCore.Curves;
            chart1.Series["series_revisead"].Points.Clear();
            for (int i = 0; i < curves.Count(); i++)
            {
                int ad = curves[i].RevisedAD;
                int thick = curves[i].Value;

                chart1.Series["series_revisead"].Points.AddXY(thick / 100.0, ad);

                if ((i + 1) <= (curves.Count() - 1))
                {
                    //补齐点， 以thick=100 步进
                    int step = 100;
                    bool isDescending = true;//降序排列
                    if (curves[i].AD < curves[i + 1].AD)
                        isDescending = false;

                    while (true)
                    {
                        if (isDescending)
                        {
                            ad -= step;
                            if (ad <= curves[i + 1].AD)
                                break;
                        }
                        else
                        {
                            ad += step;
                            if (ad >= curves[i + 1].AD)
                                break;
                        }

                        thick = curveCore.AD2Value(ad, AD2ValueFlag.Revised);
                        chart1.Series["series_revisead"].Points.AddXY(thick / 100.0, ad);
                        chart1.Series["series_revisead"].Points.Last().MarkerStyle =
                            System.Windows.Forms.DataVisualization.Charting.MarkerStyle.None;
                    }
                }
            }
        }
        #endregion

        private void Scale()
        {
            var curves = curveCore.Curves;
            if (curves.Count > 1)
            {
                WdThickScale w = new WdThickScale();
                w.Old = curves[1].Value / 100.0;
                w.New = curves[1].Value / 100.0;
                w.Owner = FLY.ControlLibrary.COMMON.GetWindow(page);
                if (w.ShowDialog() == true)
                {
                    if ((w.Old != w.New) && (w.New != 0) && (w.Old != 0))
                    {
                        double scale = (double)w.New / w.Old;
                        for (int i = 0; i < curves.Count(); i++)
                        {
                            curves[i].Value = (int)(scale * curves[i].Value);
                        }
                    }
                }
            }
            DataBindAll();
        }

        private void SetRevised()
        {
            var curves = curveCore.Curves;
            for (int i = 0; i < curves.Count(); i++)
            {
                curves[i].AD = curves[i].RevisedAD;
            }
            DataBindAll();
        }

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

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