CommunicationAddOrEditVM.cs 2.35 KB
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using HHECS.DAQClient.Model;
using System.Windows;
using MessageBox = HandyControl.Controls.MessageBox;

namespace HHECS.DAQClient.ViewModel.CommunicationVM
{
    public partial class CommunicationAddOrEditVM : ObservableObject
    {
        [ObservableProperty]
        private CommunicationConfig communicationConfig = new CommunicationConfig();

        [ObservableProperty]
        private Dictionary<string, CommunicationTypeConst> communicationTypes = new Dictionary<string, CommunicationTypeConst>();

        public Window Owner { get; set; }

        private bool IsEdit = false;

        private readonly IFreeSql _freeSql;

        public CommunicationAddOrEditVM(IFreeSql freeSql)
        {
            _freeSql = freeSql;
        }

        public void InitialData(int? communicationConfigId = null)
        {
            try
            {
                CommunicationTypes = Enum.GetNames<CommunicationTypeConst>().ToDictionary(x => x, Enum.Parse<CommunicationTypeConst>);
                if (communicationConfigId != null)
                {
                    Owner.Title = "修改通讯配置";
                    IsEdit = true;
                    CommunicationConfig = _freeSql.Queryable<CommunicationConfig>().Where(x => x.Id.Equals(communicationConfigId)).First();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Error($"初始化数据失败.{ex.Message}");
            }
        }

        [RelayCommand]
        public void Save()
        {
            try
            {
                if (!IsEdit)
                {
                    CommunicationConfig.CreateTime = DateTime.Now;
                    _freeSql.Insert(CommunicationConfig).ExecuteAffrows();
                }
                else
                {
                    _freeSql.Update<CommunicationConfig>().Set(x => x.UpdatedTime, DateTime.Now).Where(x => x.Id == CommunicationConfig.Id).ExecuteAffrows();
                }
                Owner.DialogResult = true;
                MessageBox.Success("操作成功");
            }
            catch (Exception ex)
            {
                MessageBox.Error($"操作失败.{ex.Message}");
            }
        }

        [RelayCommand]
        public void Cancel()
        {
            Owner.Close();
        }
    }
}