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

namespace CANModule.ViewModels
{
    public class CollectCANSignalSettingViewModel : DialogViewModelBase
    {
        #region 字段
        private ZLGCANFD? _canfd;
        private SystemConfig? _systemConfig;
        #endregion

        #region 属性
        public ObservableCollection<CANSignalConfig> ConfigurationList
        {
            get => _systemConfig?.ConfigurationList ?? new ObservableCollection<CANSignalConfig>();
        }

      

        private ObservableCollection<string> _messageList;
        public ObservableCollection<string> MessageList
        {
            get => _messageList;
            set => SetProperty(ref _messageList, value);
        }

        private ObservableCollection<string> _signalList;
        public ObservableCollection<string> SignalList
        {
            get => _signalList;
            set => SetProperty(ref _signalList, value);
        }

        private string _title = "信号采集设置";
        public string Title
        {
            get => _title;
            set => SetProperty(ref _title, value);
        }

        private string _selectedMessage;
        public string SelectedMessage
        {
            get => _selectedMessage;
            set
            {
                if (SetProperty(ref _selectedMessage, value))
                {
                    if (!string.IsNullOrEmpty(value) && _canfd != null)
                    {
                        var db = _canfd.DBCParser.MsgDatabase;
                        if (MessageChannel >= 0 && MessageChannel < db.Count)
                        {
                            var targetMsg = db[MessageChannel]
                                .FirstOrDefault(x => $"[0x{x.msg_id:X}]{x.msg_name}" == value);

                            if (targetMsg != null && targetMsg.signal_Name != null)
                            {
                                SignalList = new ObservableCollection<string>(targetMsg.signal_Name);
                            }
                            else
                            {
                                SignalList = new ObservableCollection<string>();
                            }
                        }
                    }
                    else
                    {
                        SignalList = new ObservableCollection<string>();
                    }
                }
            }
        }

        private CANSignalConfig _SelectedItem;
        public CANSignalConfig SelectedItem
        {
            get => _SelectedItem;
            set => SetProperty(ref _SelectedItem, value);
        }

        private string _selectedSignal;
        public string SelectedSignal
        {
            get => _selectedSignal;
            set => SetProperty(ref _selectedSignal, value);
        }

        private int _MessageChannel=-1;
        public int MessageChannel
        {
            get => _MessageChannel;
            set
            {
                if (_MessageChannel != value)
                {
                    _MessageChannel = value;

                    SelectedMessage = null;
                    SelectedSignal = null;
                    SignalList = new ObservableCollection<string>();

                    if (_canfd != null)
                    {
                        var db = _canfd.DBCParser.MsgDatabase;
                        if (db != null && value >= 0 && value < db.Count)
                        {
                            MessageList = new ObservableCollection<string>(
                                db[value].Select(s => $"[0x{s.msg_id:X}]{s.msg_name}")
                            );
                        }
                        else
                        {
                            MessageList = new ObservableCollection<string>();
                        }
                    }
                    else
                    {
                        MessageList = new ObservableCollection<string>();
                    }

                    RaisePropertyChanged();
                }
            }
        }

        private int _collectionInterval = 1000;
        public int CollectionInterval
        {
            get => _collectionInterval;
            set => SetProperty(ref _collectionInterval, value);
        }
        #endregion

        #region 命令
        public ICommand AddCommand { get; set; }
        public ICommand CloseCommand { get; set; }
        public ICommand SaveCommand { get; set; }
        public ICommand DeleteCommand { get; set; }
        #endregion

        public CollectCANSignalSettingViewModel(IContainerProvider containerProvider) : base(containerProvider)
        {
            CloseCommand = new DelegateCommand(Close);
            AddCommand = new DelegateCommand(Add);
            SaveCommand = new DelegateCommand(Save);
            DeleteCommand = new DelegateCommand(Delete);
        }

        #region Dialog 生命周期
        public override void OnDialogOpened(IDialogParameters parameters)
        {
            _systemConfig = parameters.GetValue<SystemConfig>("SystemConfig");
            _canfd = _systemConfig?.CANFD;
            string title = _systemConfig.Title;
            char lastChar = title[title.Length - 1];
            // 3. "TestCellX"转int
            MessageChannel = int.Parse(lastChar.ToString())-1;
            if (MessageChannel >= 4) MessageChannel -= 4;
            RaisePropertyChanged(nameof(ConfigurationList));
        }
        #endregion

        #region 命令处理
        private void Delete()
        {
            if (SelectedItem != null)
            {
                _systemConfig?.ConfigurationList.Remove(SelectedItem);
            }
        }

        private void Save()
        {
            ConfigService.Save(_systemConfig);
        }


        private void Add()
        {
            if (string.IsNullOrEmpty(SelectedSignal) || string.IsNullOrEmpty(SelectedMessage) || CollectionInterval < 100)
            {
                return;
            }
            if (_systemConfig == null) return;

            string hexString = ExtractHex(SelectedMessage);
            if (string.IsNullOrEmpty(hexString)) return;

            int decimalValue = ConvertHexToDecimal(hexString);
            if (_systemConfig.ConfigurationList.Any(x => x.SignalName == SelectedSignal && x.Channel == MessageChannel))
            {
                return;
            }

            _systemConfig.ConfigurationList.Add(new CANSignalConfig
            {
                CollectionID = Guid.NewGuid(),
                Channel = MessageChannel,
                MethodName = CANSignalBroadcaster.BuildMethodName((uint)decimalValue, SelectedSignal),
                MessageName = ExtractMessageName(SelectedMessage),
                SignalName = SelectedSignal,
                MessageID = decimalValue,
                CollectionInterval = CollectionInterval
            });
        }

        private string ExtractHex(string input)
        {
            int startIndex = input.IndexOf("0x") + 2;
            int endIndex = input.IndexOf("]", startIndex);
            if (startIndex >= 2 && endIndex > startIndex)
            {
                return input.Substring(startIndex, endIndex - startIndex);
            }
            return string.Empty;
        }

        private int ConvertHexToDecimal(string hex)
        {
            try
            {
                return Convert.ToInt32(hex, 16);
            }
            catch (FormatException)
            {
                return -1;
            }
        }

        private string ExtractMessageName(string input)
        {
            var parts = input.Split(']');
            return parts.Length > 1 ? parts[1] : string.Empty;
        }

        private void Close()
        {
            RequestClose.Invoke();
        }
        #endregion
    }
}
