presence/Presence.Desktop/ViewModels/PresenceViewModel.cs
2024-12-23 13:35:07 +03:00

116 lines
3.5 KiB
C#

using Avalonia.Data.Converters;
using domain.Models;
using domain.UseCase;
using Presence.Desktop.ViewModels;
using ReactiveUI;
using System;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Reactive;
namespace Presence.Desktop.ViewModels
{
public class PresenceViewModel : ViewModelBase, IRoutableViewModel
{
public string? UrlPathSegment { get; } = "Presence";
public IScreen HostScreen { get; }
private readonly GroupUseCase _groupUseCase;
private readonly UseCaseGeneratePresence _presenceUseCase;
public ObservableCollection<PresenceLocalEntity> AttendanceRecords { get; set; } = new();
public ObservableCollection<Group> Groups { get; set; } = new();
private Group? _selectedGroup;
public Group? SelectedGroup
{
get => _selectedGroup;
set
{
this.RaiseAndSetIfChanged(ref _selectedGroup, value);
FilterAttendanceRecords();
}
}
private DateTime? _selectedDate;
public DateTime? SelectedDate
{
get => _selectedDate;
set
{
this.RaiseAndSetIfChanged(ref _selectedDate, value);
FilterAttendanceRecords();
}
}
private ObservableCollection<PresenceLocalEntity> _selectedItems = new();
public ObservableCollection<PresenceLocalEntity> SelectedItems
{
get => _selectedItems;
set => this.RaiseAndSetIfChanged(ref _selectedItems, value);
}
public ReactiveCommand<Unit, Unit> NavigateBackCommand { get; }
public ReactiveCommand<Unit, Unit> DeleteSelectedItemsCommand { get; }
public PresenceViewModel(IScreen hostScreen, GroupUseCase groupUseCase, UseCaseGeneratePresence presenceUseCase)
{
_groupUseCase = groupUseCase;
_presenceUseCase = presenceUseCase;
HostScreen = hostScreen;
NavigateBackCommand = ReactiveCommand.Create(() => { });
DeleteSelectedItemsCommand = ReactiveCommand.Create(DeleteSelectedItems);
LoadGroups();
}
private void LoadGroups()
{
Groups.Clear();
var groups = _groupUseCase.GetAllGroups();
foreach (var group in groups)
{
Groups.Add(group);
}
}
private void FilterAttendanceRecords()
{
if (SelectedGroup == null || SelectedDate == null)
{
AttendanceRecords.Clear();
return;
}
var records = _presenceUseCase.GetPresenceByGroupAndDate(
SelectedGroup.Id,
SelectedDate.Value);
AttendanceRecords.Clear();
foreach (var record in records)
{
AttendanceRecords.Add(record);
}
}
public void UpdateAttendanceType(PresenceLocalEntity presence)
{
_presenceUseCase.UpdateAttendance(presence);
}
private void DeleteSelectedItems()
{
if (SelectedItems.Any())
{
foreach (var item in SelectedItems.ToList())
{
_presenceUseCase.DeletePresence(item); // Удаляем из базы данных
AttendanceRecords.Remove(item); // Удаляем из коллекции
}
}
}
}
}