using MainShell.AlgorithmCalib.Model;
using MainShell.AlgorithmCalib.Service;
using MainShell.Common;
using MainShell.Common.Display.ViewModel;
using MainShell.Hardware;
using MainShell.Motion;
using Maxwell.SemiFramework.DefaultConfig.Vision;
using MaxwellFramework.Core.Interfaces;
using MwFramework.Controls.ControlCanvas.Model;
using MwFramework.ManagerService;
using SemiconductorVisionAlgorithm.SemiParams;
using Stylet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Point = SemiconductorVisionAlgorithm.SemiParams.Point;

namespace MainShell.AlgorithmCalib.ViewModel
{
    public class CameraFusionCalibVerifyViewModel : Screen, IPage
    {
        public string Name { get; set; } = "CameraFusionCalibVerify";

        public string CameraName { get; set; }

        private readonly FusionCalibMotionService _fusionCalibMotionService;

        private HardwareManager _hardware;

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

        private FusionCalibVerifyParItem _wsfusionCalibVerifyParItem = new FusionCalibVerifyParItem();
        public FusionCalibVerifyParItem WsfusionCalibVerifyParItem
        {
            get { return _wsfusionCalibVerifyParItem; }
            set
            {
                _wsfusionCalibVerifyParItem = value;
                OnPropertyChanged(nameof(WsfusionCalibVerifyParItem));
            }
        }

        private bool _stopMotion = false;

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

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

        private void Initialize(string cameraName, List<HardwareDevice> device)
        {
            CameraName = cameraName;
            Name = cameraName;
            var paramList = IoC.Get<IParameterManager>() as IParamList;
        }


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

                    //_safeAxisMotion.SafeAbsoluteMove(_gs.Axis_X11, CameraWaferFusionCalibrationItem.WSPlatCalibXPos, block: false);
                    //_safeAxisMotion.SafeMoveWS(CameraWaferFusionCalibrationItem.WSApproachXPos, CameraWaferFusionCalibrationItem.WSApproachYPos, isBlock: false);
                }
                catch (Exception ex)
                {

                }
            });
        }

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

        public void btnMoveToStartPoint()
        {
            //_safeAxisMotion.SafeMoveXY(_gs.Axis_X21, _gs.Axis_Y21, CameraWaferFusionCalibrationItem.WaferStartVerifyX, CameraWaferFusionCalibrationItem.WaferStartVerifyY);
            _fusionCalibMotionService.MoveWsAvoidance(WsfusionCalibVerifyParItem.StartX, WsfusionCalibVerifyParItem.StartY);
        }

        public void btnMoveWafer()
        {
            //WsfusionCalibVerifyParItem.VerifyRealPts = new List<Point>();
            //List<Point> points = new List<Point>();
            //System.Threading.Tasks.Task.Run(() =>
            //{
            //    for (var i = 0; i < WsfusionCalibVerifyParItem.CountY; i++)
            //    {
            //        for (var j = 0; j < WsfusionCalibVerifyParItem.CountX; j++)
            //        {
            //            if (_stopMotion)
            //            {
            //                _stopMotion = false;
            //                return;
            //            }
            //            double yPos = WsfusionCalibVerifyParItem.StartY + i * WsfusionCalibVerifyParItem.Step;
            //            double xPos;
            //            if (i % 2 == 0)
            //            {
            //                xPos = WsfusionCalibVerifyParItem.StartX + j * WsfusionCalibVerifyParItem.Step;
            //            }
            //            else
            //            {
            //                xPos = WsfusionCalibVerifyParItem.StartX + (WsfusionCalibVerifyParItem.CountX - j - 1) * WsfusionCalibVerifyParItem.Step;
            //            }
            //            points.Add(new Point(xPos, yPos));
            //            _fusionCalibMotionService.MoveWsAvoidance(xPos, yPos);
            //            if (ApproachPointWS())
            //            {
            //                //WsfusionCalibVerifyParItem.ApproachXPos = _hardware.Axis_X2.State.ActualPos;
            //                //CameraWaferFusionCalibrationItem.WSVerityApproachXpos = _gs.Axis_X21.State.ActualPos;
            //                //CameraWaferFusionCalibrationItem.WSVerityApproachYpos = _gs.Axis_Y21.State.ActualPos;
            //                Point ruler = new Point(_hardware.Axis_X2.State.ActualPos, _hardware.Axis_Y1.State.ActualPos);
            //                Point real = _visionOperation.GetRealByRuler(_hardware.Camera_ExtendWS.Id, ruler);
            //                WsfusionCalibVerifyParItem.VerifyRealPts.Add(new Point(real.X, real.Y));
            //            }
            //            else
            //            {
            //                MwMessageBox.Show("逼近失败！");
            //            }
            //        }
            //    }
            //    MwMessageBox.Show("飞拍结束");
            //});
        }

        public void btnVerifyWafer()
        {
            //if (WsfusionCalibVerifyParItem.VerifyRealPts != null && WsfusionCalibVerifyParItem.VerifyRealPts.Count > 0)
            //{
            //    var result = MwMessageBox.Show("是否已移动到Pad位置，确认开始验证?", "确认开始", MessageBoxButton.YesNo, MessageBoxImage.Information);
            //    if (result == MessageBoxResult.Yes)
            //    {
            //        System.Threading.Tasks.Task.Factory.StartNew(() =>
            //        {
            //            List<SemiconductorVisionAlgorithm.SemiParams.Point> WSrulerThen = new List<SemiconductorVisionAlgorithm.SemiParams.Point>();
            //            List<SemiconductorVisionAlgorithm.SemiParams.Point> WSrulerNow = new List<SemiconductorVisionAlgorithm.SemiParams.Point>();
            //            Point padReal = _visionOperation.GetRealByRuler(_gs.Camera_Extend.Id, new Point(_gs.Axis_X11.State.ActualPos, _gs.Axis_Y11.State.ActualPos));
            //            for (var i = 0; i < WsfusionCalibVerifyParItem.VerifyRealPts.Count; i++)
            //            {
            //                if (_stopMotion)
            //                {
            //                    _stopMotion = false;
            //                    return;
            //                }
            //                SemiconductorVisionAlgorithm.SemiParams.Point rulerPoint = new SemiconductorVisionAlgorithm.SemiParams.Point();
            //                JM1Vision.JM1Manager.Instance.get_ws_pos(_gs.Camera_Extend.Id, _gs.Camera_ExtendWS.Id, new SemiconductorVisionAlgorithm.SemiParams.Point(padReal.X, padReal.Y), new SemiconductorVisionAlgorithm.SemiParams.Point(CameraWaferFusionCalibrationItem.VerityrealPointRealPoints[i].X, CameraWaferFusionCalibrationItem.VerityrealPointRealPoints[i].Y), out rulerPoint);
            //                WSrulerThen.Add(new SemiconductorVisionAlgorithm.SemiParams.Point(rulerPoint.X, rulerPoint.Y));
            //                _fusionCalibMotionService.MoveWsAvoidance(rulerPoint.X, rulerPoint.Y);
            //                //_safeAxisMotion.SafeMoveWS(rulerPoint.X, rulerPoint.Y, isCalib: true);
            //                if (ApproachPointWS())
            //                {
            //                    WSrulerNow.Add(new SemiconductorVisionAlgorithm.SemiParams.Point(_hardware.Axis_X2.State.ActualPos, _hardware.Axis_Y1.State.ActualPos));
            //                }
            //                else
            //                {
            //                    MwMessageBox.Show("逼近失败！");
            //                }
            //            }
            //            string filePath = System.AppDomain.CurrentDomain.BaseDirectory + @"CalibData";
            //            JM1Vision.JM1Manager.Instance.pos_verify(filePath, WSrulerThen, WSrulerNow);
            //            MwMessageBox.Show("验证完成！");
            //        });
            //    }
            //}
            //else
            //{
            //    MwMessageBox.Show("请先执行飞拍！");
            //    return;
            //}
        }

        public void btnStopVerifyWafer()
        {
            try
            {
                var result = MwMessageBox.Show("是否停止?", "确认停止", MessageBoxButton.YesNo, MessageBoxImage.Information);
                if (result == MessageBoxResult.Yes)
                {
                    _stopMotion = true;
                }
            }
            catch (Exception ex)
            {

            }
        }

        private bool ApproachPointWS(int approachTime = 10)
        {
            return false;
            //string modelFileName = WsfusionCalibVerifyParItem.ModelPath;
            //string path = System.AppDomain.CurrentDomain.BaseDirectory + modelFileName;
            //Rectangle1 r = GetRectangle();

            //VisionOperation visionOperation = IoC.Get<VisionOperation>();
            ////相机拍照
            //return visionOperation.ApproachPointCircle(_hardware.Camera_ExtendWS, _hardware.Axis_X2, _hardware.Axis_Y1, path, r, out System.Windows.Point point, approachTime);
        }

        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;
        }
    }
}
