Untitled

 avatar
unknown
plain_text
a year ago
19 kB
4
Indexable
using OdzialSpecjalny.Entities;

namespace OdzialSpecjalny
{
    public partial class OdzialSpecjalny : Form
    {
        private List<Szpital> StoreSzpitals = [];
        private List<Oddzial> StoreOddzials = [];

        public OdzialSpecjalny()
        {
            InitializeComponent();
            Context = new PostgresContext();
            UpdateDepartmentList();
            Updater = new Thread(UpdateData);
            Updater.Start();
            CheckForIllegalCrossThreadCalls = false;
            FormClosed += ExitFunc;
        }

        PostgresContext Context;
        Thread Updater;
        bool Exiting = false;

        private void UpdateDepartmentList()
        {
            //Pobieranie listy typów oddziałów z bazy albo z istniejących szpitali
            var UpdateOddzials = Context.Oddzials;
            var result = true;
            if (StoreOddzials != null)
            {
                foreach (var oddzial in StoreOddzials)
                {
                    if (StoreOddzials.Any(item => item.TypOddzialu == oddzial.TypOddzialu))
                    {
                        result = false;
                    }
                }
            }

            if (result)
            {
                TypeBox.Items.Clear();
                StoreOddzials?.Clear();
                UpdateDepartments();
            }

        }
        private void UpdateDepartments()
        {
            foreach (Oddzial odz in Context.Oddzials)
            {
                if (!TypeBox.Items.Contains(odz.TypOddzialu))
                {
                    TypeBox.Items.Add(odz.TypOddzialu);
                    StoreOddzials.Add(odz);
                }
            }
        }
        private void UpdateData()
        {
            while (!Exiting)
            {
                UpdateDepartmentList();
                Thread.Sleep(10000);
            }
        }

        public void ExitFunc(object sender, FormClosedEventArgs e)
        {
            Exiting = true;
        }


        private void SearchButton_Click(object sender, EventArgs e)
        {

            SearchHospital();
        }
        public void SearchHospital()
        {
            using (var context = new PostgresContext())
            {
                // Get selected department type and priority
                var departmentType = TypeBox.SelectedItem;
                bool isHighPriority = HighPriority.Checked;

                // Build query based on selected criteria
                var query = context.Szpitals.AsQueryable();
                query = query.Where(s => s.Oddzials.Any(o => o.TypOddzialu == departmentType));

                if (isHighPriority)
                {
                    query = query.Where(s => s.Oddzials.Any(o =>
                        o.TypOddzialu == departmentType &&
                        o.AktualnaLiczbaZajetychMiejscRezerwowych < o.MaxLiczbaZajetychMiejscRezerwowych));
                }

                // Execute query and get list of hospitals
                var hospitals = query.ToList();

                // Clear existing controls in the panel
                DepartmentsPanel.Controls.Clear();

                // Add controls for each hospital
                foreach (var hospital in hospitals)
                {
                    var departmentControl = new DepartmentControl(hospital.Nazwa);
                    // Highlight the currently selected hospital
                    if (hospital.Nazwa == CurrentHospitalLabel.Text)
                    {
                        departmentControl.BackColor = Color.LightBlue; // Or any other color you prefer
                    }
                    DepartmentsPanel.Controls.Add(departmentControl);
                }
            }


        }
        private void CurrentHospitalSelectorButton_Click(object sender, EventArgs e)
        {
            ShowHospitalListPopupWindow();
        }

        private void UpdateHospitalList()
        {
            foreach (var szpital in Context.Szpitals)
            {
                if (!string.IsNullOrEmpty(szpital.Nazwa))
                {
                    StoreSzpitals.Add(szpital);
                }
            }

        }

        private void ShowHospitalListPopupWindow()
        {
            /// Narazie statycznie
            StoreSzpitals.Clear();
            UpdateHospitalList();


            ///

            Form popup = new Form();
            popup.FormBorderStyle = FormBorderStyle.FixedDialog;
            popup.StartPosition = FormStartPosition.CenterParent;
            popup.Width = 500;
            popup.Height = 500;

            ListBox listBox = new ListBox();
            listBox.Dock = DockStyle.Fill;
            foreach (var hospital in StoreSzpitals)
            {
                listBox.Items.Add(hospital.Nazwa);
            }
            popup.Controls.Add(listBox);

            FlowLayoutPanel buttonPanel = new FlowLayoutPanel();
            buttonPanel.Dock = DockStyle.Bottom;
            buttonPanel.Height = 75;
            buttonPanel.FlowDirection = FlowDirection.LeftToRight;
            popup.Controls.Add(buttonPanel);

            int width = (buttonPanel.Width - 18) / 2;
            int height = 50;

            Button okButton = new Button();
            okButton.Text = "OK";
            okButton.Width = width;
            okButton.Height = height;
            buttonPanel.Controls.Add(okButton);

            Button cancelButton = new Button();
            cancelButton.Text = "Anuluj";
            cancelButton.Width = width;
            cancelButton.Height = height;
            buttonPanel.Controls.Add(cancelButton);

            string startOfCurrentHospitalLabelText = "Aktualny szpital:";

            okButton.Click += (sender, e) =>
            {
                if (listBox.SelectedIndex != -1)
                {
                    string selectedHospitalName = listBox.SelectedItem.ToString();
                    CurrentHospitalLabel.Text = startOfCurrentHospitalLabelText + " " + selectedHospitalName;
                    var currentHospital = listBox.SelectedItem;
                }
                if (CurrentHospitalLabel.Text != startOfCurrentHospitalLabelText && CurrentHospitalSelectorButton.Text != "Zmień szpital")
                {
                    CurrentHospitalSelectorButton.Text = "Zmień szpital";
                }
                popup.Close();
            };

            cancelButton.Click += (sender, e) =>
            {
                popup.Close();
            };

            popup.ShowDialog();
        }




        //Dodawanie pacjenta


        //Przycisk rezerwacji
        private void ReserveButton_Click(object sender, EventArgs e)
        {
            Blad? error;
            bool success = DodajPacjenta(NameTextbox.Text, SurnameTextbox.Text, PhoneNumberTextbox.Text, PeselTexbox.Text, out error);
            if (success)
            {
                ShowConfirmationDialog();
            }
            else
            {
                //Po zlokalizowaniu błędu wyświetla komunikat gdzie był błąd
                MessageBox.Show($"Nie udało się dodać pacjenta. Błąd w: {error}");
            }
        }

        //Okno potwierdzenia
        private void ShowConfirmationDialog()
        {
            string selectedHospital = CurrentHospitalLabel.Text;
            string selectedDepartment = TypeBox.SelectedItem?.ToString() ?? "Nie wybrano";
            string priority = GetSelectedPriority();
            string birthDate = ExtractBirthDateFromPesel(PeselTexbox.Text);

            Form popup = new Form
            {
                FormBorderStyle = FormBorderStyle.FixedDialog,
                StartPosition = FormStartPosition.CenterParent,
                Width = 700,
                Height = 300
            };

            TableLayoutPanel panel = new TableLayoutPanel
            {
                Dock = DockStyle.Fill,
                ColumnCount = 2,
                RowCount = 9,
                AutoSize = true
            };

            Font largeFont = new Font(DefaultFont.FontFamily, 12, FontStyle.Regular);
            Font boldLargeFont = new Font(DefaultFont.FontFamily, 12, FontStyle.Bold);

            AddLabel(panel, "Imię:", boldLargeFont, NameTextbox.Text, largeFont, 0);
            AddLabel(panel, "Nazwisko:", boldLargeFont, SurnameTextbox.Text, largeFont, 1);
            AddLabel(panel, "Numer Telefonu:", boldLargeFont, PhoneNumberTextbox.Text, largeFont, 2);
            AddLabel(panel, "PESEL:", boldLargeFont, PeselTexbox.Text, largeFont, 3);
            AddLabel(panel, "Data Urodzenia:", boldLargeFont, birthDate, largeFont, 4);
            AddLabel(panel, "Aktualny Szpital:", boldLargeFont, selectedHospital, largeFont, 5);
            AddLabel(panel, "Oddział:", boldLargeFont, selectedDepartment, largeFont, 6);
            AddLabel(panel, "Priorytet:", boldLargeFont, priority, largeFont, 7);

            popup.Controls.Add(panel);

            FlowLayoutPanel buttonPanel = new FlowLayoutPanel
            {
                Dock = DockStyle.Bottom,
                Height = 75,
                FlowDirection = FlowDirection.LeftToRight
            };
            popup.Controls.Add(buttonPanel);

            int width = (buttonPanel.Width - 18) / 2;
            int height = 50;


            //Przycisk Potwierdzenia
            Button okButton = new Button
            {
                Text = "Potwierdź",
                Width = width,
                Height = height
            };
            buttonPanel.Controls.Add(okButton);


            //Przycisk Anulowania
            Button cancelButton = new Button
            {
                Text = "Anuluj",
                Width = width,
                Height = height
            };
            buttonPanel.Controls.Add(cancelButton);


            okButton.Click += (sender, e) =>
            {
                // Zapisz pacjenta do bazy danych
                DateTime parsedBirthDate;
                if (DateTime.TryParse(birthDate, out parsedBirthDate))
                {
                    SavePatientToDatabase(NameTextbox.Text, SurnameTextbox.Text, PhoneNumberTextbox.Text, PeselTexbox.Text, parsedBirthDate);
                    MessageBox.Show("Pacjent został dodany pomyślnie.");
                }
                else
                {
                    MessageBox.Show("Błąd podczas przetwarzania daty urodzenia.");
                }
                ClearTextboxes();
                popup.Close();
            };

            cancelButton.Click += (sender, e) =>
            {
                popup.Close();
            };

            popup.ShowDialog();
        }


        //Zapisywanie pacjenta do bazy danych
        private void SavePatientToDatabase(string firstName, string lastName, string phoneNumber, string pesel, DateTime birthDate)
        {
            using (var context = new PostgresContext())
            {
                var newPatient = new Pacjenci
                {
                    Imie = firstName,
                    Nazwisko = lastName,
                    NrTelefonu = phoneNumber,
                    Pesel = pesel,
                    DataUrodzenia = DateOnly.FromDateTime(birthDate), // Konwersja DateTime na DateOnly
                    CreatedAt = DateTime.Now
                };

                context.Pacjencis.Add(newPatient);
                context.SaveChanges();
            }
        }


        //DOdawanie etykiet do okna potwierdzenia
        private void AddLabel(TableLayoutPanel panel, string title, Font titleFont, string value, Font valueFont, int rowIndex)
        {
            Label titleLabel = new Label
            {
                Text = title,
                Font = titleFont,
                TextAlign = ContentAlignment.MiddleRight,
                Dock = DockStyle.Fill,
                AutoSize = true
            };
            Label valueLabel = new Label
            {
                Text = value,
                Font = valueFont,
                TextAlign = ContentAlignment.MiddleLeft,
                Dock = DockStyle.Fill,
                AutoSize = true
            };

            panel.Controls.Add(titleLabel, 0, rowIndex);
            panel.Controls.Add(valueLabel, 1, rowIndex);
        }


        //Przerabianie przycisków priorytetu na wartości
        private string GetSelectedPriority()
        {
            if (HighPriority.Checked)
            {
                return "Wysoki";
            }
            else if (LowPriorityButton.Checked)
            {
                return "Niski";
            }
            else if (NoPriorityButton.Checked)
            {
                return "Brak";
            }
            return "Brak";
        }
        

        //Czyszczenie textboxów po dodaniu pacjenta
        private void ClearTextboxes()
        {
            NameTextbox.Clear();
            SurnameTextbox.Clear();
            PhoneNumberTextbox.Clear();
            PeselTexbox.Clear();
        }


        //Wyciąganie daty urodzenia z peselu
        private string ExtractBirthDateFromPesel(string pesel)
        {
            if (pesel.Length != 11)
            {
                return "Invalid PESEL";
            }

            int year = int.Parse(pesel.Substring(0, 2));
            int month = int.Parse(pesel.Substring(2, 2));
            int day = int.Parse(pesel.Substring(4, 2));

            if (month > 80)
            {
                year += 1800;
                month -= 80;
            }
            else if (month > 60)
            {
                year += 2200;
                month -= 60;
            }
            else if (month > 40)
            {
                year += 2100;
                month -= 40;
            }
            else if (month > 20)
            {
                year += 2000;
                month -= 20;
            }
            else
            {
                year += 1900;
            }

            DateTime birthDate = new DateTime(year, month, day);
            return birthDate.ToString("dd.MM.yyyy");
        }



        //Enum z błędami
        enum Blad
        {
            Imie,
            Nazwisko,
            PESEL,
            NumerTelefonu,
        }

        //Sprawdzanie imienia
        static Blad? SprawdzImie(string imie)
        {
            //imie musi sie zaczynać z dużej litery i miec max 13 znaków
            if (imie.Length < 2 || imie.Length > 13)
                return Blad.Imie;
            if (!char.IsUpper(imie[0]))
                return Blad.Imie;
            if (imie.Skip(1).Any(c => char.IsUpper(c)))
                return Blad.Imie;
            if (imie.Any(char.IsDigit))
                return Blad.Imie;
            return null;
        }


        //Sprawdzanie nazwiska
        static Blad? SprawdzNazwisko(string nazwisko)
        {
            // nazwisko musi się zaczynać z dużej litery i może być dwuczłonowe, w takim wypadku pomiędzy członami musi być myślnik
            if (nazwisko.Length < 2 || nazwisko.Length > 20)
                return Blad.Nazwisko;

            string[] czlonyNazwiska = nazwisko.Split('-');

            // Sprawdzenie, czy nazwisko ma dokładnie jeden lub dwa człony
            if (czlonyNazwiska.Length < 1 || czlonyNazwiska.Length > 2)
                return Blad.Nazwisko;

            foreach (string czlon in czlonyNazwiska)
            {
                if (czlon.Length < 2) // Check if each part has at least 2 letters
                    return Blad.Nazwisko;

                if (!char.IsUpper(czlon[0]))
                    return Blad.Nazwisko;

                if (czlon.Skip(1).Any(c => char.IsUpper(c)))
                    return Blad.Nazwisko;

                if (czlon.Any(char.IsDigit))
                    return Blad.Nazwisko;
            }

            return null;
        }


        //Sprawdzanie peselu
        static Blad? SprawdzPesel(string pesel)
        {
            if (pesel.Length != 11)
                return Blad.PESEL;
            for (int i = 0; i < pesel.Length; i++)
            {
                if (!char.IsDigit(pesel[i]))
                {
                    return Blad.PESEL;
                }
            }
            int[] wagi = { 1, 3, 7, 9, 1, 3, 7, 9, 1, 3 };
            int suma = 0;
            for (int i = 0; i < 10; i++)
            {
                suma += (pesel[i] - '0') * wagi[i];
            }
            int ostatniaCyfraSuma = suma % 10;
            int cyfraKontrolna = (10 - ostatniaCyfraSuma) % 10;
            if (cyfraKontrolna == (pesel[10] - '0'))
                return null;
            else
                return Blad.PESEL;
        }


        //Sprawdzanie numeru telefonu
        static Blad? SprawdzNumerTelefonu(string numer)
        {
            if (numer.StartsWith("+"))
            {
                // Numer telefonu powinien zawierać tylko cyfry po znaku '+'
                string numerBezPlus = numer.Substring(1);
                if (!numerBezPlus.All(char.IsDigit) || numer.Length < 11 || numer.Length > 13)
                    return Blad.NumerTelefonu;
            }
            else
            {
                // Numer telefonu powinien zawierać tylko cyfry i mieć dokładnie 9 znaków
                if (numer.Length != 9 || !numer.All(char.IsDigit))
                    return Blad.NumerTelefonu;
            }
            return null;
        }


        //Walidacja pacjenta
        static bool DodajPacjenta(string imie, string nazwisko, string numerTelefonu, string pesel, out Blad? error)
        {
            error = null;
            if ((error = SprawdzImie(imie)) != null) return false;
            if ((error = SprawdzNazwisko(nazwisko)) != null) return false;
            if ((error = SprawdzPesel(pesel)) != null) return false;
            if ((error = SprawdzNumerTelefonu(numerTelefonu)) != null) return false;
            return true;

        }


        //Przyciski priorytetu
        private void NoPriorityButton_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void LowPriorityButton_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void HighPriority_CheckedChanged(object sender, EventArgs e)
        {

        }
    }


}
Editor is loading...
Leave a Comment