using esoft.Class;
using esoft.Entities;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
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.Navigation;
using System.Windows.Shapes;

namespace esoft.Pages
{
    /// <summary>
    /// Логика взаимодействия для EditPriceCoefficient.xaml
    /// </summary>
    public partial class EditPriceCoefficient : Page
    {
        ActualContext actualContext = new ActualContext();
        List<CoefficientFill> coefficientContext = new List<CoefficientFill>();
        private CoefficientFill selectedCoefficient;
        private ExecuterFill selectedExecuter;
        private bool isEditing = false;

        public EditPriceCoefficient(ExecuterFill executer)
        {
            InitializeComponent();
            selectedExecuter = executer;
            if (selectedExecuter.ManagerID != 0)  // Используйте 0, если ID имеет тип int
            {
                isEditing = true;
            }
            FillForm();
            LoadUserRule(selectedExecuter);
        }

        private void FillForm()
        {
            selectedCoefficient = CoefficientFill.CoefficientFills(selectedExecuter.ManagerID);

            if (isEditing && selectedCoefficient != null)
            {
                try
                {
                    // Получаем всех пользователей, которых связывает ID
                    var usersManager = actualContext.Users.Where(user => actualContext.Manager
                        .Any(manager => selectedCoefficient.ID == user.ID)).ToList();
                    cbManager.ItemsSource = UserInFIO.GroupUser(usersManager);
                    cbManager.SelectedItem = UserInFIO.SoloUser(usersManager
                        .FirstOrDefault(u => u.ID == selectedCoefficient.ID));


                    // Заполняем остальные поля формы
                    IUDJuniorMin.Value = selectedCoefficient.JuniorMinimum;
                    IUDMiddleMin.Value = selectedCoefficient.MiddleMinimum;
                    IUDSeniorMin.Value = selectedCoefficient.SeniorMinimum;
                    TBoxAnalysisCoefficient.Text = selectedCoefficient.AnalysisCoefficient.ToString();
                    TBoxInstallationCoefficient.Text = selectedCoefficient.InstallationCoefficient.ToString();
                    TBoxSupportCoefficient.Text = selectedCoefficient.SupportCoefficient.ToString();
                    TBoxTimeCoefficient.Text = selectedCoefficient.TimeCoefficient.ToString();
                    TBoxDifficultyCoefficient.Text = selectedCoefficient.DifficultyCoefficient.ToString();
                    TBoxToMoneyCoefficient.Text = selectedCoefficient.ToMoneyCoefficient.ToString();

                    if (selectedExecuter.Grade == "junior")
                    {
                        TBlockTotalSalary.Text = selectedCoefficient.JuniorMinimum.ToString();
                    }
                    else if (selectedExecuter.Grade == "middle")
                    {
                        TBlockTotalSalary.Text = selectedCoefficient.MiddleMinimum.ToString();
                    }
                    else if (selectedExecuter.Grade == "senior")
                    {
                        TBlockTotalSalary.Text = selectedCoefficient.SeniorMinimum.ToString();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Ошибка при заполнении формы: {ex.Message}",
                                    "Ошибка",
                                    MessageBoxButton.OK,
                                    MessageBoxImage.Error);
                }
            }
        }

        private void LoadUserRule(ExecuterFill selectedExecutor)
        {

            var currentUser = GetCurrent.CurrentUser;
            var isManager = actualContext.Manager.Any(manager => manager.ID == currentUser.ID);

            if (isManager)
            {
                IUDJuniorMin.IsReadOnly = false;
                IUDMiddleMin.IsReadOnly = false;
                IUDSeniorMin.IsReadOnly = false;

                TBoxAnalysisCoefficient.IsReadOnly = false;
                TBoxInstallationCoefficient.IsReadOnly = false;
                TBoxSupportCoefficient.IsReadOnly = false;
                TBoxTimeCoefficient.IsReadOnly = false;
                TBoxDifficultyCoefficient.IsReadOnly = false;
                TBoxToMoneyCoefficient.IsReadOnly = false;

                cbManager.IsEnabled = true;

                BtnSaveSalaryCoeff.IsEnabled = true;
            }
            else // Если текущий пользователь - исполнитель
            {
                IUDJuniorMin.IsReadOnly = true;
                IUDMiddleMin.IsReadOnly = true;
                IUDSeniorMin.IsReadOnly = true;

                TBoxAnalysisCoefficient.IsReadOnly = true;
                TBoxInstallationCoefficient.IsReadOnly = true;
                TBoxSupportCoefficient.IsReadOnly = true;
                TBoxTimeCoefficient.IsReadOnly = true;
                TBoxDifficultyCoefficient.IsReadOnly = true;
                TBoxToMoneyCoefficient.IsReadOnly = true;

                cbManager.IsEnabled = false;

                BtnSaveSalaryCoeff.IsEnabled = false;
            }
        }

        private void BtnSaveSalaryCoeff_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Создаем экземпляр контекста данных
                ActualContext actualContext = new ActualContext();
                var context = esoftEntities.GetContext();

                // Получаем значения из элементов управления
                int juniorMinimum = (int)IUDJuniorMin.Value;
                int middleMinimum = (int)IUDMiddleMin.Value;
                int seniorMinimum = (int)IUDSeniorMin.Value;
                double analysisCoefficient = double.Parse(TBoxAnalysisCoefficient.Text);
                double installationCoefficient = double.Parse(TBoxInstallationCoefficient.Text);
                double supportCoefficient = double.Parse(TBoxSupportCoefficient.Text);
                double timeCoefficient = double.Parse(TBoxTimeCoefficient.Text);
                double difficultyCoefficient = double.Parse(TBoxDifficultyCoefficient.Text);
                double toMoneyCoefficient = double.Parse(TBoxToMoneyCoefficient.Text);

                var existingCoefficient = context.Manager.FirstOrDefault(t => t.ID == selectedCoefficient.ID);

                // Присваиваем свойствам объекта значения из элементов управления
                existingCoefficient.JuniorMinimum = juniorMinimum;
                existingCoefficient.MiddleMinimum = middleMinimum;
                existingCoefficient.SeniorMinimum = seniorMinimum;
                existingCoefficient.AnalysisCoefficient = analysisCoefficient;
                existingCoefficient.InstallationCoefficient = installationCoefficient;
                existingCoefficient.SupportCoefficient = supportCoefficient;
                existingCoefficient.TimeCoefficient = timeCoefficient;
                existingCoefficient.DifficultyCoefficient = difficultyCoefficient;
                existingCoefficient.ToMoneyCoefficient = toMoneyCoefficient;

                context.SaveChanges();

                MessageBoxResult result = MessageBox.Show("Коэффициенты успешно изменены!", "Успех", MessageBoxButton.OK, MessageBoxImage.Information);
                if (result == MessageBoxResult.OK)
                {
                    NavigationService.GoBack();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка при сохранении данных: {ex.Message}", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

    }
}
