PIbd-42_Kashin_M.I_CPO_Cour.../EmployeeManagmentView/Employee/Salary/AddSalaryWindow.xaml.cs

228 lines
9.1 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using EmployeeManagmentContracts.BusinessLogicContracts;
using EmployeeManagmentContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
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.Salary
{
/// <summary>
/// Логика взаимодействия для AddSalaryWindow.xaml
/// </summary>
public partial class AddSalaryWindow : Window
{
private readonly ISalaryLogic _salaryLogic;
private readonly IEmployeeLogic _employeeLogic;
private readonly IPhisicalPersonLogic _phisicalPersonLogic;
private List<EmployeeViewModel> _employees;
public AddSalaryWindow(ISalaryLogic salaryLogic, IEmployeeLogic employeeLogic, IPhisicalPersonLogic phisicalPersonLogic)
{
_salaryLogic = salaryLogic;
_employeeLogic = employeeLogic;
_phisicalPersonLogic = phisicalPersonLogic;
InitializeComponent();
LoadEmployees();
}
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 DecimalTextBox_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
{
var textBox = sender as TextBox;
if (textBox == null) return;
// Разрешаем только цифры и запятую
e.Handled = !(char.IsDigit(e.Text, 0) || e.Text == ",");
// Проверка на количество запятых
if (e.Text == "," && textBox.Text.Contains(","))
{
e.Handled = true;
}
}
private void NumericTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
// Разрешаем ввод только цифр и запятой
e.Handled = !char.IsDigit(e.Text, 0);
}
// Ограничение на 2 знака после запятой
private void DecimalTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
var textBox = sender as TextBox;
if (textBox == null) return;
// Получаем текущий текст
string currentText = textBox.Text;
// Проверяем наличие запятой
int commaIndex = currentText.IndexOf(',');
if (commaIndex != -1 && currentText.Length - commaIndex > 3)
{
// Обрезаем текст до двух знаков после запятой
textBox.Text = currentText.Substring(0, commaIndex + 3);
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 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 SaveButton_Click(object sender, RoutedEventArgs e)
{
bool isValid = true;
// Проверка обязательных полей
if (string.IsNullOrWhiteSpace(HoursTextBox.Text))
{
isValid = false;
MessageBox.Show("Поле 'Название должности' не заполнено.");
}
if (string.IsNullOrWhiteSpace(PriceTextBox.Text))
{
isValid = false;
MessageBox.Show("Поле 'Совместительство' не заполнено.");
}
if (string.IsNullOrWhiteSpace(PremiumTextBox.Text))
{
isValid = false;
MessageBox.Show("Поле 'Ставка' не заполнено.");
}
if (!DatePicker.SelectedDate.HasValue)
{
isValid = false;
MessageBox.Show("Поле 'Дата зарплаты' не выбрано.");
}
if (EmployeeComboBox.SelectedItem == null)
{
isValid = false;
MessageBox.Show("Поле 'Сотрудник' не выбрано.");
}
// Если все поля заполнены, продолжаем выполнение
if (isValid)
try
{
var salary = new SalaryViewModel
{
CountHours = int.Parse(HoursTextBox.Text),
PriceHour = float.Parse(PriceTextBox.Text),
Premium = string.IsNullOrEmpty(PremiumTextBox.Text) ? null : float.Parse(PremiumTextBox.Text),
Date = DatePicker.SelectedDate.Value.ToUniversalTime(),
EmployeeId = (int?)EmployeeComboBox.SelectedValue
};
_salaryLogic.Insert(salary);
MessageBox.Show("Зарплата успешно сохранена!");
Close();
}
catch (Exception ex)
{
MessageBox.Show($"Ошибка: {ex.Message}");
}
}
}
}