using System.Globalization; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Animation; using QuickIP.Client.Models; using QuickIP.Client.Services; namespace QuickIP.Client; public partial class DeviceDetailsWindow : Window { private readonly AgentApiService _agentApiService = new(); private readonly string _baseAddress; private readonly string _localIPv4; private readonly string _password; private bool _configValidated; private bool _suppressConfigChangeHandling; private CancellationTokenSource? _statusMessageCts; public DeviceDetailsWindow(string baseAddress, string localIPv4, string password) { InitializeComponent(); _baseAddress = baseAddress; _localIPv4 = localIPv4; _password = password; Loaded += DeviceDetailsWindow_OnLoaded; } private async void DeviceDetailsWindow_OnLoaded(object sender, RoutedEventArgs e) { await LoadRemoteDetailsAsync(); UpdateButtonStates(); } private async Task LoadRemoteDetailsAsync() { ClearDetails(); var device = await _agentApiService.GetDeviceInfoAsync(_baseAddress, _password, _localIPv4); if (device is not null) { RemoteDeviceIdTextBlock.Text = device.DeviceId; RemoteHostnameTextBlock.Text = device.Hostname; RemoteOsVersionTextBlock.Text = device.OSVersion; RemoteAgentVersionTextBlock.Text = device.AgentVersion; } var interfaces = await _agentApiService.GetInterfacesAsync(_baseAddress, _password, _localIPv4); if (interfaces is null) { ShowStatusMessage("设备已连接,但暂时无法读取 Linux 接口列表。"); return; } ShowStatusMessage($"当前管理接口:{interfaces.ManagementInterface};建议目标接口:{interfaces.SuggestedTargetInterface};{(interfaces.RequiresTargetSelection ? "需要手动选择目标接口。" : "已自动识别建议目标接口。")}"); var suggested = interfaces.Interfaces.FirstOrDefault(item => item.SystemName == interfaces.SuggestedTargetInterface) ?? interfaces.Interfaces.FirstOrDefault(item => item.IsSuggestedTarget) ?? interfaces.Interfaces.FirstOrDefault(item => !item.IsManagementInterface); RemoteTargetInterfaceComboBox.ItemsSource = interfaces.Interfaces; if (suggested is not null) { RemoteTargetInterfaceComboBox.SelectedItem = suggested; await LoadRemoteInterfaceConfigAsync(suggested.SystemName); } } private void ClearDetails() { RemoteDeviceIdTextBlock.Text = "-"; RemoteHostnameTextBlock.Text = "-"; RemoteOsVersionTextBlock.Text = "-"; RemoteAgentVersionTextBlock.Text = "-"; RemoteTargetInterfaceComboBox.ItemsSource = null; RemoteConfigInterfaceTextBlock.Text = "-"; RemoteConfigIpTextBlock.Text = "-"; RemoteConfigGatewayTextBlock.Text = "-"; RemoteConfigDnsTextBlock.Text = "-"; NewIpTextBox.Text = string.Empty; NewMaskTextBox.Text = string.Empty; NewGatewayTextBox.Text = string.Empty; NewDnsTextBox.Text = string.Empty; _configValidated = false; } private async void RemoteTargetInterfaceComboBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e) { if (RemoteTargetInterfaceComboBox.SelectedItem is not RemoteInterfaceInfo selected) { return; } await LoadRemoteInterfaceConfigAsync(selected.SystemName); } private async Task LoadRemoteInterfaceConfigAsync(string interfaceName) { var result = await _agentApiService.GetInterfaceConfigAsync(_baseAddress, _password, _localIPv4, interfaceName); if (!result.Success || result.Data is null) { RemoteConfigInterfaceTextBlock.Text = interfaceName; RemoteConfigIpTextBlock.Text = "读取失败"; RemoteConfigGatewayTextBlock.Text = "读取失败"; RemoteConfigDnsTextBlock.Text = "读取失败"; ShowStatusMessage($"读取目标接口 {interfaceName} 配置失败:{result.Message}"); return; } var config = result.Data; RemoteConfigInterfaceTextBlock.Text = config.Interface; RemoteConfigIpTextBlock.Text = string.IsNullOrWhiteSpace(config.IP) ? "无" : $"{config.IP}/{config.Prefix}"; RemoteConfigGatewayTextBlock.Text = string.IsNullOrWhiteSpace(config.Gateway) ? "无" : config.Gateway; RemoteConfigDnsTextBlock.Text = config.DnsSummary; _suppressConfigChangeHandling = true; NewIpTextBox.Text = config.IP; NewMaskTextBox.Text = PrefixToMask(config.Prefix); NewGatewayTextBox.Text = config.Gateway; NewDnsTextBox.Text = config.Dns.FirstOrDefault() ?? string.Empty; _suppressConfigChangeHandling = false; _configValidated = false; ShowStatusMessage("已回填目标接口当前配置,可直接修改后校验。"); UpdateButtonStates(); } private async void ReloadInterfaceConfigButton_OnClick(object sender, RoutedEventArgs e) { if (RemoteTargetInterfaceComboBox.SelectedItem is RemoteInterfaceInfo selected) { await LoadRemoteInterfaceConfigAsync(selected.SystemName); } } private async void ValidateConfigButton_OnClick(object sender, RoutedEventArgs e) { if (RemoteTargetInterfaceComboBox.SelectedItem is not RemoteInterfaceInfo selected) { return; } var request = BuildConfigRequest(selected.SystemName); if (request is null) { return; } var result = await _agentApiService.ValidateInterfaceConfigAsync(_baseAddress, _password, _localIPv4, request); _configValidated = result.Success && result.Data?.Valid == true; if (result.Data is not null) { var warnings = result.Data.Warnings.Count > 0 ? $" 警告:{string.Join(";", result.Data.Warnings)}" : string.Empty; var errors = result.Data.Errors.Count > 0 ? $" 错误:{string.Join(";", result.Data.Errors)}" : string.Empty; ShowStatusMessage(result.Success ? $"校验通过。{warnings}" : $"校验失败。{errors}{warnings}"); } else { ShowStatusMessage($"校验失败:{result.Message}"); } ShowStatusMessage(_configValidated ? "配置已通过校验,可提交应用。" : "当前配置尚未通过校验。"); UpdateButtonStates(); } private async void ApplyConfigButton_OnClick(object sender, RoutedEventArgs e) { if (RemoteTargetInterfaceComboBox.SelectedItem is not RemoteInterfaceInfo selected) { return; } var request = BuildConfigRequest(selected.SystemName); if (request is null) { return; } var confirmMessage = $"将要把以下配置应用到接口 {selected.SystemName}:\n\n" + $"IP:{request.IP}/{request.Prefix}\n" + $"网关:{(string.IsNullOrWhiteSpace(request.Gateway) ? "无" : request.Gateway)}\n" + $"DNS:{(request.Dns.Count == 0 ? "无" : string.Join(", ", request.Dns))}\n\n" + "请确认是否继续。"; if (MessageBox.Show(this, confirmMessage, "确认应用配置", MessageBoxButton.OKCancel, MessageBoxImage.Question) != MessageBoxResult.OK) { return; } var applyResult = await _agentApiService.ApplyInterfaceConfigAsync(_baseAddress, _password, _localIPv4, request); if (!applyResult.Success || applyResult.Data is null) { ShowStatusMessage($"提交配置任务失败:{applyResult.Message}"); return; } ShowStatusMessage($"配置任务已提交:{applyResult.Data.TaskId},正在轮询状态。"); await PollTaskAsync(applyResult.Data.TaskId); } private async Task PollTaskAsync(string taskId) { var transientFailureCount = 0; for (var i = 0; i < 20; i++) { await Task.Delay(1000); var result = await _agentApiService.GetTaskAsync(_baseAddress, _password, _localIPv4, taskId); if (!result.Success || result.Data is null) { if (result.StatusCode is null) { transientFailureCount++; ShowStatusMessage($"任务 {taskId} 轮询中,检测到短暂断连,正在重试({transientFailureCount})。"); continue; } ShowStatusMessage($"读取任务状态失败:{result.Message}"); return; } transientFailureCount = 0; var task = result.Data; ShowStatusMessage($"任务 {task.TaskId} / {task.Status} / {task.Step} / {task.Detail}"); if (task.Status is "success" or "failed" or "rolled_back") { if (RemoteTargetInterfaceComboBox.SelectedItem is RemoteInterfaceInfo selected) { await LoadRemoteInterfaceConfigAsync(selected.SystemName); } return; } } ShowStatusMessage($"任务 {taskId} 轮询超时,请稍后手动刷新。"); } private async void RebootButton_OnClick(object sender, RoutedEventArgs e) { await ExecuteSystemActionAsync( "重启设备", "设备将立即重启,当前窗口和连接可能马上中断。是否继续?", () => _agentApiService.RebootAsync(_baseAddress, _password, _localIPv4)); } private async void ShutdownButton_OnClick(object sender, RoutedEventArgs e) { await ExecuteSystemActionAsync( "关闭设备", "设备将立即关机,当前窗口和连接可能马上中断。是否继续?", () => _agentApiService.ShutdownAsync(_baseAddress, _password, _localIPv4)); } private async Task ExecuteSystemActionAsync(string title, string confirmMessage, Func>> action) { if (MessageBox.Show(this, confirmMessage, title, MessageBoxButton.OKCancel, MessageBoxImage.Warning) != MessageBoxResult.OK) { return; } var result = await action(); if (!result.Success || result.Data is null) { ShowStatusMessage($"{title}失败:{result.Message}"); return; } ShowStatusMessage($"{title}任务已提交:{result.Data.TaskId}。命令已发出,设备可能立即断开。"); } private RemoteInterfaceConfig? BuildConfigRequest(string interfaceName) { if (string.IsNullOrWhiteSpace(NewIpTextBox.Text)) { ShowStatusMessage("IP 地址不能为空。"); return null; } if (!TryMaskToPrefix(NewMaskTextBox.Text, out var prefix)) { ShowStatusMessage("子网掩码格式不正确。"); return null; } var dns = string.IsNullOrWhiteSpace(NewDnsTextBox.Text) ? Array.Empty() : new[] { NewDnsTextBox.Text.Trim() }; return new RemoteInterfaceConfig { Interface = interfaceName, IP = NewIpTextBox.Text.Trim(), Prefix = prefix, Gateway = NewGatewayTextBox.Text.Trim(), Dns = dns, }; } private static string PrefixToMask(int prefix) { if (prefix < 0 || prefix > 32) { return string.Empty; } var mask = prefix == 0 ? 0u : uint.MaxValue << (32 - prefix); return string.Join('.', new[] { (mask >> 24) & 255, (mask >> 16) & 255, (mask >> 8) & 255, mask & 255 }); } private static bool TryMaskToPrefix(string maskText, out int prefix) { prefix = 0; if (string.IsNullOrWhiteSpace(maskText)) { return false; } var parts = maskText.Trim().Split('.'); if (parts.Length != 4) { return false; } uint mask = 0; foreach (var part in parts) { if (!byte.TryParse(part, out var octet)) { return false; } mask = (mask << 8) | octet; } var seenZero = false; for (var i = 31; i >= 0; i--) { var bit = (mask & (1u << i)) != 0; if (bit && seenZero) { return false; } if (bit) { prefix++; } else { seenZero = true; } } return true; } private void ConfigInputChanged_OnChanged(object sender, TextChangedEventArgs e) { if (_suppressConfigChangeHandling) { return; } _configValidated = false; ShowStatusMessage("配置内容已变更,请重新点击“2. 校验配置”。"); UpdateButtonStates(); } private void ShowStatusMessage(string message) { ApplyStatusMessageStyle(message); StatusMessageTextBlock.Text = message; StatusMessageBorder.Opacity = 0; StatusMessageBorder.Visibility = Visibility.Visible; StatusMessageBorder.BeginAnimation(OpacityProperty, new DoubleAnimation(1, TimeSpan.FromMilliseconds(160))); _statusMessageCts?.Cancel(); _statusMessageCts = new CancellationTokenSource(); _ = HideStatusMessageAsync(_statusMessageCts.Token); } private async Task HideStatusMessageAsync(CancellationToken cancellationToken) { try { await Task.Delay(3000, cancellationToken); await Dispatcher.InvokeAsync(() => { var animation = new DoubleAnimation(0, TimeSpan.FromMilliseconds(200)); animation.Completed += (_, _) => { if (!cancellationToken.IsCancellationRequested) { StatusMessageBorder.Visibility = Visibility.Collapsed; } }; StatusMessageBorder.BeginAnimation(OpacityProperty, animation); }); } catch (TaskCanceledException) { } } private void ApplyStatusMessageStyle(string message) { var (background, foreground) = GetStatusMessageBrushes(message); StatusMessageBorder.Background = background; StatusMessageTextBlock.Foreground = foreground; } private static (Brush Background, Brush Foreground) GetStatusMessageBrushes(string message) { if (ContainsAny(message, "失败", "错误", "拒绝", "超时", "不能为空", "不正确", "无法")) { return (new SolidColorBrush((Color)ColorConverter.ConvertFromString("#B91C1C")), Brushes.White); } if (ContainsAny(message, "未发现", "请", "重试", "警告", "需要")) { return (new SolidColorBrush((Color)ColorConverter.ConvertFromString("#C2410C")), Brushes.White); } if (ContainsAny(message, "成功", "已切换", "已刷新", "已读取", "已加载", "已发现", "已提交", "已回填")) { return (new SolidColorBrush((Color)ColorConverter.ConvertFromString("#047857")), Brushes.White); } return (new SolidColorBrush((Color)ColorConverter.ConvertFromString("#111827")), Brushes.White); } private static bool ContainsAny(string message, params string[] markers) { return markers.Any(marker => message.Contains(marker, StringComparison.Ordinal)); } private void UpdateButtonStates() { ReloadInterfaceConfigButton.IsEnabled = RemoteTargetInterfaceComboBox.SelectedItem is RemoteInterfaceInfo; ValidateConfigButton.IsEnabled = RemoteTargetInterfaceComboBox.SelectedItem is RemoteInterfaceInfo; ApplyConfigButton.IsEnabled = _configValidated && RemoteTargetInterfaceComboBox.SelectedItem is RemoteInterfaceInfo; } }