using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Input;
using Prism.Commands;
using Prism.Ioc;
using UIShare.GlobalVariable;
using UIShare.PubEvent;
using UIShare.UIViewModel;
using UIShare.ViewModelBase;

namespace SettingModule.ViewModels
{
    public class SettingViewModel : NavigateViewModelBase, IRegionMemberLifetime, IDisposable
    {

        #region 属性
        private SystemConfig _systemConfig;
        public SystemConfig SystemConfig
        {
            get => _systemConfig;
            set => SetProperty(ref _systemConfig, value);
        }
        public bool KeepAlive => true;
        public string TestStatus
        {
            get => _testStatus;
            set => SetProperty(ref _testStatus, value);
        }

        public DeviceInfoVM? SelectedDevice
        {
            get => _selectedDevice;
            set
            {
                if (SetProperty(ref _selectedDevice, value))
                {
                    OnSelectedDeviceChanged();
                }
            }
        }

        public ObservableCollection<DeviceInfoVM> DeviceList
        {
            get => _deviceList;
            set => SetProperty(ref _deviceList, value);
        }       
        public ObservableCollection<SharedParameter> SharedParameterList
        {
            get => _sharedParameterList;
            set => SetProperty(ref _sharedParameterList, value);
        }

        public string StatusMessage
        {
            get => _statusMessage;
            set => SetProperty(ref _statusMessage, value);
        }

        public ObservableCollection<string> ConnectionTypes { get; } = new()
        {
            "None", "Tcp", "Serial", "CAN"
        };
        #endregion
        #region 命令
        public ICommand RefreshCommand { get; }
        public ICommand SaveCommand { get; }
        public ICommand OpenConnectionConfigCommand { get; }
        #endregion
        #region 私有字段
        private IScopedProvider _scope;
     
        private ScopedContext _scopedContext { get; set; }
        private GlobalInfo _globalInfo { get; }
        private bool IsInitiated = false;
        private string _testStatus = string.Empty;
        private DeviceInfoVM? _selectedDevice;
        private ObservableCollection<DeviceInfoVM> _deviceList;
        private ObservableCollection<SharedParameter> _sharedParameterList;
        private string _statusMessage = "请在左侧选择设备查看 / 编辑配置";
        #endregion
        public SettingViewModel(IContainerExtension container) : base(container)
        {
            _globalInfo = container.Resolve<GlobalInfo>();
            RefreshCommand = new DelegateCommand(OnExpand);
            SaveCommand = new DelegateCommand(OnSave);
            OpenConnectionConfigCommand = new DelegateCommand(OnOpenConnectionConfig);
        }

        public void Dispose()
        {
            try
            {
                if (DeviceList != null)
                {
                    DeviceList = null!;
                }
                SelectedDevice = null;
                _scopedContext = null!;
            }
            catch (Exception ex)
            {
                Logger.LoggerHelper.ErrorWithNotify(TestStatus,$"释放配置管理组件（SettingViewModel）资源失败: {ex.Message}");
            }
        }

        #region 命令
        /// <summary>
        /// 选中设备切换：右侧配置面板靠 SelectedDevice 绑定自动刷新，
        /// 这里只负责更新状态栏提示。
        /// </summary>
        private void OnSelectedDeviceChanged()
        {
            if (SelectedDevice == null)
            {
                StatusMessage = "未选中设备";
                return;
            }
            StatusMessage = $"当前配置：{SelectedDevice.DeviceName}（{SelectedDevice.DeviceType}）";
        }

        /// <summary>双击展开 / 折叠九宫格。</summary>
        private void OnExpand()
        {
            if (string.IsNullOrEmpty(TestStatus)) return;
            _globalInfo.CurrentScope = TestStatus;
            _eventAggregator.GetEvent<ExpandViewEvent>().Publish(TestStatus);
        }

        /// <summary>保存当前 SystemConfig 到 SystemPath 下，文件名为 {Title}.json。</summary>
        private void OnSave()
        {
            if (SystemConfig == null)
            {
                StatusMessage = "无可保存的配置";
                return;
            }

            if (string.IsNullOrWhiteSpace(SystemConfig.Title))
            {
                StatusMessage = "保存失败：标题（Title）不能为空";
                return;
            }

            ConfigService.Save(SystemConfig);
            StatusMessage = $"已保存配置 [{SystemConfig.Title}.json] 至 {SystemConfig.SystemPath}（{DateTime.Now:HH:mm:ss}）";
        }

        /// <summary>重置当前选中设备的配置（占位）。</summary>
       

        /// <summary>
        /// 打开"连接配置"对话框。按 SelectedDevice.ConnectionType 决定开 Tcp 还是串口对话框。
        /// </summary>
        private void OnOpenConnectionConfig()
        {
            if (SelectedDevice == null)
            {
                StatusMessage = "请先在左侧选择设备";
                return;
            }

            var dialogName = SelectedDevice.ConnectionType switch
            {
                "Tcp" => "TCPConfig",
                "Serial" => "SerialPortConfig",
                "CAN" => "CANConfig",
                _ => string.Empty
            };

            if (string.IsNullOrEmpty(dialogName))
            {
                StatusMessage = "当前设备未配置连接方式（请先选择 Tcp 或 Serial）";
                return;
            }

            var p = new DialogParameters
            {
                { "Device", SelectedDevice },
                { "SystemConfig", SystemConfig }
            };

            _dialogService.ShowDialog(dialogName, p, r =>
            {
                if (r.Result == ButtonResult.OK)
                {
                    StatusMessage = $"已更新 [{SelectedDevice.DeviceName}] 的连接参数（{DateTime.Now:HH:mm:ss}）";
                }
            });
        }
        #endregion

        #region 重写
        public override void OnNavigatedTo(NavigationContext navigationContext)
        {
            base.OnNavigatedTo(navigationContext);
            if (!IsInitiated && navigationContext.Parameters.ContainsKey("Name"))
            {
                TestStatus = navigationContext.Parameters.GetValue<string>("Name");
                _scope = _globalInfo.ScopeDic[TestStatus];
                _scopedContext = _globalInfo.ContextDic[TestStatus];
                SystemConfig = _scope.Resolve<SystemConfig>();
                ConfigService.EnsureDefaultCanDevice(SystemConfig);
                if (DeviceList != null && DeviceList.Count > 0)
                {
                    SelectedDevice = DeviceList[0];
                }
                DeviceList = SystemConfig.DeviceList;
                SharedParameterList=SystemConfig.SharedParameterList;
                if (SharedParameterList.Count == 0)
                {
                    foreach (var device in SystemConfig.ParameterList)
                    {
                        var sharedParam = new SharedParameter
                        {
                            Id = device.ID.ToString(),
                            ParameterName = device.Name,
                            Value = device.Value is int intVal ? intVal : Convert.ToInt32(device.Value)
                        };
                        SharedParameterList.Add(sharedParam);
                    }
                }
                IsInitiated = true;
            }
        }
        #endregion
       
    }
}