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 int Interval { 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, "Enable", this, "Enable");
            Misc.BindingOperations.SetBinding(this.getSampleService, "Interval", this, "Interval");
            Misc.BindingOperations.SetBinding(this.getSampleService, "Velocity", this, "Velocity");
            Misc.BindingOperations.SetBinding(this.getSampleService, "Range", this, "Range");
            Misc.BindingOperations.SetBinding(this.getSampleService, "Window", this, "Window");
            Misc.BindingOperations.SetBinding(this.getSampleService, "IsCheckByPercent", this, "IsCheckByPercent");
            Misc.BindingOperations.SetBinding(this.getSampleService, "ErrPercent", this, "ErrPercent");
            Misc.BindingOperations.SetBinding(this.getSampleService, "ErrValue", this, "ErrValue");
            Misc.BindingOperations.SetBinding(this.getSampleService, "Search", this, "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], "Enable", Samples[i], "Enable");
                Misc.BindingOperations.SetBinding(this.getSampleService.Samples[i], "JustForCheck", Samples[i], "JustForCheck");
                Misc.BindingOperations.SetBinding(this.getSampleService.Samples[i], "OrgAD", Samples[i], "OrgAD");
                Misc.BindingOperations.SetBinding(this.getSampleService.Samples[i], "Position", Samples[i], "Position");
            }

            for (int i = 0; i < Features.Count(); i++)
            {
                Features[i] = new SampleFeature();
                Misc.BindingOperations.SetBinding(this.getSampleService.Features[i], "Enable", Features[i], "Enable");
                Misc.BindingOperations.SetBinding(this.getSampleService.Features[i], "StartPos", Features[i], "StartPos");
                Misc.BindingOperations.SetBinding(this.getSampleService.Features[i], "EndPos", Features[i], "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[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();
        }
    }
}
