using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Avalonia.Controls; using CommunityToolkit.Mvvm.ComponentModel; using Microsoft.Extensions.DependencyInjection; using Sln.Wcs.UI.ViewModels.Base; using Sln.Wcs.UI.ViewModels.Device; using Sln.Wcs.UI.ViewModels.Path; using Sln.Wcs.UI.ViewModels.Task; using Sln.Wcs.UI.Views; namespace Sln.Wcs.UI.ViewModels; public partial class NavigationViewModel : ObservableObject { private readonly IServiceProvider _sp; private readonly Dictionary _vmCache = new(); private readonly Dictionary _viewCache = new(); private Control? _homeView; public ObservableCollection TopMenuItems { get; } = new(); [ObservableProperty] private string _currentPageTitle = "首页"; public event Action? PageChanged; public NavigationViewModel(IServiceProvider sp) { _sp = sp; BuildMenu(); } public void LoadDefaultPage() => ShowHome(); private void BuildMenu() { TopMenuItems.Clear(); TopMenuItems.Add(new TopMenuItem("首页", ShowHome)); TopMenuItems.Add(new TopMenuItem("系统监控", ShowMonitor)); TopMenuItems.Add(new TopMenuItem("基础数据", new List { new("库位信息", () => NavigateTo("基础数据")), new("物料信息", () => NavigateTo("基础数据")), new("仓库信息", () => NavigateTo("基础数据")), })); TopMenuItems.Add(new TopMenuItem("设备管理", new List { new("设备主机", () => NavigateTo("设备管理")), new("设备信息", () => NavigateTo("设备管理")), new("设备参数", () => NavigateTo("设备管理")), })); TopMenuItems.Add(new TopMenuItem("路径管理", new List { new("路径信息", () => NavigateTo("路径管理")), new("路径明细", () => NavigateTo("路径管理")), })); TopMenuItems.Add(new TopMenuItem("任务管理", new List { new("任务队列", () => NavigateTo("任务管理")), new("任务明细", () => NavigateTo("任务管理")), })); } private string? _currentModule; private void ShowHome() { if (_homeView == null) { var vm = _sp.GetRequiredService(); _homeView = new HomePageView { DataContext = vm }; } CurrentPageTitle = "首页"; PageChanged?.Invoke(_homeView); } private void ShowMonitor() { CurrentPageTitle = "系统监控"; PageChanged?.Invoke(new SystemMonitorView(_sp.GetRequiredService())); } private void NavigateTo(string module) where T : ICrudPageViewModel { var type = typeof(T); if (!_vmCache.TryGetValue(type, out var vm)) { vm = _sp.GetRequiredService(); _vmCache[type] = vm; } if (!_viewCache.TryGetValue(type, out var view)) { view = vm.CreateView(); view.DataContext = vm; _viewCache[type] = view; } CurrentPageTitle = $"{module} > {vm.PageTitle}"; PageChanged?.Invoke(view); vm.Load(); } } public class TopMenuItem { public string Label { get; set; } public List? Children { get; set; } public Action? Action { get; set; } public TopMenuItem(string label, Action action) { Label = label; Action = action; } public TopMenuItem(string label, List children) { Label = label; Children = children; } } public class SubMenuItem { public string Label { get; set; } public Action Action { get; set; } public SubMenuItem(string label, Action action) { Label = label; Action = action; } }