PIbd-42_Kashin_M.I_CPO_Cour.../EmployeeManagmentView/Employee/Vacation/AddVacationWindow.xaml.cs

173 lines
6.8 KiB
C#
Raw Normal View History

using EmployeeManagmentBusinessLogic.BusinessLogic;
using EmployeeManagmentContracts.BusinessLogicContracts;
using EmployeeManagmentContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace EmployeeManagmentView.Employee.Vacation
{
/// <summary>
/// Логика взаимодействия для AddVacationWindow.xaml
/// </summary>
public partial class AddVacationWindow : Window
{
private readonly IVacationLogic _vacationLogic;
private readonly IEmployeeLogic _employeeLogic;
private readonly IPhisicalPersonLogic _phisicalPersonLogic;
private List<EmployeeViewModel> _employees;
public AddVacationWindow(IVacationLogic vacationLogic, IEmployeeLogic employeeLogic, IPhisicalPersonLogic phisicalPersonLogic)
{
_vacationLogic = vacationLogic;
_employeeLogic = employeeLogic;
_phisicalPersonLogic = phisicalPersonLogic;
InitializeComponent();
LoadEmployees();
}
private void LoadEmployees()
{
_employees = _employeeLogic.GetFullList();
// Заполняем комбинированное свойство, если нужно
foreach (var employee in _employees)
{
var physicalPerson = _phisicalPersonLogic.GetElement(employee.PhysicalPersonsId ?? 0);
employee.PhysicalPersonName = physicalPerson?.FullNameWithBirthday;
}
EmployeeComboBox.ItemsSource = _employees;
EmployeeComboBox.DisplayMemberPath = "DisplayText"; // Используем новое свойство
EmployeeComboBox.SelectedValuePath = "Id";
}
private void NameTextBox_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
{
// Разрешаем только буквы
e.Handled = !char.IsLetter(e.Text, 0);
}
private void NameTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
var textBox = sender as TextBox;
if (textBox == null) return;
// Получаем текущий текст
string currentText = textBox.Text;
// Если текст не пустой, преобразуем первую букву в заглавную, а остальные в строчные
if (!string.IsNullOrEmpty(currentText))
{
// Разбиваем строку по пробелам, чтобы обрабатывать каждое слово отдельно
var words = currentText.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < words.Length; i++)
{
// Преобразуем первую букву в заглавную, а остальные в строчные
words[i] = char.ToUpper(words[i][0]) + words[i].Substring(1).ToLower();
}
// Объединяем слова обратно в строку и обновляем текст
textBox.Text = string.Join(" ", words);
// Устанавливаем курсор в конец текста
textBox.SelectionStart = textBox.Text.Length;
}
}
private void TelephoneTextBox_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
{
e.Handled = !char.IsDigit(e.Text, 0);
}
private void TelephoneTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
var textBox = sender as TextBox;
if (textBox == null) return;
// Удаляем все символы, кроме цифр
string rawInput = new string(textBox.Text.Where(char.IsDigit).ToArray());
// Добавляем "7" по умолчанию
if (!rawInput.StartsWith("7"))
rawInput = "7" + rawInput;
if (rawInput.Length > 11) rawInput = rawInput.Substring(0, 11);
// Форматируем как +7 (XXX) XXX-XX-XX
if (rawInput.Length <= 1)
textBox.Text = "+7 ";
else if (rawInput.Length <= 4)
textBox.Text = $"+7 ({rawInput.Substring(1)}";
else if (rawInput.Length <= 7)
textBox.Text = $"+7 ({rawInput.Substring(1, 3)}) {rawInput.Substring(4)}";
else if (rawInput.Length <= 9)
textBox.Text = $"+7 ({rawInput.Substring(1, 3)}) {rawInput.Substring(4, 3)}-{rawInput.Substring(7)}";
else
textBox.Text = $"+7 ({rawInput.Substring(1, 3)}) {rawInput.Substring(4, 3)}-{rawInput.Substring(7, 2)}-{rawInput.Substring(9)}";
// Устанавливаем курсор в конец
textBox.SelectionStart = textBox.Text.Length;
}
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
bool isValid = true;
if (!StartDatePicker.SelectedDate.HasValue)
{
isValid = false;
MessageBox.Show("Поле 'Начало отпуска' не выбрано.");
}
if (!EndDatePicker.SelectedDate.HasValue)
{
isValid = false;
MessageBox.Show("Поле 'Конец отпуска' не выбрано.");
}
if (EmployeeComboBox.SelectedItem == null)
{
isValid = false;
MessageBox.Show("Поле 'Сотрудник' не выбрано.");
}
// Если все поля заполнены, продолжаем выполнение
if (isValid)
try
{
var vacation = new VacationViewModel
{
StartData = StartDatePicker.SelectedDate.Value.ToUniversalTime(),
EndData = EndDatePicker.SelectedDate.Value.ToUniversalTime(),
Passed = PassedCheckBox.IsChecked ?? false,
EmployeeId = (int?)EmployeeComboBox.SelectedValue
};
_vacationLogic.Insert(vacation);
MessageBox.Show("Отпуск успешно сохранен!");
Close();
}
catch (Exception ex)
{
MessageBox.Show($"Ошибка: {ex.Message}");
}
}
}
}