using DeviceService.Core;
using DeviceService.Device;
using System.Windows;
using System.Windows.Controls;
namespace DeviceService;
///
/// 添加设备弹窗:从 AllDeviceType 中选择设备类型,
/// 选型后在下方加载该设备类型对应的配置 UserControl,确定后交回设备实例。
///
public partial class AddDeviceWindow : Window
{
private IDevice? _device;
/// 点击确定后返回待添加的设备实例;取消时为 null。
public IDevice? Device { get; private set; }
public AddDeviceWindow()
{
InitializeComponent();
TypeCombo.ItemsSource = DeviceHelper.AllDeviceType;
}
private void TypeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
_device = null;
ControlHost.Content = null;
if (TypeCombo.SelectedItem is string type
&& DeviceHelper.TryCreateDevice(type, out IDevice? device)
&& device != null)
{
// 默认 Id:类型名-序号,可在配置控件中看到
int seq = DeviceManager.Devices.Count(d => d.Type == type) + 1;
SetDeviceId(device, $"{type}-{seq}");
_device = device;
UserControl? control = DeviceConfigControlFactory.Create(device);
if (control == null)
{
ControlHost.Content = new TextBlock
{
Text = $"未找到 {device.GetType().Name}ConfigControl,该设备类型暂无配置界面。",
Margin = new Thickness(8),
TextWrapping = TextWrapping.Wrap,
TextAlignment = TextAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
};
}
else
{
control.DataContext = device;
ControlHost.Content = control;
}
}
OkButton.IsEnabled = _device != null;
}
private void OkButton_Click(object sender, RoutedEventArgs e)
{
if (_device == null)
{
return;
}
string id = _device.DeviceId;
if (string.IsNullOrWhiteSpace(id))
{
MessageBox.Show(this, "设备 ID 不能为空。", "添加设备",
MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
if (DeviceManager.Devices.Any(d => d.DeviceId == id))
{
MessageBox.Show(this, $"设备 ID \"{id}\" 已存在,请修改后重试。", "添加设备",
MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
Device = _device;
DialogResult = true;
}
private void CancelButton_Click(object sender, RoutedEventArgs e)
{
DialogResult = false;
}
/// IDevice 接口只暴露 Id getter,实际实现类一般有 setter,通过反射赋值。
private static void SetDeviceId(IDevice device, string id)
{
device.GetType().GetProperty(nameof(IDevice.DeviceId))?.SetValue(device, id);
}
}