2024-11-08 18:03:17 +04:00

82 lines
2.7 KiB
C#

using ProjectGasStation.Entities;
using ProjectGasStation.Entities.Enums;
using ProjectGasStation.Repositories;
using ProjectGasStation.Repositories.Implementations;
namespace ProjectGasStation.Forms;
public partial class FormShift : Form
{
public readonly IShiftRepository _shiftRepository;
private int? _shiftId;
public int Id
{
set
{
try
{
var shift = _shiftRepository.ReadShiftById(value);
if (shift == null)
{
throw new InvalidDataException(nameof(shift));
}
dateTimePickerStart.Value = shift.Date.Date + shift.StartTime;
dateTimePickerEnd.Value = shift.Date.Date + shift.EndTime;
dateTimePickerDate.Value = shift.Date.Date;
comboBoxType.SelectedItem = shift.Type;
_shiftId = shift.Id;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
public FormShift(IShiftRepository shiftRepository)
{
InitializeComponent();
_shiftRepository = shiftRepository ?? throw new ArgumentNullException(nameof(shiftRepository));
comboBoxType.DataSource = Enum.GetValues(typeof(ShiftType));
}
private void buttonSave_Click(object sender, EventArgs e)
{
try
{
if (comboBoxType.SelectedIndex < 1)
{
throw new Exception("Имеются незаполненные поля");
}
if (_shiftId.HasValue)
{
_shiftRepository.UpdateShift(CreateShift(_shiftId.Value));
}
else
{
_shiftRepository.CreateShift(CreateShift(0));
}
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonCancel_Click(object sender, EventArgs e) => Close();
private Shift CreateShift(int id)
{
var startTime = dateTimePickerStart.Value.TimeOfDay;
var endTime = dateTimePickerEnd.Value.TimeOfDay;
var startTimeRounded = new TimeSpan(startTime.Hours, startTime.Minutes, startTime.Seconds);
var endTimeRounded = new TimeSpan(endTime.Hours, endTime.Minutes, endTime.Seconds);
return Shift.CreateShift(id, startTimeRounded, endTimeRounded, dateTimePickerDate.Value.Date, (ShiftType)comboBoxType.SelectedItem!);
}
}