using JM1.VisionModule;
using MainShell.AlgorithmCalib.Model;
using MainShell.AlgorithmCalib.Service;
using MainShell.AlgorithmCalib.View;
using MainShell.Common;
using MainShell.Common.Display.ViewModel;
using MainShell.Filewritable;
using MainShell.Hardware;
using MaxwellFramework.Core.Interfaces;
using MwFramework.ManagerService;
using Stylet;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace MainShell.AlgorithmCalib.ViewModel
{
    /// <summary>
    /// Pad融合标定 - 多区域管理VM（对标 MotionMultipleCalibViewModel）
    /// 管理4组标定区域，每组可打开子窗口标定
    /// </summary>
    public class FusionMultipleCalibViewModel : Screen, IPage
    {
        #region 常量 & 字段

        private const int CalibAreaCount = 4;
        private const string PointsFileExt = ".csv";
        private const string AreaFilePrefix = "Fusion_Time";

        private readonly HashSet<string> _forceCloseIds = new HashSet<string>();
        private readonly Dictionary<string, Window> _calibWindows = new Dictionary<string, Window>();
        private bool _isDataLoaded = false;

        #endregion

        #region 属性

        public string Name { get; set; } = "FusionMultipleCalib";
        public string CalibName { get; set; }
        public string FileSaveDir { get; set; }

        private CameraAxisViewModel _cameraAxisViewModelService;
        public CameraAxisViewModel CameraAxisViewModelService
        {
            get => _cameraAxisViewModelService;
            set => SetAndNotify(ref _cameraAxisViewModelService, value);
        }

        private ObservableCollection<FusionCalibModuleItem> _calibItems = new
ObservableCollection<FusionCalibModuleItem>();
        public ObservableCollection<FusionCalibModuleItem> CalibItems
        {
            get => _calibItems;
            set => SetAndNotify(ref _calibItems, value);
        }

        private FusionCalibModuleItem _selectedItem;
        public FusionCalibModuleItem SelectedItem
        {
            get => _selectedItem;
            set => SetAndNotify(ref _selectedItem, value);
        }

        private FusionCalibSetting _setting;
        private List<HardwareDevice> _hardwareDevice;
        public List<HardwareDevice> HardwareDevice
        {
            get => _hardwareDevice;
            set => SetAndNotify(ref _hardwareDevice, value);
        }

        private HardwareManager _hardware;
        public HardwareManager Hardware
        {
            get => _hardware;
            set => SetAndNotify(ref _hardware, value);
        }

        private FusionCalibMotionService _fusionCalibMotionService;

        #endregion

        #region 构造 & 工厂

        public FusionMultipleCalibViewModel()
        {
            _cameraAxisViewModelService = IoC.Get<CameraAxisViewModel>();
        }

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

        #endregion

        #region 初始化 & 生命周期

        private void Initialize(string calibName, string saveFileName,
            List<HardwareDevice> device, HardwareManager hardware, FusionCalibMotionService motion)
        {
            CalibName = calibName;
            Hardware = hardware;
            HardwareDevice = device;
            _fusionCalibMotionService = motion;
            FileSaveDir = Path.Combine(Paths.CalibSettingPath, "fusionCalib");
            _setting = FusionCalibSetting.LoadOrCreate();
        }

        protected override void OnViewLoaded()
        {
            base.OnViewLoaded();
            if (_hardware != null)
            {
                _cameraAxisViewModelService.CameraAxisDevices.HardwareDeviceList = HardwareDevice;
                NotifyOfPropertyChange(nameof(CameraAxisViewModelService));
            }
            if (!_isDataLoaded)
            {
                ReadCalibData();
                _isDataLoaded = true;
            }
        }

        #endregion

        #region 打开标定窗口

        public void btnOpenCalibWindow()
        {
            if (SelectedItem == null)
            {
                MwMessageBox.Show("请先选择一组标定数据。", "提示",
                    MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            string calibId = SelectedItem.Camera_ID;

            if (_calibWindows.TryGetValue(calibId, out var existingWindow))
            {
                if (existingWindow.WindowState == WindowState.Minimized)
                    existingWindow.WindowState = WindowState.Normal;
                existingWindow.Show();
                existingWindow.Activate();
                return;
            }

            // 创建子窗口 VM（Pad模式）
            var calibVM = FusionCalibViewModel.Create(
                CalibName, HardwareDevice, SelectedItem, Hardware, _fusionCalibMotionService, isWaferCalib:
false);
            calibVM.FileSaveDir = FileSaveDir;

            var window = CreateCalibWindow(calibId, calibVM);
            _calibWindows[calibId] = window;
            window.Show();
        }

        private Window CreateCalibWindow(string calibId, FusionCalibViewModel calibVM)
        {
            var calibView = new PadFusionCalibView { DataContext = calibVM };

            var window = new Window
            {
                Title = $"Pad融合标定 - {calibId}",
                Width = 1100,
                Height = 750,
                WindowStartupLocation = WindowStartupLocation.CenterOwner,
                Owner = Application.Current.MainWindow,
                ResizeMode = ResizeMode.CanResize,
                Content = calibView
            };

            window.Closing += (s, args) =>
            {
                if (_forceCloseIds.Contains(calibId))
                {
                    _forceCloseIds.Remove(calibId);
                    return;
                }
                args.Cancel = true;
                SyncResultBack(calibVM);
                window.Hide();
            };

            return window;
        }

        #endregion

        #region 数据同步

        private void SyncResultBack(FusionCalibViewModel calibVM)
        {
            var source = calibVM.ModuleItem;
            if (source == null) return;

            var target = CalibItems.FirstOrDefault(p => p.Camera_ID == source.Camera_ID);
            if (target == null) return;

            target.MoveAxisPos = source.MoveAxisPos;
            target.ApproachXPos = source.ApproachXPos;
            target.ApproachYPos = source.ApproachYPos;
            target.CameraAxisPos = source.CameraAxisPos;
            target.StartX = source.StartX;
            target.StartY = source.StartY;
            target.Step = source.Step;
            target.Count = source.Count;
            target.CalibStep = source.CalibStep;
            target.CalibCount = source.CalibCount;
            target.RulerPoints = source.RulerPoints;
            target.RealPoints = source.RealPoints;

            OnPropertyChanged(nameof(CalibItems));
        }

        #endregion

        #region 读取 & 保存

        public void btnReadCalibData()
        {
            var result = MwMessageBox.Show("确认读取本地标定数据？", "确认读取",
                MessageBoxButton.YesNo, MessageBoxImage.Warning);
            if (result == MessageBoxResult.Yes)
            {
                if (!ReadCalibData())
                    MwMessageBox.Show("读取本地标定数据失败！", "提示", MessageBoxButton.OK,
MessageBoxImage.Error);
            }
        }

        public bool ReadCalibData()
        {
            try
            {
                var items = new ObservableCollection<FusionCalibModuleItem>();
                for (int i = 0; i < CalibAreaCount; i++)
                {
                    var module = i < _setting.PadModules.Count
                        ? _setting.PadModules[i]
                        : new FusionCalibModuleItem
                        {
                            Index = i + 1,
                            Camera_ID = $"{AreaFilePrefix}{i + 1}",
                            IsWaferCalib = false,
                        };

                    var pointsPath = Path.Combine(FileSaveDir,$"{AreaFilePrefix}{module.Index}{PointsFileExt}");
                    if (File.Exists(pointsPath))
                    {
                        MotionCalibFileService.ReadCalibPointsFile(pointsPath, out var real, out var ruler);
                        module.RealPoints = real;
                        module.RulerPoints = ruler;
                    }

                    items.Add(module);
                }
                CalibItems = items;
                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"[FusionMultiple] ReadCalibData 失败: {ex}");
                return false;
            }
        }

        public void btnSaveCalibData()
        {
            var result = MwMessageBox.Show("确认保存当前全部标定数据？", "确认保存",
                MessageBoxButton.YesNo, MessageBoxImage.Warning);
            if (result == MessageBoxResult.Yes)
            {
                if (SaveCalibData())
                    MwMessageBox.Show("保存成功！", "提示", MessageBoxButton.OK,
MessageBoxImage.Information);
                else
                    MwMessageBox.Show("保存失败！", "提示", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private bool SaveCalibData()
        {
            try
            {
                Directory.CreateDirectory(FileSaveDir);
                _setting.PadModules = new List<FusionCalibModuleItem>(CalibItems);
                _setting.Write();

                foreach (var par in CalibItems)
                {
                    if (par.RealPoints?.Count > 0 && par.RulerPoints?.Count > 0)
                    {
                        var pointsPath = Path.Combine(FileSaveDir,$"{AreaFilePrefix}{par.Index}{PointsFileExt}");
                        MotionCalibFileService.SaveCalibPointsFile(pointsPath, par.RealPoints,par.RulerPoints);
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"[FusionMultiple] SaveCalibData 失败: {ex}");
                return false;
            }
        }

        #endregion

        #region 应用

        public void btnApplyCalibData()
        {
            if (CalibItems.Count != CalibAreaCount)
            {
                MwMessageBox.Show("标定数据不足！", "提示", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            var result = MwMessageBox.Show("确认应用标定数据？", "确认应用",
                MessageBoxButton.YesNo, MessageBoxImage.Warning);
            if (result == MessageBoxResult.Yes)
            {
                // TODO: 调用融合应用算法
                MwMessageBox.Show("应用成功！", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        #endregion

        #region 窗口生命周期

        public void CleanupCalibWindows()
        {
            foreach (var kvp in _calibWindows) _forceCloseIds.Add(kvp.Key);
            foreach (var kvp in _calibWindows)
            {
                try { kvp.Value.Close(); }
                catch { }
            }
            _calibWindows.Clear();
            _forceCloseIds.Clear();
        }

        #endregion
    }
}