using MainShell.AlgorithmCalib.Model;
using MainShell.AlgorithmCalib.Service;
using MainShell.Common;
using MainShell.Common.Display.ViewModel;
using MainShell.Filewritable;
using MainShell.Hardware;
using Maxwell.SemiFramework.WaferCalibration.ViewModel;
using MaxwellFramework.Core.Interfaces;
using MwFramework.Controls.SystemCalib;
using MwFramework.Controls.UIControl;
using MwFramework.ManagerService;
using Stylet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using CameraAxisViewModel = MainShell.Common.Display.ViewModel.CameraAxisViewModel;

namespace MainShell.AlgorithmCalib.ViewModel
{
    public class CameraFusionPadCalibViewModel:Screen,IPage
    {
        private bool _stopMotion = false;
        public string Name { get; set; } = "CameraFusionPadCalib";

        public string CameraName { get; set; }

        private readonly FusionCalibMotionService _fusionCalibMotionService;

        private HardwareManager _hardware;
        private string _fileSaveDir = Paths.CalibSettingPath;
        public string FileSaveDir
        {
            get { return _fileSaveDir; }
            set { SetAndNotify(ref _fileSaveDir, value); }
        }
        private CameraAxisViewModel _cameraAxisViewModelSevice;
        public CameraAxisViewModel CameraAxisViewModelSevice
        {
            get { return _cameraAxisViewModelSevice; }
            set
            {
                _cameraAxisViewModelSevice = value;
                OnPropertyChanged(nameof(CameraAxisViewModelSevice));
            }
        }

        private FusionCalibParItem _fusionCalibParItem = new FusionCalibParItem();
        public FusionCalibParItem FusionCalibParItem
        {
            get { return _fusionCalibParItem; }
            set
            {
                _fusionCalibParItem = value;
                OnPropertyChanged(nameof(FusionCalibParItem));
            }
        }

        private FusionCalibParItem _inputParam;
        public FusionCalibParItem InputParam
        {
            get { return _inputParam; }
            set { SetAndNotify(ref _inputParam, value); }
        }

        private FusionCalibParItem _resultParam;
        public FusionCalibParItem ResultParam
        {
            get { return _resultParam; }
            set { SetAndNotify(ref _resultParam, value); }
        }

        //private CameraFusionPadCalibViewModel _service;
        //public CameraFusionPadCalibViewModel Service
        //{
        //    get { return _service; }
        //    set
        //    {
        //        _service = value;
        //        NotifyOfPropertyChange();
        //    }
        //}

        private bool _isInitialized=false;

        public CameraFusionPadCalibViewModel()
        {

        }

        public CameraFusionPadCalibViewModel(HardwareManager hardware, FusionCalibMotionService fusionCalibMotionService)
        {
            _hardware = hardware;
            _fusionCalibMotionService = fusionCalibMotionService ?? throw new ArgumentNullException(nameof(fusionCalibMotionService));

        }

        /// <summary>
        /// 弹窗专用工厂方法（新增）：传入标定参数
        /// </summary>
        public static CameraFusionPadCalibViewModel Create(
            string cameraName, string fileSaveName, List<HardwareDevice> device, FusionCalibParItem param, HardwareManager hardware, FusionCalibMotionService fusionCalibMotionService)
        {
            var vm = new CameraFusionPadCalibViewModel(hardware,fusionCalibMotionService);
            vm.InputParam = param;
            vm.ResultParam = param;
            vm.Initialize(cameraName, fileSaveName, device, true);
            return vm;
        }

        public void viewLoad()
        {
            base.OnViewLoaded();

            if (_isInitialized)
            {
                return;
            }

            if (_hardware != null)
            {
                _cameraAxisViewModelSevice = new CameraAxisViewModel();
                _cameraAxisViewModelSevice.CameraAxisDevices.HardwareDeviceList = _hardware.CameraAxisManager.TopPositionCameraAxisDevices;
                NotifyOfPropertyChange(nameof(CameraAxisViewModelSevice));
            }

            //RebuildModuleViewModels();
            _isInitialized = true;
        }

        public void viewUnLoad()
        {
            ResultParam = FusionCalibParItem;
        }
        private void Initialize(string cameraName, string fileSaveName, List<HardwareDevice> device, bool isSignUp)
        {
            //if (isSignUp)
            //{
            //    IoC.Get<IEventAggregator>().Unsubscribe(this);
            //    IoC.Get<IEventAggregator>().Subscribe(this);
            //}
            //CameraName = cameraName;
            Name = cameraName;
            //FileSaveName = fileSaveName;
            var paramList = IoC.Get<IParameterManager>() as IParamList;

            //Service = new CameraFusionPadCalibViewModel();
            FusionCalibParItem = InputParam;
            //string pathSavePath = Path.Combine(FileSaveDir, FileSaveName + ".xml");
            //Service.SetParaSavePath(pathSavePath);
            //Service.IsShowSolidLine = true;
            //Service.ShapeThickness = 1;
            //Service.DrawInConcurrency = false;
            //Service.IsAxisControlLDBVisible = Visibility.Visible;
        }

        public void btnMovePhsCalibPosPosition()
        {
            System.Threading.Tasks.Task.Factory.StartNew(() =>
            {
                try
                {
                    _fusionCalibMotionService.SafeMove(_hardware.Axis_Y1, FusionCalibParItem.MoveAxisPos);
                    _fusionCalibMotionService.MovePhsAvoidance(FusionCalibParItem.ApproachXPos, FusionCalibParItem.ApproachYPos);
                }
                catch (Exception ex)
                {

                }
            });
        }

        public void btnApproachPhsCalibPosition()
        {
            System.Threading.Tasks.Task.Factory.StartNew(() =>
            {
                try
                {

                    //if (FindPointWSCircle())
                    //{
                        FusionCalibParItem.ApproachXPos = _hardware.Axis_X1.State.ActualPos;
                        FusionCalibParItem.ApproachYPos = _hardware.Axis_Y2.State.ActualPos;
                        //CameraWaferFusionCalibrationItem.CenterX = _gs.Axis_X21.State.ActualPos;
                        //CameraWaferFusionCalibrationItem.CenterY = _gs.Axis_Y21.State.ActualPos;
                        MessageBox.Show($"对齐值，X1:{FusionCalibParItem.ApproachXPos},Y2:{FusionCalibParItem.ApproachYPos}");
                    //}
                    //else
                    //{
                    //    MessageBox.Show("对齐失败！");
                    //}
                }
                catch (Exception ex)
                {

                }
            });
        }

        public void btnCalculateCameraPosition()
        {
            try
            {
                //起点覆盖标定范围，起点往负方向6mm
                int offset = -10;
                double Y2MinPos = 0;
                _hardware.Axis_Y2.GetSoftMel(ref Y2MinPos);
                var delx = FusionCalibParItem.ApproachYPos - Y2MinPos + offset;
                FusionCalibParItem.CameraAxisPos = FusionCalibParItem.MoveAxisPos - delx;
            }
            catch (Exception ex)
            {

            }
        }

        public void btnSetCameraPosition()
        {

            var result = MwMessageBox.Show("是否使用当前位置?", "确认", MessageBoxButton.YesNo, MessageBoxImage.Information);
            if (result == MessageBoxResult.Yes)
            {
                try
                {
                    FusionCalibParItem.CameraAxisPos = _hardware.Axis_Y1.State.ActualPos;
                }
                catch (Exception ex)
                {

                }
            }
        }

        public void btnMoveCameraPosition()
        {
            var result = MwMessageBox.Show("是否移动到该点?", "确认", MessageBoxButton.YesNo, MessageBoxImage.Information);
            if (result == MessageBoxResult.Yes)
            {
                System.Threading.Tasks.Task.Factory.StartNew(() =>
                {
                    try
                    {
                        _fusionCalibMotionService.SafeMove(_hardware.Axis_Y1, FusionCalibParItem.CameraAxisPos);
                    }
                    catch (Exception ex)
                    {

                    }
                });

            }
        }

        public void btnCalculatePhsPosition()
        {
            try
            {
                //起点覆盖标定范围，起点往负方向6mm
                int offset = -10;
                double Y2MinPos = 0;
                _hardware.Axis_Y2.GetSoftMel(ref Y2MinPos);

                var delx = FusionCalibParItem.ApproachXPos - Y2MinPos + offset;
                FusionCalibParItem.CameraAxisPos = FusionCalibParItem.MoveAxisPos - delx;

                double y11Offset = FusionCalibParItem.CameraAxisPos - FusionCalibParItem.MoveAxisPos;
                FusionCalibParItem.StartX = FusionCalibParItem.ApproachXPos;
                FusionCalibParItem.StartY = FusionCalibParItem.ApproachYPos + y11Offset;
            }
            catch (Exception ex)
            {

            }
        }

        public void btnSetStageStartPosition()
        {
            var result = MwMessageBox.Show("是否使用当前位置?", "确认", MessageBoxButton.YesNo, MessageBoxImage.Information);
            if (result == MessageBoxResult.Yes)
            {
                System.Threading.Tasks.Task.Factory.StartNew(() =>
                {
                    try
                    {
                        FusionCalibParItem.StartX = _hardware.Axis_X1.State.ActualPos;
                        FusionCalibParItem.StartY = _hardware.Axis_Y2.State.ActualPos;
                    }
                    catch (Exception ex)
                    {

                    }
                });

            }
        }

        public void btnMoveStageStartPosition()
        {
            var result = MwMessageBox.Show("是否移动到该点?", "确认", MessageBoxButton.YesNo, MessageBoxImage.Information);
            if (result == MessageBoxResult.Yes)
            {
                try
                {
                    _fusionCalibMotionService.MovePhsAvoidance(FusionCalibParItem.StartX, FusionCalibParItem.StartY);
                }
                catch (Exception ex)
                {

                }
            }
        }

        public void btnMoveToCenter()
        {
            System.Threading.Tasks.Task.Factory.StartNew(() =>
            {
                try
                {
                    //if (ApproachPointWS(1))
                    //{
                    //    CameraWaferFusionCalibrationItem.WaferStartVerifyX = _gs.Axis_X21.State.ActualPos;
                    //    CameraWaferFusionCalibrationItem.WaferStartVerifyY = _gs.Axis_Y21.State.ActualPos;
                    //    MwMessageBox.Show("中心对齐完成");
                    //}
                    //else
                    //{
                    //    MwMessageBox.Show("逼近失败！");
                    //}
                }
                catch (Exception ex)
                {

                }
            });
        }

        public void btnStart()
        {

        }

        public void btnStop()
        {

        }
    }
}
