public IEnumerable<MessageStorageModel> GetList()
        {
            var titles = new List<string>
            {
                "Warning",
                "Attention",
                "Error",
                "Fatal Error",
                "Success",
                "Notice",
                "Message",
                "Hint"
            };

            var result = new List<MessageStorageModel>();
            var users = _userRepository.GetModels().ToList();

            foreach (var userTo in users)
            {
                var messagesCount = 0; //extendedRandom.Next(5, 15);
                for (var i = 0; i < messagesCount; i++)
                {
                    var nextUserFrom = _extendedRandom.GetRandomValueFromList(users);
                    var message = new MessageStorageModel
                    {
                        Date = DateTime.Now,
                        Text = $"{_extendedRandom.GetRandomValueFromList(titles)} {_extendedRandom.Next(1000)}",
                        IsRead = false,
                        MessageType = _extendedRandom.GetRandomBool() ? MessageType.UserMessage : MessageType.WarningMessage,
                        ShowStatus = TwoSideShowStatus.Showed,
                        Title = $"{_extendedRandom.GetRandomValueFromList(titles)} {_extendedRandom.Next(1000)}",
                        UserFromId = nextUserFrom.Id,
                        UserToId = userTo.Id
                    };
                    result.Add(message);
                }
            }

            return result;
        }
        public BreakHospitalRegistrationCommandAnswer BreakHospitalRegistration(BreakHospitalRegistrationCommand command)
        {
            if (command.Cause == null)
            {
                return new BreakHospitalRegistrationCommandAnswer
                {
                    Token = command.Token.Value,
                    DialogMessage = "Регистрация НЕ отменена. Пожалуйста, укажите причину отмены регистрации",
                    HasDialogMessage = true
                };
            }
            var reservation = this._reservationRepository.GetModels().FirstOrDefault(model => model.Id == command.ReservationId);
            var patient = this._reservationRepository.GetModels().Where(model => model.Id == command.ReservationId).Select(model => model.Patient).FirstOrDefault();
            var user = this._tokenManager.GetUserByToken(command.Token);

            reservation.CancelTime = DateTime.Now;
            reservation.Status = ReservationStatus.ClosedByHospital;

            this._reservationRepository.Update(command.ReservationId, reservation);

            var hospitalId = this._reservationRepository.GetModels()
                .Where(model => model.Id == command.ReservationId)
                .Select(model => model.EmptyPlaceByTypeStatistic.EmptyPlaceStatistic.HospitalSectionProfile.HospitalId)
                .FirstOrDefault();

            var reservatorId = this._reservationRepository.GetModels()
                .Where(model => model.Id == command.ReservationId)
                .Select(model => model.ReservatorId).FirstOrDefault();

            var message = new MessageStorageModel
            {
                Date = DateTime.Now.Date,
                IsRead = false,
                MessageType = MessageType.WarningMessage,
                ShowStatus = TwoSideShowStatus.Showed,
                Text = $"Бронирование пациента с номером {patient.Code} был отменено.\0\n" +
                        $"Диагноз: {reservation.Diagnosis}.\n\0" +
                        $"Причина отмены: {command.Cause}",
                Title = "Уведомление о отмене бронирования места для пациента.",
                UserFromId = user.Id,
                UserToId = reservatorId
            };

            _messageRepository.Add(message);

            _reservationRepository.SaveChanges();

            this._reservationRepository.SaveChanges();

            return new BreakHospitalRegistrationCommandAnswer
            {
                Token = command.Token.Value,
                DialogMessage = "Бронирование пациента было успешно отменено",
                HasDialogMessage = true
            };
        }
        public BreakClinicRegistrationCommandAnswer BreakClinicRegistration(BreakClinicRegistrationCommand command)
        {
            var reservation = this._reservationRepository.GetModels().FirstOrDefault(model => model.Id == command.ReservationId);
            var patient = this._reservationRepository.GetModels().Where(model => model.Id == command.ReservationId).Select(model => model.Patient).FirstOrDefault();
            var user = this._tokenManager.GetUserByToken(command.Token);

            reservation.CancelTime = DateTime.Now;
            reservation.Status = ReservationStatus.ClosedByClinic;

            this._reservationRepository.Update(command.ReservationId, reservation);

            var hospitalId = this._reservationRepository.GetModels()
                .Where(model => model.Id == command.ReservationId)
                .Select(model => model.EmptyPlaceByTypeStatistic.EmptyPlaceStatistic.HospitalSectionProfile.HospitalId)
                .FirstOrDefault();

            var hospitalSectionProfileId = this._reservationRepository.GetModels()
                .Where(model => model.Id == command.ReservationId)
                .Select(model => model.EmptyPlaceByTypeStatistic.EmptyPlaceStatistic.HospitalSectionProfileId)
                .FirstOrDefault();

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

                _messageRepository.Add(message);
            }

            _reservationRepository.SaveChanges();

            this._reservationRepository.SaveChanges();

            return new BreakClinicRegistrationCommandAnswer
            {
                Token = command.Token.Value
            };
        }
        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;
        }
        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
            };
        }
        public SaveDischargeCommandAnswer SaveDischarge(SaveDischargeCommand command)
        {
            var user = _tokenManager.GetUserByToken(command.Token);

            var hospital = _hospitalManager.GetHospitalByUser(user);

            var responsiblePersonId = _clinicUserRepository.GetModels()
                .FirstOrDefault(model => model.ClinicId == command.ClinicId && model.IsDischargeResponsiblePerson).Id;

            var anotherPersonsFromClinic = _clinicUserRepository.GetModels()
                .Where(model => model.ClinicId == command.ClinicId && !model.IsDischargeResponsiblePerson).Select(model => model.Id).ToList();

            var titleMessage = $"Новая выписка была отправлена из больницы '{hospital.Name}'";
            var textMessage =
                $"Новая выписка была отправлена из больницы '{hospital.Name}'. Отправитель '{user.Name}'. Дата: '{DateTime.Now.ToCorrectDateString()} {DateTime.Now.ToString("t")}' ";

            var body = ReadFully(command.File);

            var discharge = new DischargeStorageModel
            {
                Id = 0,
                Name = command.FileName,
                Message = new MessageStorageModel
                {
                    Id = 0,
                    Title = titleMessage,
                    Date = DateTime.Now,
                    Text = textMessage,
                    ShowStatus = TwoSideShowStatus.Showed,
                    UserFromId = user.Id,
                    UserToId = responsiblePersonId,
                    IsRead = false,
                    MessageType = MessageType.WarningMessage,
                },
                Body = body,
                MimeType = command.ContentType
            };
            this._dischargeRepository.Add(discharge);

            foreach (var personId in anotherPersonsFromClinic)
            {
                var message = new MessageStorageModel
                {
                    Id = 0,
                    Title = titleMessage,
                    Date = DateTime.Now,
                    Text = textMessage,
                    ShowStatus = TwoSideShowStatus.Showed,
                    UserFromId = user.Id,
                    UserToId = personId,
                    IsRead = false,
                    MessageType = MessageType.WarningMessage,
                };
                _messageRepository.Add(message);
            }
            _messageRepository.SaveChanges();

            return new SaveDischargeCommandAnswer
            {
                Token = command.Token.Value
            };
        }