Загрузка данных


private void AddEditVisit(int? id)
{
    var frm = new Form
    {
        Text = id == -1 ? "Добавить приём" : "Редактировать приём",
        Size = new Size(550, 520),
        StartPosition = FormStartPosition.CenterParent,
        BackColor = Color.FromArgb(30, 30, 30),
        ForeColor = Color.White
    };

    int y = 30;

    // Пациент (обязательное поле)
    Label lblPatient = new Label { Text = "Пациент:", Location = new Point(20, y), AutoSize = true, ForeColor = Color.White };
    ComboBox cmbPatient = new ComboBox
    {
        Location = new Point(20, y + 20),
        Width = 400,
        DropDownStyle = ComboBoxStyle.DropDownList,
        BackColor = Color.FromArgb(55, 55, 55),
        ForeColor = Color.White
    };
    cmbPatient.DataSource = DatabaseHelper.GetAllPatients();
    cmbPatient.DisplayMember = "Фамилия";
    cmbPatient.ValueMember = "id_patient";
    frm.Controls.Add(lblPatient);
    frm.Controls.Add(cmbPatient);
    y += 60;

    // Дата (выбор даты приёма)
    Label lblDate = new Label { Text = "Дата приёма:", Location = new Point(20, y), AutoSize = true, ForeColor = Color.White };
    DateTimePicker dtpDate = new DateTimePicker
    {
        Location = new Point(20, y + 20),
        Width = 200,
        Format = DateTimePickerFormat.Short,
        BackColor = Color.FromArgb(55, 55, 55),
        ForeColor = Color.White
    };
    frm.Controls.Add(lblDate);
    frm.Controls.Add(dtpDate);
    y += 60;

    // Время
    Label lblTime = new Label { Text = "Время:", Location = new Point(20, y), AutoSize = true, ForeColor = Color.White };
    DateTimePicker dtpTime = new DateTimePicker
    {
        Location = new Point(20, y + 20),
        Width = 120,
        Format = DateTimePickerFormat.Time,
        ShowUpDown = true,
        BackColor = Color.FromArgb(55, 55, 55),
        ForeColor = Color.White
    };
    frm.Controls.Add(lblTime);
    frm.Controls.Add(dtpTime);
    y += 60;

    // Врач
    Label lblDoctor = new Label { Text = "Врач:", Location = new Point(20, y), AutoSize = true, ForeColor = Color.White };
    ComboBox cmbDoctor = new ComboBox
    {
        Location = new Point(20, y + 20),
        Width = 400,
        DropDownStyle = ComboBoxStyle.DropDownList,
        BackColor = Color.FromArgb(55, 55, 55),
        ForeColor = Color.White
    };
    cmbDoctor.DataSource = DatabaseHelper.GetAllDoctors();
    cmbDoctor.DisplayMember = "Фамилия";
    cmbDoctor.ValueMember = "id_doctor";
    frm.Controls.Add(lblDoctor);
    frm.Controls.Add(cmbDoctor);
    y += 60;

    // Диагноз (необязательное поле)
    Label lblDiagnosis = new Label { Text = "Диагноз (необязательно):", Location = new Point(20, y), AutoSize = true, ForeColor = Color.White };
    ComboBox cmbDiagnosis = new ComboBox
    {
        Location = new Point(20, y + 20),
        Width = 400,
        DropDownStyle = ComboBoxStyle.DropDownList,
        BackColor = Color.FromArgb(55, 55, 55),
        ForeColor = Color.White
    };
    DataTable dtDiagnoses = DatabaseHelper.GetAllDiagnoses();
    cmbDiagnosis.DataSource = dtDiagnoses;
    cmbDiagnosis.DisplayMember = "Название";
    cmbDiagnosis.ValueMember = "id_diagnosis";
    cmbDiagnosis.SelectedIndex = -1; // пустой выбор
    frm.Controls.Add(lblDiagnosis);
    frm.Controls.Add(cmbDiagnosis);
    y += 60;

    // Анамнез (текстовое поле, обязательное)
    Label lblAnamnesis = new Label { Text = "Анамнез:", Location = new Point(20, y), AutoSize = true, ForeColor = Color.White };
    TextBox txtAnamnesis = new TextBox
    {
        Location = new Point(20, y + 20),
        Width = 400,
        Height = 80,
        Multiline = true,
        BackColor = Color.FromArgb(55, 55, 55),
        ForeColor = Color.White,
        BorderStyle = BorderStyle.FixedSingle
    };
    frm.Controls.Add(lblAnamnesis);
    frm.Controls.Add(txtAnamnesis);
    y += 110;

    // Если редактируем существующий приём – загружаем данные
    if (id != -1)
    {
        var dt = DatabaseHelper.GetAllVisits();
        foreach (DataRow row in dt.Rows)
            if (Convert.ToInt32(row["id_visit"]) == id)
            {
                // Пациент
                int patientId = Convert.ToInt32(row["id_patient"]);
                for (int i = 0; i < cmbPatient.Items.Count; i++)
                {
                    var item = (DataRowView)cmbPatient.Items[i];
                    if (Convert.ToInt32(item["id_patient"]) == patientId)
                    {
                        cmbPatient.SelectedIndex = i;
                        break;
                    }
                }

                // Дата и время из связанной записи visitrecords
                int recordId = row["id_record"] != DBNull.Value ? Convert.ToInt32(row["id_record"]) : 0;
                if (recordId > 0)
                {
                    var dtRecords = DatabaseHelper.GetAllVisitRecords();
                    foreach (DataRow recRow in dtRecords.Rows)
                    {
                        if (Convert.ToInt32(recRow["id_record"]) == recordId)
                        {
                            dtpDate.Value = Convert.ToDateTime(recRow["date"]);
                            dtpTime.Value = DateTime.Today.Add((TimeSpan)recRow["time"]);
                            break;
                        }
                    }
                }

                // Врач
                int doctorId = Convert.ToInt32(row["id_doctor"]);
                for (int i = 0; i < cmbDoctor.Items.Count; i++)
                {
                    var item = (DataRowView)cmbDoctor.Items[i];
                    if (Convert.ToInt32(item["id_doctor"]) == doctorId)
                    {
                        cmbDoctor.SelectedIndex = i;
                        break;
                    }
                }

                // Диагноз
                if (row["id_diagnosis"] != DBNull.Value)
                {
                    int diagnosisId = Convert.ToInt32(row["id_diagnosis"]);
                    for (int i = 0; i < cmbDiagnosis.Items.Count; i++)
                    {
                        var item = (DataRowView)cmbDiagnosis.Items[i];
                        if (Convert.ToInt32(item["id_diagnosis"]) == diagnosisId)
                        {
                            cmbDiagnosis.SelectedIndex = i;
                            break;
                        }
                    }
                }

                // Анамнез
                txtAnamnesis.Text = row["anamnesis"]?.ToString();
                break;
            }
    }

    // Кнопки
    Button btnSave = new Button
    {
        Text = "Сохранить",
        Location = new Point(120, y + 20),
        Width = 120,
        Height = 35,
        DialogResult = DialogResult.OK,
        BackColor = Color.FromArgb(0, 140, 220),
        ForeColor = Color.White,
        FlatStyle = FlatStyle.Flat
    };
    Button btnCancel = new Button
    {
        Text = "Отмена",
        Location = new Point(260, y + 20),
        Width = 120,
        Height = 35,
        DialogResult = DialogResult.Cancel,
        BackColor = Color.FromArgb(70, 70, 70),
        ForeColor = Color.White,
        FlatStyle = FlatStyle.Flat
    };
    frm.Controls.Add(btnSave);
    frm.Controls.Add(btnCancel);
    frm.AcceptButton = btnSave;
    frm.CancelButton = btnCancel;

    if (frm.ShowDialog() == DialogResult.OK)
    {
        // Проверка обязательных полей
        if (cmbPatient.SelectedItem == null)
        {
            MessageBox.Show("Выберите пациента!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }
        if (cmbDoctor.SelectedItem == null)
        {
            MessageBox.Show("Выберите врача!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }
        if (string.IsNullOrWhiteSpace(txtAnamnesis.Text))
        {
            MessageBox.Show("Заполните анамнез!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }

        int patientId = (int)((DataRowView)cmbPatient.SelectedItem)["id_patient"];
        int doctorId = (int)((DataRowView)cmbDoctor.SelectedItem)["id_doctor"];
        int? diagnosisId = cmbDiagnosis.SelectedIndex != -1 ? (int?)((DataRowView)cmbDiagnosis.SelectedItem)["id_diagnosis"] : null;
        string anamnesis = txtAnamnesis.Text;

        // Создаём или находим запись в visitrecords
        int recordId = 0;
        if (id == -1)
        {
            // Добавляем новую запись в visitrecords
            DatabaseHelper.AddVisitRecord(patientId, doctorId, dtpDate.Value, dtpTime.Value.TimeOfDay, "очный");
            // Получаем последний добавленный id_record
            var dtRecords = DatabaseHelper.GetAllVisitRecords();
            if (dtRecords.Rows.Count > 0)
            {
                recordId = Convert.ToInt32(dtRecords.Rows[dtRecords.Rows.Count - 1]["id_record"]);
            }
            // Добавляем приём
            DatabaseHelper.AddVisit(recordId, patientId, diagnosisId, null, anamnesis, doctorId);
        }
        else
        {
            // При редактировании – сначала обновляем запись в visitrecords (если нужно)
            // Проще создать новый метод, но для простоты можно обновить напрямую
            // В вашем DatabaseHelper должен быть метод UpdateVisit для обновления существующего приёма
            DatabaseHelper.UpdateVisit(id.Value, recordId, patientId, diagnosisId, null, anamnesis, doctorId);
        }
        LoadAllData();
        MessageBox.Show("Приём успешно сохранён!", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
}
public static void UpdateVisit(int id, int recordId, int patientId, int? diagnosisId, int? orderId, string anamnesis, int doctorId)
{
    using (var conn = new NpgsqlConnection(ConnStr))
    {
        conn.Open();
        using (var cmd = new NpgsqlCommand(
            @"UPDATE visits SET id_record=@rec, id_patient=@pat, id_diagnosis=@diag, id_order=@ord, anamnesis=@anam, id_doctor=@doc 
              WHERE id_visit=@id", conn))
        {
            cmd.Parameters.AddWithValue("@id", id);
            cmd.Parameters.AddWithValue("@rec", recordId);
            cmd.Parameters.AddWithValue("@pat", patientId);
            cmd.Parameters.AddWithValue("@diag", diagnosisId.HasValue ? (object)diagnosisId.Value : DBNull.Value);
            cmd.Parameters.AddWithValue("@ord", orderId.HasValue ? (object)orderId.Value : DBNull.Value);
            cmd.Parameters.AddWithValue("@anam", anamnesis);
            cmd.Parameters.AddWithValue("@doc", doctorId);
            cmd.ExecuteNonQuery();
        }
    }
}