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 { /// /// Логика взаимодействия для EditSalaryWindow.xaml /// public partial class EditSalaryWindow : Window { private readonly ISalaryLogic _salaryLogic; // Логика для работы с зарплатами private readonly IEmployeeLogic _employeeLogic; // Логика для работы с сотрудниками private readonly IPhisicalPersonLogic _phisicalPersonLogic; private List _salaries; private List _employees; // Список сотрудников public EditSalaryWindow(ISalaryLogic salaryLogic, IEmployeeLogic employeeLogic, IPhisicalPersonLogic phisicalPersonLogic) { _salaryLogic = salaryLogic; _employeeLogic = employeeLogic; _phisicalPersonLogic = phisicalPersonLogic; InitializeComponent(); LoadSalaries(); } private void LoadSalaries() { _salaries = _salaryLogic.GetFullList(); SalaryComboBox.ItemsSource = _salaries; SalaryComboBox.DisplayMemberPath = "EmployeeName"; SalaryComboBox.SelectedValuePath = "Id"; } private void SalaryComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (SalaryComboBox.SelectedValue is int selectedSalaryId) { LoadSalary(selectedSalaryId); } } private void LoadSalary(int salaryId) { var salary = _salaryLogic.GetElement(salaryId); if (salary != null) { CountHoursTextBox.Text = salary.CountHours.ToString(); PriceHourTextBox.Text = salary.PriceHour.ToString(); PremiumTextBox.Text = salary.Premium?.ToString() ?? string.Empty; DatePicker.SelectedDate = salary.Date; PassedCheckBox.IsChecked = salary.Passed; } else { MessageBox.Show("Зарплата не найдена", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error); } } private void SearchTextBox_TextChanged(object sender, TextChangedEventArgs e) { var searchText = SearchTextBox.Text.ToLower(); var filteredSalaries = _salaries .Where(sal => sal.EmployeeName.ToLower().Contains(searchText)) .ToList(); SalaryComboBox.ItemsSource = filteredSalaries; } 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 SaveButton_Click(object sender, RoutedEventArgs e) { try { if (SalaryComboBox.SelectedValue is int selectedSalaryId) { var updatedSalary = new SalaryViewModel { Id = selectedSalaryId, CountHours = int.Parse(CountHoursTextBox.Text), PriceHour = float.Parse(PriceHourTextBox.Text), Premium = float.TryParse(PremiumTextBox.Text, out var premium) ? premium : (float?)null, Date = DatePicker.SelectedDate.Value.ToUniversalTime(), Passed = PassedCheckBox.IsChecked ?? false, }; _salaryLogic.Update(updatedSalary); MessageBox.Show("Зарплата успешно обновлена!"); this.Close(); } else { MessageBox.Show("Выберите зарплату перед сохранением!", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Warning); } } catch (Exception ex) { MessageBox.Show($"Ошибка при сохранении данных: {ex.Message}", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error); } } } }