MainVM.cs 2.82 KB
using System.Collections.ObjectModel;
using System.Windows;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using HHECS.DAQClient.Common;
using HHECS.DAQClient.Services;

namespace HHECS.DAQClient.ViewModel
{
    internal partial class MainVM : ObservableObject
    {
        private readonly SystemLog _log = SystemLog.GetInstance();
        private readonly CenterService _centerService;

        [ObservableProperty]
        private bool btnStartEnabled = true;

        [ObservableProperty]
        private bool btnStopEnabled = false;

        [ObservableProperty]
        private ObservableCollection<LogModel> logModels = new();

        public MainVM(CenterService centerService)
        {
            _centerService = centerService;
            InitialLogComponent();
        }

        [RelayCommand]
        public void Start()
        {
            BtnStartEnabled = false;
            BtnStopEnabled = true;
            _centerService.Start();

        }

        [RelayCommand]
        public void Stop()
        {
            BtnStartEnabled = true;
            BtnStopEnabled = false;
            _centerService.Stop();
        }

        private void InitialLogComponent()
        {
            Task.Run(() =>
            {
                Application.Current.Dispatcher.Invoke(async () =>
                {
                    do
                    {
                        while (!_log.IsEmpty)
                        {
                            var log = _log.GetLog();
                            if (log != null)
                            {
                                var oldItem = LogModels.Where(x => x.Messages.Equals(log.Messages)).FirstOrDefault();
                                if (oldItem != null)
                                {
                                    oldItem.CreateTime = log.CreateTime;
                                    LogModels = new ObservableCollection<LogModel>(LogModels.OrderByDescending(x => x.CreateTime));
                                }
                                else
                                {
                                    LogModels.Insert(0, new LogModel()
                                    {
                                        LogType = log.LogType,
                                        Messages = log.Messages,
                                        CreateTime = log.CreateTime
                                    });
                                }
                                if (LogModels.Count > 50)
                                {
                                    LogModels.Remove(LogModels.Last());
                                }
                            }
                        }
                        await Task.Delay(100);
                    } while (true);
                });
            });
        }
    }
}