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 FLY.Thick.Base.Client;
using FLY.Thick.Base.UI.Converter;
using Unity;
using FLY.Thick.Base.IService;
using System.ComponentModel;
using System.Collections.ObjectModel;
using GalaSoft.MvvmLight.Command;

namespace FLY.Thick.Base.UI
{
    /// <summary>
    /// Page_Curve.xaml 的交互逻辑
    /// </summary>
    public partial class PgCurve : Page
    {
        PgCurveVm viewModel;
        public PgCurve()
        {
            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 series1 = new System.Windows.Forms.DataVisualization.Charting.Series();
            
            chart1.Name = "chart1";
            // 
            // 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 = false;
            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);

            series1.Name = "Series 1";
            series1.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(180)))), ((int)(((byte)(26)))), ((int)(((byte)(59)))), ((int)(((byte)(105)))));
            series1.BorderWidth = 3;
            series1.ChartArea = "Default";
            series1.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            series1.Color = System.Drawing.Color.FromArgb(((int)(((byte)(220)))), ((int)(((byte)(65)))), ((int)(((byte)(140)))), ((int)(((byte)(240)))));
            series1.Legend = "Default";
            series1.MarkerSize = 8;
            series1.MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Circle;
            
            series1.ShadowColor = System.Drawing.Color.Black;
            series1.ShadowOffset = 2;
            series1.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Double;
            series1.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;



            this.chart1.Series.Add(series1);

            this.chart1.BackColor = System.Drawing.Color.Transparent;
        }


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

            this.DataContext = viewModel;
        }
    }
    public class CurveTypeConverter : EnumToIsCheckedConverter<CurveType>
    {

    }
    public class CurveCorrectWayConverter : EnumToIsCheckedConverter<CurveCorrectWay>
    {

    }

    public class PgCurveVm : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        
        #region 参数
        /// <summary>
        /// AD曲线校正方式
        /// </summary>
        public CurveCorrectWay CorrectWay { get; set; }
        /// <summary>
        /// 标记，用于告诉 客户端，当前的曲线类型， 自然对数 / 直线拟合 / 二次拟合
        /// </summary>
        public CurveType Flag { get; set; }

        public ObservableCollection<CurveCell> Curves { get; } = new ObservableCollection<CurveCell>();

        #endregion

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


        ICurveService mCurveService;
        System.Windows.Forms.DataVisualization.Charting.Chart chart1;
        Page page;
        public PgCurveVm() 
        {
            ApplyCmd = new RelayCommand(Apply);
            ScaleCmd = new RelayCommand(Scale);
        }

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

            Misc.BindingOperations.SetBinding(mCurveService, "CorrectWay", this, "CorrectWay");
            Misc.BindingOperations.SetBinding(mCurveService, "Flag", this, "Flag");
            update_curves();

            
            this.PropertyChanged += PgCurveVm_PropertyChanged;
        }

        private void PgCurveVm_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "Flag") 
            {
                DataBindAll();
            }
        }

        void update_curves() 
        {
            mCurveService.PropertyChanged -= mCurveService_PropertyChanged;
            Curves.CollectionChanged -= Curves_CollectionChanged;
            Curves.Clear();
            if (mCurveService.Curves != null)
            {
                foreach (var cell in mCurveService.Curves)
                {
                    Curves.Add(cell);
                    cell.PropertyChanged += (s, e) => { DataBindAll(); };
                }
            }
            Curves.CollectionChanged += Curves_CollectionChanged;
            mCurveService.PropertyChanged += mCurveService_PropertyChanged;
            DataBindAll();
        }
        void mCurveService_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "Curves") 
            {
                update_curves();
            }
        }

        void Curves_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
            {
                foreach (CurveCell c in e.NewItems)
                {
                    c.PropertyChanged += (_s, _e) => { DataBindAll(); };
                }
                DataBindAll();
            }
            else if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
            {
                DataBindAll();
            }
        }

        void DataBindAll()
        {

            CurveCore CurveCore = new CurveCore();
            CurveCore.Flag = Flag;
            CurveCore.Curves = Curves.ToList();

            var curves = CurveCore.Curves;

            chart1.Series["Series 1"].Points.Clear();
            for (int i = 0; i < curves.Count(); i++)
            {
                int ad = curves[i].AD;
                int thick = curves[i].Value;

                chart1.Series["Series 1"].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 1"].Points.AddXY(thick / 100.0, ad);
                        chart1.Series["Series 1"].Points[chart1.Series["Series 1"].Points.Count() - 1].MarkerStyle =
                            System.Windows.Forms.DataVisualization.Charting.MarkerStyle.None;
                    }
                }
            }
        }
        private void Apply()
        {
            if (!WdPassword.Authorize("Curve"))
                return;

            mCurveService.CorrectWay = this.CorrectWay;
            mCurveService.Flag = this.Flag;
            mCurveService.Curves = this.Curves.ToList();
            mCurveService.Apply();
            FLY.ControlLibrary.Window_Tip.Show("应用成功",
                null,
                TimeSpan.FromSeconds(2));
            
        }
        private void Scale()
        {
            var curves = Curves;
            if (curves.Count > 1)
            {
                WdAdScale w = new WdAdScale();
                w.Old = curves[0].AD;
                w.New = curves[0].AD;
                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].AD = (int)(scale * curves[i].AD);
                        }
                    }
                }
            }
        }
    }
}
