EquipmentAddVM.cs 2.87 KB
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using HHECS.DAQClient.DataAccess;
using HHECS.EquipmentModel;
using System.Collections.ObjectModel;
using MessageBox = HandyControl.Controls.MessageBox;

namespace HHECS.DAQClient.ViewModel.EquipmentVM
{
    public partial class EquipmentAddVM : ObservableObject
    {
        [ObservableProperty]
        private Equipment equipment = new Equipment();

        [ObservableProperty]
        private ObservableCollection<EquipmentType> equipmentTypes = new ObservableCollection<EquipmentType>();

        private readonly DataContext _context;

        public EquipmentAddVM(DataContext context)
        {
            _context = context;
            InitialData();
        }

        private void InitialData()
        {
            try
            {
                var result = _context.EquipmentType.Where(x => true).ToList();
                EquipmentTypes = new ObservableCollection<EquipmentType>(result);
            }
            catch (Exception ex)
            {
                MessageBox.Error($"加载数据失败.{ex.Message}");
            }
        }

        [RelayCommand]
        public void Save()
        {
            try
            {
                if (Equipment.EquipmentTypeId == default)
                {
                    MessageBox.Warning($"请选择设备类型!");
                    return;
                }

                var equipmentPropTemps = _context.EquipmentTypePropTemplate.Where(x => x.EquipmentTypeId == Equipment.EquipmentTypeId).ToList();
                if (equipmentPropTemps.Count == 0)
                {
                    MessageBox.Warning($"当前选择的设备类型模板数据为空!");
                    return;
                }

                Equipment.Created = DateTime.Now;
                _context.Equipment.Add(Equipment);
                _context.SaveChanges();

                var equipmentId = _context.Equipment.Where(x => x.Code == Equipment.Code).First(x => x.Id);
                var equipmentProps = equipmentPropTemps.Select(x => new EquipmentProp
                {
                    EquipmentId = equipmentId,
                    EquipmentTypePropTemplateId = x.Id,
                    EquipmentTypePropTemplateCode = x.Code,
                    ServerHandle = 0,
                    Address = x.Address,
                    Value = string.Empty,
                    Remark = x.Name,
                    Created = DateTime.Now,
                }).ToList();
                _context.EquipmentProp.AddRange(equipmentProps);
                _context.SaveChanges();
                MessageBox.Success($"新增设备数据成功");
            }
            catch (Exception ex)
            {
                MessageBox.Error($"新增数据失败.{ex.Message}");
            }
        }

        [RelayCommand]
        public void Cancel()
        {

        }
    }
}