using System.Collections.ObjectModel;
using System.Windows.Input;
using UIShare.PubEvent;
using UIShare.UIViewModel;
using UIShare.ViewModelBase;

namespace SettingModule.ViewModels.Dialogs
{
    /// <summary>
    /// CAN 连接配置对话框 VM。
    /// 通过 DialogParameters 接收宿主 DeviceInfoVM；保存时把副本写回宿主。
    /// 参数对应 ZLGCANFD 构造函数 + 初始化并启动通道 方法。
    /// </summary>
    public class CANConfigViewModel : DialogViewModelBase
    {
        #region 属性

        private string _title = "CAN 连接配置";
        public string Title
        {
            get => _title;
            set => SetProperty(ref _title, value);
        }

        /// <summary>编辑用的副本，取消时不会污染宿主对象。</summary>
        private CANConfigVM _config = new();
        public CANConfigVM Config
        {
            get => _config;
            set => SetProperty(ref _config, value);
        }

        /// <summary>常用仲裁域波特率。</summary>
        public ObservableCollection<string> CommonABitBauds { get; } = new()
        {
            "250000", "500000", "1000000"
        };

        /// <summary>常用数据域波特率。</summary>
        public ObservableCollection<string> CommonDBitBauds { get; } = new()
        {
            "1000000", "2000000", "4000000", "5000000", "8000000"
        };

        private string _errorMessage = string.Empty;
        public string ErrorMessage
        {
            get => _errorMessage;
            set => SetProperty(ref _errorMessage, value);
        }

        #endregion

        #region 命令
        public ICommand SaveCommand { get; }
        public ICommand CancelCommand { get; }
        #endregion

        // 用于保存时把副本回写到原对象
        private DeviceInfoVM? _hostDevice;

        public CANConfigViewModel(IContainerProvider containerProvider) : base(containerProvider)
        {
            SaveCommand = new DelegateCommand(OnSave);
            CancelCommand = new DelegateCommand(OnCancel);
        }

        private bool Validate(out string error)
        {
            error = string.Empty;
            if (Config.DeviceType == 0)
            {
                error = "设备类型号不能为 0";
                return false;
            }
            if (string.IsNullOrWhiteSpace(Config.ABitBaud))
            {
                error = "仲裁域波特率不能为空";
                return false;
            }
            if (string.IsNullOrWhiteSpace(Config.DBitBaud))
            {
                error = "数据域波特率不能为空";
                return false;
            }
            return true;
        }

        private void OnSave()
        {
            if (!Validate(out var error))
            {
                ErrorMessage = error;
                return;
            }
            ErrorMessage = string.Empty;

            // 把副本写回宿主
            if (_hostDevice != null)
            {
                _hostDevice.CANConfig ??= new CANConfigVM();
                Config.CopyTo(_hostDevice.CANConfig);
                _hostDevice.ConnectionType = "CAN";
            }

            RequestClose.Invoke(ButtonResult.OK);
        }

        private void OnCancel() => RequestClose.Invoke(ButtonResult.Cancel);

        #region Prism Dialog 规范
        public override void OnDialogOpened(IDialogParameters parameters)
        {
            _eventAggregator.GetEvent<OverlayEvent>().Publish(true);

            if (parameters.ContainsKey("Device"))
            {
                _hostDevice = parameters.GetValue<DeviceInfoVM>("Device");
                Title = $"CAN 连接配置 - {_hostDevice?.DeviceName}";
                Config = new CANConfigVM(_hostDevice?.CANConfig);
            }
            else if (parameters.ContainsKey("Config"))
            {
                Config = new CANConfigVM(parameters.GetValue<CANConfigVM>("Config"));
            }
        }

        public override void OnDialogClosed()
        {
            _eventAggregator.GetEvent<OverlayEvent>().Publish(false);
        }
        #endregion
    }
}
