public ActionResult SaveRegistration(SaveClinicRegistrationCommand command, HttpPostedFileBase reservationFile)
        {
            if (reservationFile != null)
            {
                command.File = reservationFile.InputStream;
                command.FileName = reservationFile.FileName;
            }
            var answer = _clinicRegistrationsService.SaveClinicRegistration(command);

            if (answer.Errors.Any())
            {
                var model = new GetClinicRegistrationUserFormCommandAnswer
                {
                    Sex = command.Sex,
                    DateValue = command.DateValue,
                    Date = command.DateValue.ToCorrectDateString(),
                    CurrentHospitalId = command.CurrentHospitalId,
                    Token = answer.Token,
                    SectionProfileId = command.SectionProfileId,
                    FirstName = command.FirstName,
                    LastName = command.LastName,
                    SexId = command.SexId,
                    SectionProfile = command.SectionProfile,
                    Years = command.Years,
                    Months = command.Months,
                    Weeks = command.Weeks,
                    Code = command.Code,
                    CurrentHospital = command.CurrentHospital,
                    PhoneNumber = command.PhoneNumber,
                    Diagnosis = command.Diagnosis,
                    MedicalExaminationResult = command.MedicalExaminationResult,
                    MedicalConsultion = command.MedicalConsultion,
                    ReservationPurpose = command.ReservationPurpose,
                    OtherInformation = command.OtherInformation,
                    Errors = answer.Errors,
                    AgeCategoryId = command.AgeCategoryId,
                    File = command.File
                };

                return View("Step3", model);
            }

            return RedirectToAction("Step2", "MakeClinicRegistrationPage",
                new
                {
                    Token = command.Token,
                    Sex = command.SexId,
                    SectionProfileId = command.SectionProfileId,
                    answer.DialogMessage,
                    answer.HasDialogMessage
                });
        }
        private List<CommandAnswerError> ValidateSaveClinicRegistrationCommand(SaveClinicRegistrationCommand command)
        {
            var result = new List<CommandAnswerError>();

            var emptyPlaceStatisticId = _emptyPlaceStatisticRepository.GetModels()
                .Where(model => model.HospitalSectionProfileId == command.SectionProfileId && model.Date == command.DateValue).Select(m=>m.Id).ToList();

            var emptyPlaceByTypeStatisticRepository = _emptyPlaceByTypeStatisticRepository.GetModels();

            var places = emptyPlaceStatisticId.Select(i => emptyPlaceByTypeStatisticRepository
                    .Where(model => model.EmptyPlaceStatistic.HospitalSectionProfileId == command.SectionProfileId)
                    .Where(model => model.Sex == (command.SexId == 1 ? Sex.Male : Sex.Female))
                    .Where(storageModel => storageModel.EmptyPlaceStatisticId.Equals(i))
                    .Select(model => new HospitalRegistrationCountStatisticItem
                    {
                        FreePlacesCount = model.Count - model.Reservations.Count(storageModel => storageModel.Status == ReservationStatus.Opened)
                    }).FirstOrDefault()).FirstOrDefault();

            if (places.FreePlacesCount <= 0)
            {
                result.Add(new CommandAnswerError
                {
                    FieldName = "Внимание!",
                    Title = "К сожалению свободных мест по выбранным критериям не осталось."
                });
            }

            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.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 SaveClinicRegistrationCommandAnswer SaveClinicRegistration(SaveClinicRegistrationCommand command)
        {
            var errors = this.ValidateSaveClinicRegistrationCommand(command);

            if (errors.Any())
            {
                return new SaveClinicRegistrationCommandAnswer
                {
                    Errors = errors,
                    Token = command.Token.Value
                };
            }

            var user = this._tokenManager.GetUserByToken(command.Token);
            var clinicId = this._clinicManager.GetClinicByUser(user).Id;

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

            var emptyPlaceByTypeStatistics = _emptyPlaceByTypeStatisticRepository
                .GetModels()
                .Where(model => model.Sex == (Sex?)command.SexId
                    && model.EmptyPlaceStatistic.HospitalSectionProfile.SectionProfileId == command.SectionProfileId
                    && model.EmptyPlaceStatistic.Date == date
                    && model.EmptyPlaceStatistic.HospitalSectionProfile.HospitalId == command.CurrentHospitalId);

            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 = user.Id
            };

            _reservationRepository.Add(reservation);

            if (command.File != null)
            {
                var reservationFile = new ReservationFileStorageModel()
                {
                    Name = command.FileName,
                    ReservationId = reservation.Id,
                    Reservation = reservation,
                    File = ReadFully(command.File)
                };

                _reservationFileRepository.Add(reservationFile);
            }

            var receiverIds = this._userRepository.GetModels()
                .Where(model => model.HospitalUser != null && model.HospitalUser.HospitalId == command.CurrentHospitalId)
                .Where(model => model.HospitalUser.HospitalUserSectionAccesses.Any(storageModel => !storageModel.IsBlocked && storageModel.HospitalSectionProfile.SectionProfileId == command.SectionProfileId))
                .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" +
                           $"Отделение: {command.SectionProfile}.\n\0" +
                           $"Диагноз: {command.Diagnosis}.\n\0",
                    Title = "Уведомление о бронировании места для пациента.",
                    UserFromId = user.Id,
                    UserToId = receiverId
                };

                _messageRepository.Add(message);
            }

            _reservationRepository.SaveChanges();

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

            return new SaveClinicRegistrationCommandAnswer
            {
                Token = command.Token.Value,
                HasDialogMessage = true,
                DialogMessage = messageText
            };
        }