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.IService;
using FLY.Thick.Base.UI;
using Unity;

using System.ComponentModel;


namespace FLY.Thick.Base.UI
{
    /// <summary>
    /// Page_GetSample.xaml 的交互逻辑
    /// </summary>
    public partial class PgGetSample : Page
    {
        IGetSampleService getSampleService;
        IInitParamService initParamService;
        IGageInfoService gageInfoService;
        IUnityContainer container;

        GetSampleVm viewModel;

        public PgGetSample()
        {
            InitializeComponent();
        }
        [InjectionMethod]
        public void Init(
            IUnityContainer container, 
            IGetSampleService getSampleService,
            IInitParamService initParamService,
            IGageInfoService gageInfoService) 
        {

            this.getSampleService = getSampleService;
            this.initParamService = initParamService;
            this.gageInfoService = gageInfoService;
            this.container = container;


            //复制一份 getsample
            //TODO
            viewModel = new GetSampleVm();
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(getSampleService);
            Newtonsoft.Json.JsonConvert.PopulateObject(json, viewModel);
            viewModel.IsChanged = false;
            foreach (var s in viewModel.Samples)
                s.IsChanged = false;
            foreach (var s in viewModel.Features)
                s.IsChanged = false;

            this.DataContext = viewModel;
            this.grid_null.DataContext = this.initParamService;
        }

        private void button_apply_Click(object sender, RoutedEventArgs e)
        {
            if (!WdPassword.Authorize("GetSample"))
                return;

            bool isChanged = false;
            if (viewModel.IsChanged)
                isChanged = true;
            else if (viewModel.Samples.Any(s => s.IsChanged))
                isChanged = true;
            else if (viewModel.Features.Any(f => f.IsChanged))
                isChanged = true;
            if (!isChanged)
            {
                FLY.ControlLibrary.Window_Tip.Show("操作无效",
                    "没有任何数据被修改",
                    TimeSpan.FromSeconds(2));
                return;
            }

            //复制一份 到 getSampleService
            //TODO
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(viewModel);
            Newtonsoft.Json.JsonConvert.PopulateObject(json, getSampleService);
            getSampleService.Apply();
            FLY.ControlLibrary.Window_Tip.Show("应用成功",
                null,
                TimeSpan.FromSeconds(2));
            
        }

        private void button_getorgad_Click(object sender, RoutedEventArgs e)
        {
            if (gageInfoService.ForwData == null || gageInfoService.BackwData == null)
            {
                FLY.ControlLibrary.Window_WarningTip.Show("失败",
                    "机架信息 为空",
                    TimeSpan.FromSeconds(2));
                return;
            }
            int[] forwdata = gageInfoService.ForwData.ToArray();
            int[] backwdata = gageInfoService.BackwData.ToArray();

            for (int i = 0; i < viewModel.Samples.Count(); i++)
            {
                var sampleCell = viewModel.Samples[i];
                if (sampleCell.Enable)
                {

                    int grid = sampleCell.Position / gageInfoService.PosOfGrid;
                    int range = viewModel.Range / gageInfoService.PosOfGrid;

                    int bg = grid - range;
                    int eg = grid + range;

                    if (bg < 0 || bg >= forwdata.Length || bg > backwdata.Length)
                    {
                        FLY.ControlLibrary.Window_WarningTip.Show("失败",
                            "位置出错",
                            TimeSpan.FromSeconds(2));
                        return;
                    }
                    if (eg < 0 || eg >= forwdata.Length || eg > backwdata.Length)
                    {
                        FLY.ControlLibrary.Window_WarningTip.Show("失败",
                            "位置出错",
                            TimeSpan.FromSeconds(2));
                        return;
                    }

                    int ad1 = Misc.MyMath.Avg(forwdata, bg, eg);
                    int ad2 = Misc.MyMath.Avg(backwdata, bg, eg);
                    if (!Misc.MyBase.ISVALIDATA(ad1) || !Misc.MyBase.ISVALIDATA(ad2))
                    {
                        FLY.ControlLibrary.Window_WarningTip.Show("失败",
                            "位置出错",
                            TimeSpan.FromSeconds(2));
                        return;
                    }
                    sampleCell.OrgAD = (ad1+ad2)/2;
                }
            }

            FLY.ControlLibrary.Window_Tip.Show("设置完成",
                null,
                TimeSpan.FromSeconds(2));
            

        }

        private void button_gageinfo_Click(object sender, RoutedEventArgs e)
        {
            if (container.IsRegistered<Page>("pgGageInfo"))
            {
                var p = container.Resolve<Page>("pgGageInfo");
                NavigationService.Navigate(p);
            }
            else
            {
                var p = container.Resolve<PgGageInfo>();
                //PgGageInfo p = new PgGageInfo();
                //container.BuildUp(p);
                NavigationService.Navigate(p);
            }
        }

    }

    public class GetSampleVm : INotifyPropertyChanged
    {
        public GetSampleVm()
        {



        }

        #region IGetSampleService 成员

        /// <summary>
        /// 参数：使能
        /// </summary>
        public bool Enable { get; set; }

        /// <summary>
        /// 参数：间隔
        /// </summary>
        public int Interval { get; set; }

        /// <summary>
        /// 采样计数
        /// </summary>
        public int Timer { get; set; }

        /// <summary>
        /// 参数：速度
        /// </summary>
        public UInt32 Velocity { get; set; }

        /// <summary>
        /// 参数：样品点范围
        /// </summary>
        public int Range { get; set; }


        /// <summary>
        /// 滤波窗口
        /// </summary>
        public int Window { get; set; }

        /// <summary>
        /// 样品
        /// </summary>
        public SampleCell[] Samples { get; set; }

        /// <summary>
        /// 查找公差
        /// </summary>
        public int Search { get; set; }

        /// <summary>
        /// 特征  相识度 0 正， 1 反
        /// </summary>
        public SampleFeature[] Features { get; set; }


        /// <summary>
        /// 状态：从flyad7 得到的。 用于绘制图
        /// </summary>
        public int PosOfGrid { get; set; } = 10;

        public event PropertyChangedEventHandler PropertyChanged;


        #endregion

        public bool IsChanged { get; set; }
    }
    public class GetSampleVmUt:INotifyPropertyChanged
    {
        public GetSampleVmUt()
        {

            for (int i = 0; i < Samples.Count(); i++)
            {
                SampleCell sampleCell = new SampleCell();
                Samples[i] = sampleCell;
            }
            Features[0] = new SampleFeature();
            Features[1] = new SampleFeature();


            Enable = true;
            Interval = 20;
            Samples[0].Enable = true;

            Features[0].Enable = true;

        }

        #region IGetSampleService 成员

        /// <summary>
        /// 参数：使能
        /// </summary>
        public bool Enable { get; set; }

        /// <summary>
        /// 参数：间隔
        /// </summary>
        public int Interval { get; set; }

        /// <summary>
        /// 采样计数
        /// </summary>
        public int Timer { get; set; }

        /// <summary>
        /// 参数：速度
        /// </summary>
        public UInt32 Velocity { get; set; }

        /// <summary>
        /// 参数：样品点范围
        /// </summary>
        public int Range { get; set; }


        /// <summary>
        /// 滤波窗口
        /// </summary>
        public int Window { get; set; }

        /// <summary>
        /// 样品
        /// </summary>
        public SampleCell[] Samples { get; set; } = new SampleCell[3];

        /// <summary>
        /// 查找公差
        /// </summary>
        public int Search { get; set; }

        /// <summary>
        /// 特征  相识度 0 正， 1 反
        /// </summary>
        public SampleFeature[] Features { get; set; } = new SampleFeature[2];


        /// <summary>
        /// 状态：从flyad7 得到的。 用于绘制图
        /// </summary>
        public int PosOfGrid { get; set; } = 10;

        public event PropertyChangedEventHandler PropertyChanged;


        #endregion

    }
    
   

    /// <summary>
    /// 列表转序号
    /// </summary>
    [ValueConversion(typeof(object), typeof(int))]
    public class Item2IndexConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {

            int result = -1;
            if (value != null)
            {

                var collectionViewSource = parameter as CollectionViewSource;
                if (collectionViewSource != null)
                {
                    var cv = (CollectionView)collectionViewSource.View;
                    //在 设计模式中， View为null, 所以下面必须判断
                    if (cv != null)
                    {
                        result = cv.IndexOf(value);
                    }
                }
            }
            return result >= 0 ? result : System.Windows.DependencyProperty.UnsetValue;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    /// <summary>
    /// 列表转序号
    /// </summary>
    [ValueConversion(typeof(object), typeof(string))]
    public class Item2DirectionConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value != null)
            {

                var collectionViewSource = parameter as CollectionViewSource;
                if (collectionViewSource != null)
                {
                    var cv = (CollectionView)collectionViewSource.View;
                    //在 设计模式中， View为null, 所以下面必须判断
                    if (cv != null)
                    {
                        switch (cv.IndexOf(value)) 
                        {
                            case 0:
                                return "正向";
                            case 1:
                                return "反向";

                        }
                    }
                }
            }
            return "";
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
