public ActionResult SaveRegistration(SaveHospitalRegistrationCommand command)
        {
            var answer = _clinicRegistrationsService.SaveHospitalRegistration(command);

            if (answer.Errors.Any())
            {
                var model = new GetHospitalRegistrationUserFormCommandAnswer
                {
                    Date = answer.Date,
                    Token = answer.Token,
                    FirstName = answer.FirstName,
                    LastName = answer.LastName,
                    SexId = answer.SexId,
                    Years = answer.Years,
                    Months = answer.Months,
                    Weeks = answer.Weeks,
                    Code = answer.Code,
                    PhoneNumber = answer.PhoneNumber,
                    Diagnosis = answer.Diagnosis,
                    DoesAgree = answer.DoesAgree,
                    UserId = answer.UserId,
                    HospitalSectionProfileId = answer.HospitalSectionProfileId,
                    Sex = answer.Sex,
                    ClinicId = answer.ClinicId,
                    Clinics = answer.Clinics,
                    Users = answer.Users,
                    HospitalSectionProfile = answer.HospitalSectionProfile,
                    Errors = answer.Errors,
                    AgeCategoryId = command.AgeCategoryId
                };

                return View("Step2", model);
            }

            return RedirectToAction("Index", "MakeHospitalRegistrationPage", new
            {
                Token = command.Token,
                answer.HasDialogMessage,
                answer.DialogMessage
            });
        }
        private List<CommandAnswerError> ValidateSaveHospitalRegistrationCommand(SaveHospitalRegistrationCommand command)
        {
            var result = new List<CommandAnswerError>();

            if (string.IsNullOrWhiteSpace(command.FirstName) || command.FirstName.Length < 2)
            {
                result.Add(new CommandAnswerError
                {
                    FieldName = "Имя",
                    Title = "Имя не может иметь меньше 2 букв"
                });
            }

            if (string.IsNullOrWhiteSpace(command.LastName) || command.LastName.Length < 2)
            {
                result.Add(new CommandAnswerError
                {
                    FieldName = "Фамилия",
                    Title = "Фамилия не может иметь меньше 2 букв"
                });
            }

            if (string.IsNullOrWhiteSpace(command.PhoneNumber) || command.PhoneNumber.Length < 3 || !command.PhoneNumber.Any(char.IsDigit))
            {
                result.Add(new CommandAnswerError
                {
                    FieldName = "Телефон",
                    Title = "Телефон имеет некорректный формат"
                });
            }

            if (!command.DoesAgree)
            {
                result.Add(new CommandAnswerError
                {
                    FieldName = "Соглашение",
                    Title = "Вы должны подтвердить, что согласны взять на себя ответственность за регистраию"
                });
            }

            if ((command.Years < 0) &&(command.Years != null))
            {
                result.Add(new CommandAnswerError
                {
                    FieldName = "Возраст",
                    Title = "Возраст не может быть отрицательным"
                });
            }

            if ((command.Months < 0) &&(command.Months != null))
            {
                result.Add(new CommandAnswerError
                {
                    FieldName = "Возраст",
                    Title = "Возраст не может быть отрицательным (Месяц)"
                });
            }

            if ((command.Months > 12) &&(command.Months != null))
            {
                result.Add(new CommandAnswerError
                {
                    FieldName = "Возраст",
                    Title = "Количество месяцев не может быть больше 12"
                });
            }
            if ((command.Weeks < 0) &&(command.Weeks != null))
            {
                result.Add(new CommandAnswerError
                {
                    FieldName = "Возраст",
                    Title = "Возраст не может быть отрицательным (Неделя)"
                });
            }
            if ((command.Weeks > 5) &&(command.Weeks != null))
            {
                result.Add(new CommandAnswerError
                {
                    FieldName = "Возраст",
                    Title = "Количество недель не может быть больше 5"
                });
            }
            if (string.IsNullOrWhiteSpace(command.Diagnosis) || command.Diagnosis.Length < 2)
            {
                result.Add(new CommandAnswerError
                {
                    FieldName = "Диагноз",
                    Title = "Диагноз не может иметь меньше 2 букв"
                });
            }

            return result;
        }
        public SaveHospitalRegistrationCommandAnswer SaveHospitalRegistration(SaveHospitalRegistrationCommand command)
        {
            var errors = this.ValidateSaveHospitalRegistrationCommand(command);

            var users = this._userRepository.GetModels().Where(model => model.ClinicUser != null && model.ClinicUser.ClinicId == command.ClinicId).ToList();
            var userResults = users.Select(model => new KeyValuePair<int, string>(model.Id, model.Name)).ToList();

            var clinics = this._clinicRepository.GetModels().ToList();
            var clinicResults = clinics.Select(model => new KeyValuePair<int, string>(model.Id, model.Name)).ToList();

            var hospitalSectionProfileName =
                this._hospitalSectionProfileRepository.GetModels()
                    .FirstOrDefault(model => model.Id == command.HospitalSectionProfileId)
                    .Name;

            if (errors.Any())
            {
                return new SaveHospitalRegistrationCommandAnswer
                {
                    SexId = command.SexId,
                    HospitalSectionProfileId = command.HospitalSectionProfileId,
                    Sex = command.SexId == null ? string.Empty : ((Sex) command.SexId).ToCorrectString(),
                    ClinicId = command.ClinicId,
                    LastName = command.LastName,
                    FirstName = command.FirstName,
                    Date = command.Date,
                    PhoneNumber = command.PhoneNumber,
                    Years = command.Years ?? 0,
                    Months = command.Months ?? 0,
                    Weeks = command.Weeks ?? 0,
                    Code = command.Code,
                    Diagnosis = command.Diagnosis,
                    MedicalExaminationResult = command.MedicalExaminationResult,
                    MedicalConsultion = command.MedicalConsultion,
                    ReservationPurpose = command.ReservationPurpose,
                    OtherInformation = command.OtherInformation,
                    DoesAgree = command.DoesAgree,
                    UserId = command.UserId,
                    Clinics = clinicResults,
                    Users = userResults,
                    HospitalSectionProfile = hospitalSectionProfileName,
                    Errors = errors,
                    Token = command.Token.Value
                };
            }

            var user = this._tokenManager.GetUserByToken(command.Token);

            var clinicId = command.ClinicId;
            var hospital = this._hospitalManager.GetHospitalByUser(user);

            var date = DateTime.ParseExact(command.Date.Split(' ').First(), "dd.MM.yyyy", CultureInfo.InvariantCulture);

            var emptyPlaceByTypeStatistics = _emptyPlaceByTypeStatisticRepository
                .GetModels()
                .Where(model => model.Sex == (command.SexId == null || command.SexId == 0 ? (Sex?)null : (Sex?)command.SexId)
                    && model.EmptyPlaceStatistic.HospitalSectionProfile.Id == command.HospitalSectionProfileId
                    && model.EmptyPlaceStatistic.Date == date
                    && model.EmptyPlaceStatistic.HospitalSectionProfile.HospitalId == hospital.Id);

            var emptyPlaceByTypeStatisticId = emptyPlaceByTypeStatistics.FirstOrDefault().Id;

            var reservation = new ReservationStorageModel
            {
                Patient = new PatientStorageModel
                {
                    Years = command.Years == null ? 0 : command.Years.Value,
                    Months = command.Months == null ? 0 : command.Months.Value,
                    Weeks = command.Weeks == null ? 0 : command.Weeks.Value,
                    Code = command.Code,
                    FirstName = command.FirstName,
                    LastName = command.LastName,
                    PhoneNumber = command.PhoneNumber,
                    Sex = command.SexId == null ? 0 : (Sex) command.SexId
                },
                ApproveTime = DateTime.Now,
                ClinicId = clinicId,
                EmptyPlaceByTypeStatisticId = emptyPlaceByTypeStatisticId,
                Status = ReservationStatus.Opened,
                Diagnosis = command.Diagnosis,
                MedicalExaminationResult = command.MedicalExaminationResult,
                MedicalConsultion = command.MedicalConsultion,
                ReservationPurpose = command.ReservationPurpose,
                OtherInformation = command.OtherInformation,
                ReservatorId = command.UserId,
                BehalfReservatorId = user.Id
            };

            _reservationRepository.Add(reservation);

            var receiverIds = this._userRepository.GetModels()
                .Where(model => model.HospitalUser != null && model.HospitalUser.HospitalId == hospital.Id)
                .Select(model => model.Id)
                .ToList();

            foreach (var receiverId in receiverIds)
            {
                var message = new MessageStorageModel
                {
                    Date = DateTime.Now.Date,
                    IsRead = false,
                    MessageType = MessageType.WarningMessage,
                    ShowStatus = TwoSideShowStatus.Showed,
                    Text = $"Пациент с номером {command.Code} был зарезервирован в Вашу больницу.\0\n" +
                           $"Дата: {command.Date}.\n\0" +
                           $"Отделение: {hospitalSectionProfileName}.\n\0" +
                           $"Диагноз: {command.Diagnosis}.\n\0",
                    Title = "Уведомление о бронировании места для пациента.",
                    UserFromId = command.UserId,
                    UserToId = receiverId
                };

                _messageRepository.Add(message);
            }

            _reservationRepository.SaveChanges();

            var messageText = "Пациент с номером {command.Code} был успешно зарезервирован в Вашу больницу.\0\n" +
                           $"Дата: {command.Date}.\n\0" +
                           $"Отделение: {hospitalSectionProfileName}.\n\0" +
                           $"Диагноз: {command.Diagnosis}.\n\0";

            var answer = new SaveHospitalRegistrationCommandAnswer
            {
                Token = command.Token.Value,
                SexId = command.SexId,
                HospitalSectionProfileId = command.HospitalSectionProfileId,
                Sex = command.SexId != null ? ((Sex)command.SexId).ToCorrectString() : string.Empty,
                ClinicId = command.ClinicId,
                LastName = command.LastName,
                FirstName = command.FirstName,
                Date = command.Date,
                PhoneNumber = command.PhoneNumber,
                Years = command.Years ?? 0,
                Months = command.Months ?? 0,
                Weeks = command.Weeks ?? 0,
                Code = command.Code,
                Diagnosis = command.Diagnosis,
                MedicalExaminationResult = command.MedicalExaminationResult,
                MedicalConsultion = command.MedicalConsultion,
                ReservationPurpose = command.ReservationPurpose,
                OtherInformation = command.OtherInformation,
                DoesAgree = command.DoesAgree,
                UserId = command.UserId,
                Clinics = clinicResults,
                Users = userResults,
                HospitalSectionProfile = hospitalSectionProfileName,
                HasDialogMessage = true,
                DialogMessage = messageText

            };

            return answer;
        }