RobotConfigAddOrEditVM.cs 2.75 KB
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using HHECS.RobotTool.Model;
using HHECS.RobotTool.View.RobotConfigView;
using MessageBox = HandyControl.Controls.MessageBox;

namespace HHECS.RobotTool.ViewModel.RobotConfigVM
{
    internal partial class RobotConfigAddOrEditVM : ObservableObject
    {
        [ObservableProperty]
        private RobotConfig robotConfig = new RobotConfig();

        [ObservableProperty]
        private bool isEdit;

        private readonly IFreeSql _freeSql;

        public RobotConfigAddOrEditView Owner { get; set; } = null!;

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

        public void InitialData(int? robotConfigId = null)
        {
            try
            {
                if (robotConfigId != null)
                {
                    Owner.Title = "修改基础配置";
                    IsEdit = true;
                    var result = _freeSql.Queryable<RobotConfig>().Where(x => x.Id == robotConfigId).First();
                    if (result == null)
                    {
                        MessageBox.Error($"为查询到Id为“{robotConfigId}”的数据!");
                        return;
                    }
                    RobotConfig = result;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Error($"获取Id为“{robotConfigId}”的配置数据失败:{ex.Message}");
            }
        }

        [RelayCommand]
        public void Save()
        {
            try
            {
                if (string.IsNullOrWhiteSpace(RobotConfig.Code))
                {
                    MessageBox.Warning($"编号不能为空!");
                    return;
                }

                if (string.IsNullOrWhiteSpace(RobotConfig.Name))
                {
                    MessageBox.Warning($"名称不能为空!");
                    return;
                }

                //新增
                if (!IsEdit)
                {
                    RobotConfig.Created = DateTime.Now;
                    _freeSql.Insert(RobotConfig).ExecuteAffrows();
                }
                //修改
                else
                {
                    RobotConfig.Updated = DateTime.Now;
                    _freeSql.Update<RobotConfig>().SetSource(RobotConfig).ExecuteAffrows();
                }

                Owner.DialogResult = true;
                MessageBox.Success($"操作成功");
            }
            catch (Exception ex)
            {
                MessageBox.Error($"操作失败:{ex.Message}");
            }
        }

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