using MainShell.AlgorithmCalib.Model;
using MainShell.AlgorithmCalib.Service;
using MainShell.Common;
using MainShell.Common.Display.ViewModel;
using MainShell.Filewritable;
using MainShell.Hardware;
using MainShell.Motion;
using Maxwell.SemiFramework.DefaultConfig.Vision;
using Maxwell.SemiFramework.WaferCalibration.View;
using Maxwell.SemiFramework.WaferCalibration.ViewModel;
using MaxwellControl.Tools;
using MaxwellFramework.Core.Interfaces;
using MwFramework.Controls.ControlCanvas.DrawingControl;
using MwFramework.Controls.ControlCanvas.Model;
using MwFramework.Device;
using MwFramework.ManagerService;
using SemiconductorVisionAlgorithm.SemiParams;
using SemiconductorVisionAlgorithm.SemiWaferRecip;
using Stylet;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using CameraAxisViewModel = MainShell.Common.Display.ViewModel.CameraAxisViewModel;
using Point = SemiconductorVisionAlgorithm.SemiParams.Point;

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

        public string CameraName { get; set; } 

        private readonly FusionCalibMotionService _fusionCalibMotionService;

        private HardwareManager _hardware;

        private DelegateBase _motion = new DelegateBase();
        public DelegateBase Motion
        {
            get
            {
                return _motion;
            }
            set
            {
                _motion = value;
                OnPropertyChanged(nameof(Motion));
            }
        }

        private CameraAxisViewModel _cameraAxisViewModelSevice = new CameraAxisViewModel();
        public CameraAxisViewModel CameraAxisViewModelSevice
        {
            get { return _cameraAxisViewModelSevice; }
            set
            {
                _cameraAxisViewModelSevice = value;
                OnPropertyChanged(nameof(CameraAxisViewModelSevice));
            }
        }

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

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

        public CameraFusionCalibViewModel()
        {

        }

        private bool _isInitialized = false;

        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()
        {

        }

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

        }

        public static CameraFusionCalibViewModel Create(string name,string cameraName, List<HardwareDevice> device, HardwareManager hardware, FusionCalibMotionService motion)
        {
            var vm = new CameraFusionCalibViewModel(hardware,motion);
            vm.Initialize(name, device);
            return vm;
        }

        private void Initialize(string cameraName, List<HardwareDevice> device)
        {
            CameraName = cameraName;
            Name = cameraName;
            //Hardware = device;
            //FileSaveDir = Path.Combine(Paths.CalibSettingPath, "bottomCamera");
            var paramList = IoC.Get<IParameterManager>() as IParamList;
            
            Service = new CameraFusionCalibViewModel();
            //Service.IsShowSolidLine = true;
            //Service.ShapeThickness = 1;
            //Service.DrawInConcurrency = false;
            //Service.IsAxisControlLDBVisible = Visibility.Visible;
        }


        public void btnMoveWSCalibPosPosition()
        {
            System.Threading.Tasks.Task.Factory.StartNew(() =>
            {
                try
                {
                    _fusionCalibMotionService.SafeMove(_hardware.Axis_X1, WsFusionCalibParItem.MoveAxisPos);
                    _fusionCalibMotionService.MoveWsAvoidance(WsFusionCalibParItem.ApproachXPos, WsFusionCalibParItem.ApproachYPos);
                }
                catch (Exception ex)
                {

                }
            });
        }

        public void btnApproachWSCalibPosition()
        {
            System.Threading.Tasks.Task.Factory.StartNew(() =>
            {
                try
                {
                    
                    //if (FindPointWSCircle())
                    {
                        WsFusionCalibParItem.ApproachXPos = _hardware.Axis_X2.State.ActualPos;
                        WsFusionCalibParItem.ApproachYPos = _hardware.Axis_Y1.State.ActualPos;
                        MessageBox.Show($"对齐值，X2:{WsFusionCalibParItem.ApproachXPos},Y1:{WsFusionCalibParItem.ApproachYPos}");
                    }
                    //else
                    //{
                    //    MessageBox.Show("对齐失败！");
                    //}
                }
                catch (Exception ex)
                {

                }
            });
        }

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

            }
        }

        public void btnSetCameraPosition()
        {

            var result = MwMessageBox.Show("是否使用当前位置?", "确认", MessageBoxButton.YesNo, MessageBoxImage.Information);
            if (result == MessageBoxResult.Yes)
            {
                try
                {
                    WsFusionCalibParItem.CameraAxisPos = _hardware.Axis_X1.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_X1, WsFusionCalibParItem.CameraAxisPos);
                    }
                    catch (Exception ex)
                    {

                    }
                });

            }
        }

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

                var delx = WsFusionCalibParItem.ApproachXPos - X2MinPos + offset;
                WsFusionCalibParItem.CameraAxisPos = WsFusionCalibParItem.MoveAxisPos - delx;

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

            }
        }

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

                    }
                });

            }
        }

        public void btnMoveWaferStartPosition()
        {
            var result = MwMessageBox.Show("是否移动到该点?", "确认", MessageBoxButton.YesNo, MessageBoxImage.Information);
            if (result == MessageBoxResult.Yes)
            {
                try
                {
                    _fusionCalibMotionService.MoveWsAvoidance(WsFusionCalibParItem.StartX, WsFusionCalibParItem.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()
        {
            try
            {
                var result = MwMessageBox.Show("是否开始?", "确认开始", MessageBoxButton.YesNo, MessageBoxImage.Information);
                if (result == MessageBoxResult.Yes)
                {
                    //CameraWaferFusionCalibrationItem.AxisAndPixelPointItemList.Clear();
                    FusionCalib(false);
                }

            }
            catch (Exception ex)
            {

            }
        }

        public void btnStop()
        {
            try
            {
                var result = MwMessageBox.Show("是否开始?", "确认开始", MessageBoxButton.YesNo, MessageBoxImage.Information);
                if (result == MessageBoxResult.Yes)
                {
                    Motion.Cancel();
                    _stopMotion = true;
                }

            }
            catch (Exception ex)
            {


            }
        }

        private void FusionCalib(bool isRecheck, bool isAsyn = true)
        {
            Motion = (DelegateBase)TaskManager.Instance.GetIntance(typeof(FusionCalibTask));
            FusionCalibTask cameraFusionCalibration = Motion as FusionCalibTask;
            if (cameraFusionCalibration != null)
            {
                cameraFusionCalibration.Rectangle = GetRectangle();
            }
            TaskManager.Instance.AsyncStart(Motion, new object[] {  });
        }

        private Rectangle1 GetRectangle()
        {
            var region = CameraAxisViewModelSevice.Regions;
            Rectangle rectangle = null;
            Rectangle1 r = null;
            if (region != null && region.Count > 0)
            {
                RectRegion rect = region[0].Region as RectRegion;
                double start_x = rect.CenterPoint.X - rect.Width / 2;
                double start_y = rect.CenterPoint.Y - rect.Height / 2;
                double end_x = rect.CenterPoint.X + rect.Width / 2;
                double end_y = rect.CenterPoint.Y + rect.Height / 2;
                rectangle = new Rectangle(new System.Windows.Point(start_y, start_x), new System.Windows.Point(end_y, end_x));
                r = new Rectangle1();
                r.Start_X = rectangle.StartPoint.X;
                r.Start_Y = rectangle.StartPoint.Y;
                r.End_X = rectangle.EndPoint.X;
                r.End_Y = rectangle.EndPoint.Y;
            }
            else
            {
                throw new Exception("请添加矩形！");
            }

            return r;
        }
    }

}

