using FLY.Thick.Base.IService;
using GalaSoft.MvvmLight.Command;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Navigation;
using Unity;

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;

            viewModel = new GetSampleVm();
            viewModel.Init(getSampleService, gageInfoService, tempdatas);
            this.DataContext = viewModel;
            this.grid_initparam.DataContext = this.initParamService;
        }
        private void btnGageInfoClick(object sender, RoutedEventArgs e)
        {
            Page p = (container.IsRegistered<Page>("pgGageInfo")) ? container.Resolve<Page>("pgGageInfo") : container.Resolve<PgGageInfo>(); ;
            //container.BuildUp(p);
            NavigationService.Navigate(p);
        }

    }

    public class GetSampleVm : INotifyPropertyChanged
    {
        #region 参数

        /// <summary>
        /// 参数:使能
        /// </summary>
        public bool Enable { 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 bool IsCheckByPercent { get; set; }
        /// <summary>
        /// 异常%
        /// </summary>
        public double ErrPercent { get; set; }
        /// <summary>
        /// 异常值
        /// </summary>
        public int ErrValue { get; set; }
        /// <summary>
        /// 参数:样品点参数
        /// </summary>
        public SampleCell[] Samples { get; private set; }
        /// <summary>
        /// 参数:特征查找范围
        /// </summary>
        public int Search { get; set; }
        /// <summary>
        /// 参数:特征参数
        /// </summary>
        public SampleFeature[] Features { get; private set; }

        #endregion

        #region Command
        public RelayCommand ApplyCmd { get; }
        public RelayCommand GetOrgAdCmd { get; }
        public RelayCommand GetTempDataCmd { get; }
        #endregion

        public event PropertyChangedEventHandler PropertyChanged;

        IGetSampleService getSampleService;
        IGageInfoService gageInfoService;
        ItemsControl tempdatas;
        public GetSampleVm()
        {
            ApplyCmd = new RelayCommand(Apply);
            GetOrgAdCmd = new RelayCommand(GetOrgAd);
            GetTempDataCmd = new RelayCommand(GetTempData);
        }



        [InjectionMethod]
        public void Init(
            IGetSampleService getSampleService,
            IGageInfoService gageInfoService,
            ItemsControl tempdatas)
        {

            this.getSampleService = getSampleService;
            this.gageInfoService = gageInfoService;
            this.tempdatas = tempdatas;
            Misc.BindingOperations.SetBinding(this.getSampleService, nameof(this.getSampleService.Enable), this, nameof(Enable));
            Misc.BindingOperations.SetBinding(this.getSampleService, nameof(this.getSampleService.Velocity), this, nameof(Velocity));
            Misc.BindingOperations.SetBinding(this.getSampleService, nameof(this.getSampleService.Range), this, nameof(Range));
            Misc.BindingOperations.SetBinding(this.getSampleService, nameof(this.getSampleService.Window), this, nameof(Window));
            Misc.BindingOperations.SetBinding(this.getSampleService, nameof(this.getSampleService.IsCheckByPercent), this, nameof(IsCheckByPercent));
            Misc.BindingOperations.SetBinding(this.getSampleService, nameof(this.getSampleService.ErrPercent), this, nameof(ErrPercent));
            Misc.BindingOperations.SetBinding(this.getSampleService, nameof(this.getSampleService.ErrValue), this, nameof(ErrValue));
            Misc.BindingOperations.SetBinding(this.getSampleService, nameof(this.getSampleService.Search), this, nameof(Search));

            Samples = new SampleCell[this.getSampleService.Samples.Count()];
            Features = new SampleFeature[this.getSampleService.Features.Count()];
            for (int i = 0; i < Samples.Count(); i++)
            {
                Samples[i] = new SampleCell();
                Misc.BindingOperations.SetBinding(this.getSampleService.Samples[i], nameof(SampleCell.Enable), Samples[i], nameof(SampleCell.Enable));
                Misc.BindingOperations.SetBinding(this.getSampleService.Samples[i], nameof(SampleCell.JustForCheck), Samples[i], nameof(SampleCell.JustForCheck));
                Misc.BindingOperations.SetBinding(this.getSampleService.Samples[i], nameof(SampleCell.OrgAD), Samples[i], nameof(SampleCell.OrgAD));
                Misc.BindingOperations.SetBinding(this.getSampleService.Samples[i], nameof(SampleCell.Position), Samples[i], nameof(SampleCell.Position));
            }

            for (int i = 0; i < Features.Count(); i++)
            {
                Features[i] = new SampleFeature();
                Misc.BindingOperations.SetBinding(this.getSampleService.Features[i], nameof(SampleFeature.Enable), Features[i], nameof(SampleFeature.Enable));
                Misc.BindingOperations.SetBinding(this.getSampleService.Features[i], nameof(SampleFeature.StartPos), Features[i], nameof(SampleFeature.StartPos));
                Misc.BindingOperations.SetBinding(this.getSampleService.Features[i], nameof(SampleFeature.EndPos), Features[i], nameof(SampleFeature.EndPos));
            }

        }


        private void GetOrgAd()
        {
            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 < Samples.Count(); i++)
            {
                var sampleCell = Samples[i];
                if (sampleCell.Enable)
                {

                    int grid = sampleCell.Position / gageInfoService.PosOfGrid;
                    int range = 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 Apply()
        {
            if (!WdPassword.Authorize("GetSample"))
                return;



            this.getSampleService.Enable = this.Enable;
            this.getSampleService.Range = this.Range;
            this.getSampleService.Velocity = this.Velocity;
            this.getSampleService.Window = this.Window;
            this.getSampleService.IsCheckByPercent = this.IsCheckByPercent;
            this.getSampleService.ErrPercent = this.ErrPercent;
            this.getSampleService.ErrValue = this.ErrValue;

            for (int i = 0; i < Samples.Count(); i++)
            {
                var sample_src = this.Samples[i];
                var sample_desp = this.getSampleService.Samples[i];

                sample_desp.Enable = sample_src.Enable;
                sample_desp.JustForCheck = sample_src.JustForCheck;
                sample_desp.OrgAD = sample_src.OrgAD;
                sample_desp.Position = sample_src.Position;
            }
            this.getSampleService.Search = this.Search;
            for (int i = 0; i < Features.Count(); i++)
            {
                var feature_src = this.Features[i];
                var feature_desp = this.getSampleService.Features[i];


                feature_desp.Enable = feature_src.Enable;
                feature_desp.StartPos = feature_src.StartPos;
                feature_desp.EndPos = feature_src.EndPos;
            }

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

        private void GetTempData()
        {
            getSampleService.GetTempFilterDatas((asyncContext, retData) =>
            {
                var ll = retData as List<List<TempFilterData>>;
                tempdatas.ItemsSource = ll;
                FLY.ControlLibrary.Window_Tip.Show("加载完成",
                    $"共加载{ll.Count()}列数据",
                    TimeSpan.FromSeconds(2));
            }, null);
        }
    }
    public class GetSampleVmUt : INotifyPropertyChanged
    {
        public GetSampleVmUt()
        {
            Samples = new SampleCell[3];
            for (int i = 0; i < Samples.Count(); i++)
            {
                SampleCell sampleCell = new SampleCell();
                Samples[i] = sampleCell;
            }
            Features = new SampleFeature[2];
            Features[0] = new SampleFeature();
            Features[1] = new SampleFeature();


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

            Features[0].Enable = true;

        }

        #region IGetSampleService 成员

        /// <summary>
        /// 参数:使能
        /// </summary>
        public bool Enable { 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 bool IsCheckByPercent { get; set; }
        /// <summary>
        /// 异常%
        /// </summary>
        public double ErrPercent { get; set; }
        /// <summary>
        /// 异常值
        /// </summary>
        public int ErrValue { get; set; }
        /// <summary>
        /// 参数:样品点参数
        /// </summary>
        public SampleCell[] Samples { get; }
        /// <summary>
        /// 参数:特征查找范围
        /// </summary>
        public int Search { get; set; }
        /// <summary>
        /// 参数:特征参数
        /// </summary>
        public SampleFeature[] Features { get; }

        /// <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();
        }
    }
}