using MainShell.Common;
using MainShell.EventArgsFolder;
using MainShell.Hardware;
using MainShell.HeightMeasure.Model;
using MainShell.HeightMeasure.Service;
using MainShell.Log;
using MainShell.Parameter;
using MaxwellControl.Tools;
using MaxwellFramework.Core.Interfaces;
using MwFramework.Controls.Components;
using MwFramework.Controls.UIControl;
using MwFramework.Device;
using MwFramework.ManagerService;
using MXJM.Parameter.Maintance;
using Stylet;
using StyletIoC;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using MessageBox = MaxwellControl.Controls.MessageBox;

namespace MainShell.HeightMeasure.ViewModel
{
    public class HeightViewModel : Screen, IPage, IHandle<NeedleCalibrationHeightTestEventArgs>, IHandle<DiastimeterSampleChangedEventArgs>
    {
        public string Name { get; set; } = "HeightMaint";

        private ParameterHelper _parameterHelper = new ParameterHelper();
        public ParameterHelper ParameterHelper
        {
            get
            {
                return _parameterHelper;
            }
            set
            {
                _parameterHelper = value;
                OnPropertyChanged(nameof(ParameterHelper));
            }
        }

        //private bool _isHaveDia;
        ///// <summary>
        ///// 是否有激光测距仪
        ///// </summary>
        //public bool IsHaveDia
        //{
        //    get
        //    {
        //        return _isHaveDia;
        //    }
        //    set
        //    {
        //        _isHaveDia = value;
        //        OnPropertyChanged(nameof(IsHaveDia));
        //    }
        //}

        private IHeightMeasure _heightMeasureManager;
        public IHeightMeasure HeightMeasureManager
        {
            get
            {
                return _heightMeasureManager;
            }
            set
            {
                _heightMeasureManager = value;
                OnPropertyChanged(nameof(Parameter));
            }
        }

        private HeightBaseSetting _heightTestSetting = new HeightBaseSetting();
        public HeightBaseSetting HeightTestSetting
        {
            get
            {
                return _heightTestSetting;
            }
            set
            {
                _heightTestSetting = value;
                OnPropertyChanged(nameof(Parameter));
            }
        }

        private HeightBaseItem _heightBaseItem = new HeightBaseItem();
        public HeightBaseItem HeightBaseItem
        {
            get
            {
                return _heightBaseItem;
            }
            set
            {
                _heightBaseItem = value;
                OnPropertyChanged(nameof(HeightBaseItem));
            }
        }

        //private CapHeightItem _capHeightItem = new CapHeightItem();
        //public CapHeightItem CapHeightItem
        //{
        //    get
        //    {
        //        return _capHeightItem;
        //    }
        //    set
        //    {
        //        _capHeightItem = value;
        //        OnPropertyChanged(nameof(CapHeightItem));
        //    }
        //}

        private DiaHeightItem _diaHeightItem = new DiaHeightItem();
        public DiaHeightItem DiaHeightItem
        {
            get
            {
                return _diaHeightItem;
            }
            set
            {
                _diaHeightItem = value;
                OnPropertyChanged(nameof(DiaHeightItem));
            }
        }

        private TeachPoint _selectedGlassPoint = null;
        public TeachPoint SelectedGlassPoint
        {
            get
            {
                return _selectedGlassPoint;
            }
            set
            {
                _selectedGlassPoint = value;
                OnPropertyChanged(nameof(SelectedGlassPoint));
            }
        }

        private TeachPoint _selectedWaferPoint = null;
        public TeachPoint SelectedWaferPoint
        {
            get
            {
                return _selectedWaferPoint;
            }
            set
            {
                _selectedWaferPoint = value;
                OnPropertyChanged(nameof(SelectedWaferPoint));
            }
        }

        //private GlassCraftParItem _glassCraftParItem;
        //public GlassCraftParItem GlassCraftParItem
        //{
        //    get { return _glassCraftParItem; }
        //    set { _glassCraftParItem = value; OnPropertyChanged(nameof(GlassCraftParItem)); }
        //}


        //private GlassRecipeContentItem _glassRecipeContentItem;
        //public GlassRecipeContentItem GlassRecipeContentItem
        //{
        //    get { return _glassRecipeContentItem; }
        //    set { if (_glassRecipeContentItem != value) { _glassRecipeContentItem = value; OnPropertyChanged(nameof(GlassRecipeContentItem)); } }
        //}

        private HardwareManager _hardware;
        private readonly GlobalParameterContext _gp;
        private readonly HeightMeasureMotionService _heightMeasureMotionService;
        private readonly IEventAggregator _eventAggregator;
        private readonly DiastimeterPollingService _diastimeterPollingService;
        private double _currentDiastimeterDistance;
        private string _diastimeterStatus;
        private bool _isDiastimeterPolling;

        public HeightViewModel(GlobalParameterContext gp, HardwareManager hardware, IParameterManager parameterManager, IHeightMeasure heightMeasure, HeightMeasureMotionService heightMeasureMotionService, IEventAggregator eventAggregator, DiastimeterPollingService diastimeterPollingService)
        {
            _gp = gp;
            _hardware = hardware;
            _heightMeasureMotionService = heightMeasureMotionService ?? throw new ArgumentNullException(nameof(heightMeasureMotionService));
            _eventAggregator = eventAggregator ?? throw new ArgumentNullException(nameof(eventAggregator));
            _diastimeterPollingService = diastimeterPollingService ?? throw new ArgumentNullException(nameof(diastimeterPollingService));
            var _paramlist = parameterManager as IParamList;
            HeightTestSetting = _paramlist.GetParameter<HeightBaseSetting>();
            HeightBaseItem = HeightTestSetting.HeightBaseItem;
            DiaHeightItem = HeightTestSetting.DiaHeightItem;
            HeightMeasureManager = heightMeasure;
            DiastimeterStatus = "未启动";
        }

        public double CurrentDiastimeterDistance
        {
            get
            {
                return _currentDiastimeterDistance;
            }
            set
            {
                _currentDiastimeterDistance = value;
                OnPropertyChanged(nameof(CurrentDiastimeterDistance));
            }
        }

        public string DiastimeterStatus
        {
            get
            {
                return _diastimeterStatus;
            }
            set
            {
                _diastimeterStatus = value;
                OnPropertyChanged(nameof(DiastimeterStatus));
            }
        }

        public bool IsDiastimeterPolling
        {
            get
            {
                return _isDiastimeterPolling;
            }
            set
            {
                _isDiastimeterPolling = value;
                OnPropertyChanged(nameof(IsDiastimeterPolling));
            }
        }

        protected override void OnInitialActivate()
        {
            base.OnInitialActivate();
            _eventAggregator.Subscribe(this);
        }

        protected override void OnDeactivate()
        {
            _eventAggregator.Unsubscribe(this);
            _diastimeterPollingService.Stop();
            IsDiastimeterPolling = false;
            base.OnDeactivate();
        }

        public void StartDiastimeterPolling()
        {
            try
            {
                _diastimeterPollingService.Start();
                IsDiastimeterPolling = true;
                DiastimeterStatus = "采集中";
            }
            catch (Exception ex)
            {
                DiastimeterStatus = $"启动失败：{ex.Message}";
                LogManager.LogSysError(ex, true);
            }
        }

        public void StopDiastimeterPolling()
        {
            _diastimeterPollingService.Stop();
            IsDiastimeterPolling = false;
            DiastimeterStatus = "已停止";
        }
        
        #region 第一步
        public void btnMoveCZAndStagePlatform()
        {
            if (MessageBox.Show("是否移动到当前位置", null, "确认", MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.Cancel) == MessageBoxResult.OK)
            {
                CommonUti.RunOnUi(() =>
                {
                    _heightMeasureMotionService.MoveCalibrationAndStagePlatformHeights(HeightBaseItem.CZCalibrationHeight, HeightBaseItem.StageDatumHeight);
                });
            }
        }

        #endregion

        #region 第二步
        public void btnReadAvoidancePosition()
        {
            if (MessageBox.Show("是否读取当前位置", null, "确认", MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.Cancel) == MessageBoxResult.OK)
            {
                CommonUti.RunOnUi(() =>
                {
                    HeightBaseItem.AvoidancePositionX21 = _hardware.Axis_X2.State.ActualPos;
                    HeightBaseItem.AvoidancePositionY21 = _hardware.Axis_Y2.State.ActualPos;
                });
            }
        }

        public void btnMoveAvoidancePosition()
        {
            if (MessageBox.Show("是否移动到当前位置", null, "确认", MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.Cancel) == MessageBoxResult.OK)
            {
                CommonUti.RunOnUi(() =>
                {
                    _heightMeasureMotionService.MoveWsAvoidance(HeightBaseItem.AvoidancePositionX21, HeightBaseItem.AvoidancePositionY21);
                });  
            }
        }

        public void btnReadLaserToKnifePosition()
        {
            if (MessageBox.Show("是否读取当前位置", null, "确认", MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.Cancel) == MessageBoxResult.OK)
            {
                CommonUti.RunOnUi(() =>
                {
                    DiaHeightItem.CaliZHeightPositionX = _hardware.Axis_X1.State.ActualPos;
                    DiaHeightItem.CaliZHeightPositionY = _hardware.Axis_Y1.State.ActualPos;
                    DiaHeightItem.CaliZHeightPositionZ = _hardware.Axis_Z1.State.ActualPos;
                });
            }
        }

        public void btnMoveLaserToKnifePosition()
        {
            if (MessageBox.Show("是否移动到当前位置", null, "确认", MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.Cancel) == MessageBoxResult.OK)
            {
                CommonUti.RunOnUi(() =>
                {
                    _heightMeasureMotionService.MovePhsAndNeedle(DiaHeightItem.CaliZHeightPositionX, DiaHeightItem.CaliZHeightPositionY, DiaHeightItem.CaliZHeightPositionZ);
                });
            }
        }

        public void btnHeightMeasure()
        {
            CommonUti.RunOnUi(() =>
            {
                DiaHeightItem.CaliZHeightLaserReading = HeightMeasureManager.GetDistance();
                Thread.Sleep(500);

                //1107-暂时注释：目前没有_equipmentParaSysSetting对象

                //SafeAxisMotion.MoveAbs(_hardware.Axis_Z1, _equipmentParaSysSetting.SafeParaSysItem.Z1GeneralSafeHeight, false, true);
            });
        }

        #endregion

        #region 第三步
       
        public void BtnGlassAdd()
        {
            TeachPoint teachPoint = new TeachPoint();
            teachPoint.Id = HeightBaseItem.GlassHeightMeasureList.Count + 1;
            teachPoint.X = 0;
            teachPoint.Y = 0;
            HeightBaseItem.GlassHeightMeasureList.Add(teachPoint);
        }

        public void BtnGlassDelete()
        {
            if (SelectedGlassPoint == null)
            {
                MessageBox.Show("请先选中要设置的点");
                return;
            }
            if (MessageBox.Show("是否删除", null, "确认", MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.Cancel) == MessageBoxResult.OK)
            {
                HeightBaseItem.GlassHeightMeasureList.Remove(SelectedGlassPoint);
            }
        }

        public void btnSetPositionGlass()
        {
            if (SelectedGlassPoint == null)
            {
                MessageBox.Show("请先选中要设置的点");
                return;
            }
            if (MessageBox.Show("是否使用当前位置", null, "确认", MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.Cancel) == MessageBoxResult.OK)
            {
                CommonUti.RunOnUi(() =>
                {
                    SelectedGlassPoint.X = _hardware.Axis_X1.State.ActualPos;
                    SelectedGlassPoint.Y = _hardware.Axis_Y1.State.ActualPos;
                    SelectedGlassPoint.Z = _hardware.Axis_Z1.State.ActualPos;
                    SelectedGlassPoint.LaserZ = 0.0;
                    SelectedGlassPoint.Height = 0;
                });
            }
        }

        public void btnMovePositionGlass()
        {
            if (SelectedGlassPoint == null)
            {
                MessageBox.Show("请先选中要设置的点");
                return;
            }
            if (MessageBox.Show("是否移动到选中点", null, "确认", MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.Cancel) == MessageBoxResult.OK)
            {
                CommonUti.RunOnUi(() =>
                {
                    _heightMeasureMotionService.MoveGlassMeasurePoint(SelectedGlassPoint);
                });
            }
        }

        public void btnTestGlassHeightGlass()
        {
            if (SelectedGlassPoint == null)
            {
                MessageBox.Show("请先选中要设置的点");
                return;
            }
            if (MessageBox.Show("是否测量", null, "确认", MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.Cancel) == MessageBoxResult.OK)
            {
                CommonUti.RunOnUi(() =>
                {
                    var Distance = HeightMeasureManager.GetDistance();
                    SelectedGlassPoint.LaserZ = Distance + SelectedGlassPoint.Z;
                    SelectedGlassPoint.Height = Distance;
                });
            }
        }


        /////////Wafer/////////////
        
        public void BtnWaferAdd()
        {
            TeachPoint teachPoint = new TeachPoint();
            teachPoint.Id = HeightBaseItem.WaferHeightMeasureList.Count + 1;
            teachPoint.X = 0;
            teachPoint.Y = 0;
            HeightBaseItem.WaferHeightMeasureList.Add(teachPoint);
        }

        public void BtnWaferDelete()
        {
            if (SelectedWaferPoint == null)
            {
                MessageBox.Show("请先选中要设置的点");
                return;
            }
            if (MessageBox.Show("是否删除", null, "确认", MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.Cancel) == MessageBoxResult.OK)
            {
                HeightBaseItem.WaferHeightMeasureList.Remove(SelectedWaferPoint);
            }
        }

        public void btnSetPositionWafer()
        {
            if (SelectedWaferPoint == null)
            {
                MessageBox.Show("请先选中要设置的点");
                return;
            }
            if (MessageBox.Show("是否使用当前位置", null, "确认", MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.Cancel) == MessageBoxResult.OK)
            {
                CommonUti.RunOnUi(() =>
                {
                    SelectedWaferPoint.X = _hardware.Axis_X2.State.ActualPos;
                    SelectedWaferPoint.Y = _hardware.Axis_Y2.State.ActualPos;
                    SelectedWaferPoint.Z = _hardware.Axis_Z1.State.ActualPos;
                    SelectedWaferPoint.LaserZ = 0.0;
                    SelectedWaferPoint.Height = 0.0;
                });
            }
        }

        public void btnMovePositionWafer()
        {
            if (SelectedWaferPoint == null)
            {
                MessageBox.Show("请先选中要设置的点");
                return;
            }
            if (MessageBox.Show("是否移动到选中点", null, "确认", MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.Cancel) == MessageBoxResult.OK)
            {
                CommonUti.RunOnUi(() =>
                {
                    _heightMeasureMotionService.MoveWaferMeasurePoint(SelectedWaferPoint);
                });
            }
        }

        public void btnTestWaferHeight()
        {
            if (SelectedWaferPoint == null)
            {
                MessageBox.Show("请先选中要设置的点");
                return;
            }
            if (MessageBox.Show("是否测量", null, "确认", MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.Cancel) == MessageBoxResult.OK)
            {
                CommonUti.RunOnUi(() =>
                {
                    var Distance = HeightMeasureManager.GetDistance();
                    SelectedWaferPoint.LaserZ = Distance + SelectedWaferPoint.Z;
                    SelectedWaferPoint.Height = Distance;
                });
            }
        }

        public void btnMoveGantry1()
        {
            if (MessageBox.Show("是否移动到该位置", null, "确认", MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.Cancel) == MessageBoxResult.OK)
            {
                CommonUti.RunOnUi(() =>
                {
                    _heightMeasureMotionService.MoveWaferMeasurePose(HeightBaseItem.MeasureWaferHeightX11, HeightBaseItem.MeasureWaferHeightY11);
                });
            }
        }
        #endregion

        #region 第四步
        public void BtnCalculateHeight()
        {
            CommonUti.RunOnUi(() =>
            {
                HeightMeasureManager.CalculateHeight();
            });
        }


        public void btnSave()
        {
            var a=_gp.HeightBaseSetting.HeightBaseItem;
            if (MessageBox.Show("是否保存", null, "确认保存", MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.Cancel) == MessageBoxResult.OK)
            {
                CommonUti.RunOnUi(() =>
                {
                    HeightMeasureManager.HeightBaseItem = HeightBaseItem;
                    //HeightMeasureManager.CapHeightItem = CapHeightItem;
                    HeightMeasureManager.DiaHeightItem = DiaHeightItem;
                    HeightTestSetting.Write();
                    SaveParaLog();
                    ParameterHelper.RaiseValueAccept();
                });
            }
        }

        public void SaveParaLog()
        {
            LogWatchValueManager.Save(HeightBaseItem, "HeightTestPara_测高参数");
            LogWatchValueManager.Save(DiaHeightItem, "HeightTestPara_测高参数");
        }

        #endregion


        public void Handle(NeedleCalibrationHeightTestEventArgs message)
        {
            throw new NotImplementedException();
        }

        public void Handle(DiastimeterSampleChangedEventArgs message)
        {
            if (message == null)
            {
                return;
            }

            if (message.IsValid)
            {
                CurrentDiastimeterDistance = message.Distance;
                DiastimeterStatus = $"采样时间：{message.SampleTime:HH:mm:ss.fff}";
                return;
            }

            DiastimeterStatus = string.IsNullOrWhiteSpace(message.Message) ? "采样失败" : message.Message;
        }
    }
}
