using MainShell.AlgorithmCalib.Model;
using MainShell.AlgorithmCalib.Service;
using MainShell.Common;
using MainShell.Common.Display.ViewModel;
using MainShell.Hardware;
using MainShell.Log;
using MainShell.Motion;
using MaxwellFramework.Core.Interfaces;
using MwFramework.Controls.ControlCanvas.Model;
using SemiconductorVisionAlgorithm.SemiParams;
using Stylet;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace MainShell.AlgorithmCalib.ViewModel
{
    /// <summary>
    /// 对标 OriginCalibViewModel（页面主VM）
    /// 原 RotateFormCalibViewModel 中页面级逻辑搬到这里
    /// </summary>
    public class RotateMatixFormCalibViewModel : Screen, IPage
    {
        public string Name { get; set; } = "RotateFormCalib";

        private readonly RotateMatixFormCalibSetting _setting;
        private readonly HardwareManager _hardware;
        private readonly RotateMatixFormCalibMotionService _motionService;
        private readonly ApproachAlignmentService _approachAlignmentService;
        private bool _isInitialized;

        private RotateMatixFormModuleViewModel _module;
        public RotateMatixFormModuleViewModel Module
        {
            get { return _module; }
            private set { SetAndNotify(ref _module, value); }
        }
        private CameraAxisViewModel _cameraAxisViewModel;
        public CameraAxisViewModel CameraAxisViewModel
        {
            get { return _cameraAxisViewModel; }
            private set { SetAndNotify(ref _cameraAxisViewModel, value); }
        }

        public RotateMatixFormCalibViewModel(
            HardwareManager hardware,
            RotateMatixFormCalibMotionService motionService,
            ApproachAlignmentService approachAlignmentService)
        {
            _hardware = hardware ?? throw new ArgumentNullException(nameof(hardware));
            _motionService = motionService ?? throw new ArgumentNullException(nameof(motionService));
            _setting = RotateMatixFormCalibSetting.LoadOrCreate();
            _approachAlignmentService = approachAlignmentService;
        }

        protected override void OnViewLoaded()
        {
            // TODO: 对标 OriginCalibViewModel.OnViewLoaded()
            if (_isInitialized) return;

            // 1. 初始化相机
            CameraAxisViewModel = IoC.Get<CameraAxisViewModel>();
            CameraAxisViewModel.CameraAxisDevices.HardwareDeviceList = _hardware.CameraAxisManager.TopCameraAxisDevices;

            // 2. 初始化后处理器
            InitializePostProcessors();

            // 3. 构建模块 ViewModel
            RebuildModuleViewModels();

            _isInitialized = true;
        }

        /// <summary>
        /// 对标 OriginCalibViewModel.InitializePostProcessors()
        /// 为每个模块注入 RotateFormCalibPostProcessor
        /// </summary>
        private void InitializePostProcessors()
        {
            foreach (var module in _setting.Modules)
            {
                module.PostProcessor = new RotateMatixFormCalibPostProcessor(
                    _motionService,
                    _hardware,
                    module,
                    _approachAlignmentService,
                    GetRoiRect
                    );
            }
        }

        /// <summary>
        /// 对标 OriginCalibViewModel.RebuildModuleViewModels()
        /// </summary>
        private void RebuildModuleViewModels()
        {
            Module = null;
            if (_setting.Modules.Count > 0)
            {
                Module = new RotateMatixFormModuleViewModel(
                              _setting.Modules[0],
                              _hardware,
                              _motionService,
                              _approachAlignmentService,
                              GetRoiRect);
                Module.Index = 1;
                NotifyOfPropertyChange(nameof(Module));
            }
        }

        /// <summary>
        /// 对标 OriginCalibViewModel.SaveConfig()
        /// </summary>
        public void SaveConfig()
        {
            // 填入：
            try
            {
                _setting.Write();
                MwMessageBox.Show("标定数据已保存。", "旋转表标定",
                    MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                MwMessageBox.Show($"保存失败：{ex.Message}", "旋转表标定",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 对标 OriginCalibViewModel.ResetAll()
        /// </summary>
        public void ResetAll()
        {
            // 填入：
            Module?.ResetModule();
        }

        /// <summary>
        /// 获取当前 ROI 区域
        /// </summary>
        private Rectangle1 GetRoiRect()
        {
            try
            {
                var region = CameraAxisViewModel?.Regions;
                if (region != null && region.Count > 0)
                {
                    RectRegion rect = region[0].Region as RectRegion;
                    if (rect != null)
                    {
                        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;

                        return new Rectangle1
                        {
                            Start_X = start_y,
                            Start_Y = start_x,
                            End_X = end_y,
                            End_Y = end_x
                        };
                    }
                }
            }
            catch (Exception ex)
            {
                $"获取Region失败：{ex.Message}".LogSysError();
            }
            return null;
        }
    }
}
