public ActionResult CreateNewTrip(long ownerTripRouteId, long ownerTripDateId)
        {
            var currentUser = _usersService.GetUserByLogin(System.Web.HttpContext.Current.User.Identity.Name);
            var ownerTripDate = _tripsService.GetTripDateById(ownerTripDateId);
            var ownerTrip = ownerTripDate.Trip;
            var ownerRoute = ownerTrip.TripRoute.FirstOrDefault(x => x.Id == ownerTripRouteId);

            if (ownerTrip != null && ownerRoute != null)
            {
                var newTrip = new Trip
                    {
                        OwnerId = currentUser.Id,
                        TripStatus = 1,
                        TripType = ownerTrip.TripType == TripType.Driver ? TripType.Passenger : TripType.Driver,
                        MainRouteStr = string.Format("{0};{1}", ownerRoute.StartPointFullName, ownerRoute.EndPointFullName),
                        MainRouteShortStr = string.Format("{0};{1}", ownerRoute.StartPointShortName, ownerRoute.EndPointShortName),
                        IsDeleted = false
                    };

                newTrip.TripRoute.Add(new TripRoute
                {
                    StartPointGid = ownerRoute.StartPointGid,
                    StartPointFullName = ownerRoute.StartPointFullName,
                    StartPointShortName = ownerRoute.StartPointShortName,
                    EndPointGid = ownerRoute.EndPointGid,
                    EndPointFullName = ownerRoute.EndPointFullName,
                    EndPointShortName = ownerRoute.EndPointShortName
                });

                newTrip.TripDate.Add(new TripDate
                {
                    Date = ownerTripDate.Date,
                    IsDeleted = false
                });

                _tripsService.Insert(newTrip);
                _tripsService.Save();

                var entity = new Request
                {
                    DriverTripId = ownerTrip.TripType == TripType.Driver ? ownerTrip.Id : newTrip.Id,
                    PassengerTripId = ownerTrip.TripType == TripType.Driver ? newTrip.Id : ownerTrip.Id,
                    OwnerRouteId = ownerRoute.Id,
                    OwnerTripDateId = ownerTripDate.Id,
                    InitiatorId = currentUser.Id,
                    StatusRequestId = 1,
                    CreateDate = DateTime.Now,
                    RequestToDate = ownerTripDate.Date
                };

                _requestsService.Insert(entity);
                _requestsService.SaveChanges();
            }

            return PartialView("YourRequestSent");
        }
        public JsonResult SaveTrip(TripModel model, string points, DateTime dateAt, DateTime? dateTo, string costPerRoute)
        {
            var currentUser = _usersService.GetUserByLogin(System.Web.HttpContext.Current.User.Identity.Name);
            var trip = new Trip
                {
                    OwnerId = currentUser.Id
                };

            var costs = costPerRoute.Split(';');

            // Дисериализуем строку с массивом точек
            var js = new JavaScriptSerializer();
            var deserializedPoints = (object[])js.DeserializeObject(points);
            var myPoints = new List<SJSonModel>();

            if (deserializedPoints != null)
            {
                // получаем массив точек
                myPoints.AddRange(from Dictionary<string, object> newFeature in deserializedPoints select new SJSonModel(newFeature));

                var mainRouteStr = new List<string>();
                var mainRouteShortStr = new List<string>();

                foreach (var point in myPoints)
                {
                    mainRouteStr.Add(point.FullName);
                    mainRouteShortStr.Add(point.ShortName);
                }

                trip.MainRouteStr = string.Join(";", mainRouteStr);
                trip.MainRouteShortStr = string.Join(";", mainRouteShortStr);
            }

            if (model.IsDriver)
            {
                trip.TripType = TripType.Driver;

                // генерируем всевозможные варианты маршрутов по этому пути точек
                for (var i = 0; i < myPoints.Count - 1; i++)
                {
                    // счетчик для стоимости маршрута
                    var xCost = Convert.ToInt32(costs[i]);
                    for (var j = i + 1; j < myPoints.Count; j++)
                    {
                        var route = new TripRoute
                        {
                            StartPointGid = myPoints[i].Gid,
                            StartPointFullName = myPoints[i].FullName,
                            StartPointShortName = myPoints[i].ShortName,
                            EndPointGid = myPoints[j].Gid,
                            EndPointFullName = myPoints[j].FullName,
                            EndPointShortName = myPoints[j].ShortName,
                            Cost = xCost
                        };

                        trip.TripRoute.Add(route);

                        if (j != myPoints.Count - 1)
                        {
                            xCost += Convert.ToInt32(costs[j]);
                        }
                    }
                }
            }
            else
            {
                trip.TripType = TripType.Passenger;

                // генерируем маршрут только из точки А в точку В
                trip.TripRoute.Add(new TripRoute
                    {
                        StartPointGid = myPoints.First().Gid,
                        StartPointFullName = myPoints.First().FullName,
                        StartPointShortName = myPoints.First().ShortName,
                        EndPointGid = myPoints.Last().Gid,
                        EndPointFullName = myPoints.Last().FullName,
                        EndPointShortName = myPoints.Last().ShortName,
                        Cost = 0
                    });
            }

            if (dateTo == null || model.IsDriver)
            {
                trip.TripDate.Add(new TripDate
                {
                    Date = dateAt,
                    IsDeleted = false
                });
            }
            else
            {
                for (var date = dateAt; date <= dateTo.Value; date = date.AddDays(1))
                {
                    trip.TripDate.Add(new TripDate
                    {
                        Date = date,
                        IsDeleted = false
                    });
                }
            }

            trip.Seats = model.SeatsNumber;
            trip.FreeSeats = model.SeatsNumber;
            trip.TripStatus = 1;
            trip.IsDeleted = false;

            _tripsService.Insert(trip);
            _tripsService.Save();

            return Json(true, JsonRequestBehavior.AllowGet);
        }
        public ActionResult SendRequest(long tripDateId, long routeId)
        {
            var currentUser = _usersService.GetUserByLogin(System.Web.HttpContext.Current.User.Identity.Name);
            var hisTripDate = _tripsService.GetTripDateById(tripDateId);
            var hisTrip = hisTripDate.Trip;
            var hisRoute = hisTrip.TripRoute.FirstOrDefault(x => x.Id == routeId);

            if (hisTrip.OwnerId == currentUser.Id)
            {
                ViewBag.Error = "Вы пытаетесь отправить заявку самому себе";
                return PartialView("Error");
            }

            if (hisRoute == null)
            {
                ViewBag.Error = "Данного маршрута не существует";
                return PartialView("Error");
            }

            if (hisTripDate.Date < DateTime.Today)
            {
                ViewBag.Error = "Вы пытаетесь отправить заявку на прошедшую поездку";
                return PartialView("Error");
            }

            var thisRequest = _requestsService.GetRequest(currentUser.Id, routeId, tripDateId);
            if (thisRequest != null)
            {
                ViewBag.Error = "Заявка на эту поездку уже отправлена";
                return PartialView("Error");
            }

            var searchingType = hisTrip.TripType == TripType.Driver ? TripType.Passenger : TripType.Driver;
            var myTrips = _tripsService.GetActiveTripsByUserAndRoute(currentUser.Id, hisRoute.StartPointGid, hisRoute.EndPointGid, DateTime.Today, searchingType).ToList();

            string message;
            if (myTrips.Any())
            {
                // До лучших времен. Выбор к какой поездке принадлежит заявка
                /* var model = new TripsListModel
                    {
                        trips = myTrips.GroupBy(trip => trip.TripId).Select(group => new TripModel
                        {
                            TripId = group.Key,
                            MainRouteShortStr = group.First().MainRouteShortStr.Split(';'),
                            MainRouteStr = group.First().MainRouteStr.Split(';'),
                            StartDateAt = group.Min(x => x.Date),
                            StartDateTo = group.Max(x => x.Date),
                            StartPointShortName = someoneRoute.StartPointShortName,
                            EndPointShortName = someoneRoute.EndPointShortName
                        }).ToList()
                    };

                ViewBag.OwnerTripRouteId = routeId;
                ViewBag.OwnerTripDateId = tripDateId;

                return PartialView("MyTripsList", model); */

                var myTrip = _tripsService.GetById(myTrips.First().TripId);
                var myRoute =
                    myTrip.TripRoute.FirstOrDefault(
                        x => x.StartPointGid == hisRoute.StartPointGid && x.EndPointGid == hisRoute.EndPointGid);

                if (myTrip.TripType == TripType.Passenger)
                {
                    if (myTrip.TripDate.FirstOrDefault(d => d.Date == hisTripDate.Date) == null)
                    {
                        myTrip.TripDate.Add(new TripDate
                            {
                                Date = hisTripDate.Date,
                                IsDeleted = false
                            });
                    }
                }

                var request = new Request
                {
                    DriverTripId = myTrip.TripType == TripType.Driver ? myTrip.Id : hisTrip.Id,
                    PassengerTripId = myTrip.TripType == TripType.Passenger ? myTrip.Id : hisTrip.Id,
                    OwnerRouteId = hisRoute.Id,
                    OwnerTripDateId = hisTripDate.Id,
                    InitiatorId = currentUser.Id,
                    Cost = myTrip.TripType == TripType.Driver ? myRoute.Cost : 0,
                    StatusRequestId = 1,
                    CreateDate = DateTime.Now,
                    RequestToDate = hisTrip.TripType == TripType.Driver ? myTrip.TripDate.First().Date : hisTripDate.Date
                };

                _requestsService.Insert(request);
                _requestsService.SaveChanges();
                _tripsService.Save();

                message = string.Format(
                    "Вам пришла новая заявка:\n{0}-{1}\n{2}\n{3} {4}.\nВы можете Принять или Отклонить в личном кабинете. www.beride.ru", myRoute.StartPointShortName, myRoute.EndPointShortName, hisTripDate.Date.ToShortDateString(), currentUser.FirstName, currentUser.LastName);

                _smsService.SendMessage(hisTrip.User.Phone, message);

                return PartialView("YourRequestSent");
            }

            // Создаем новую поездку со стороны пользователя, если у него нет активных поездок
            var myNewTrip = new Trip
                {
                    OwnerId = currentUser.Id,
                    Seats = 1,
                    TripStatus = 1,
                    TripType = searchingType,
                    MainRouteStr = string.Format("{0};{1}", hisRoute.StartPointFullName, hisRoute.EndPointFullName),
                    MainRouteShortStr = string.Format("{0};{1}", hisRoute.StartPointShortName, hisRoute.EndPointShortName),
                    IsDeleted = false
                };

            myNewTrip.TripRoute.Add(new TripRoute
                {
                    StartPointGid = hisRoute.StartPointGid,
                    StartPointFullName = hisRoute.StartPointFullName,
                    StartPointShortName = hisRoute.StartPointShortName,
                    EndPointGid = hisRoute.EndPointGid,
                    EndPointFullName = hisRoute.EndPointFullName,
                    EndPointShortName = hisRoute.EndPointShortName,
                    Cost = 0 // Надо сделать добавление стоимости из расчета автоматом
                });

            myNewTrip.TripDate.Add(new TripDate
                {
                    Date = hisTripDate.Date,
                    IsDeleted = false
                });

            _tripsService.Insert(myNewTrip);
            _tripsService.Save();

            var entity = new Request
            {
                DriverTripId = hisTrip.TripType == TripType.Driver ? hisTrip.Id : myNewTrip.Id,
                PassengerTripId = hisTrip.TripType == TripType.Driver ? myNewTrip.Id : hisTrip.Id,
                OwnerRouteId = hisRoute.Id,
                OwnerTripDateId = hisTripDate.Id,
                InitiatorId = currentUser.Id,
                StatusRequestId = 1,
                CreateDate = DateTime.Now,
                RequestToDate = hisTrip.TripType == TripType.Driver ? myNewTrip.TripDate.First().Date : hisTripDate.Date,
                Cost = 0
            };

            _requestsService.Insert(entity);
            _requestsService.SaveChanges();

            message = string.Format(
                "Вам пришла новая заявка:\n{0}-{1}\n{2}\n{3} {4}.\nВы можете Принять или Отклонить в личном кабинете. www.beride.ru",
                myNewTrip.TripRoute.First().StartPointShortName,
                myNewTrip.TripRoute.First().EndPointShortName,
                hisTripDate.Date.ToShortDateString(),
                currentUser.FirstName,
                currentUser.LastName);

            _smsService.SendMessage(hisTrip.User.Phone, message);

            return PartialView("YourTripCreated");
        }
 /// <summary>
 /// Устаревший метод для добавления новых объектов в набор EntitySet Trip. Взамен можно использовать метод .Add связанного свойства ObjectSet&lt;T&gt;.
 /// </summary>
 public void AddToTrip(Trip trip)
 {
     base.AddObject("Trip", trip);
 }
 /// <summary>
 /// Создание нового объекта Trip.
 /// </summary>
 /// <param name="id">Исходное значение свойства Id.</param>
 /// <param name="tripType">Исходное значение свойства TripType.</param>
 /// <param name="ownerId">Исходное значение свойства OwnerId.</param>
 /// <param name="tripStatus">Исходное значение свойства TripStatus.</param>
 /// <param name="isDeleted">Исходное значение свойства IsDeleted.</param>
 /// <param name="mainRouteStr">Исходное значение свойства MainRouteStr.</param>
 /// <param name="mainRouteShortStr">Исходное значение свойства MainRouteShortStr.</param>
 public static Trip CreateTrip(global::System.Int32 id, global::System.Int32 tripType, global::System.Int32 ownerId, global::System.Int32 tripStatus, global::System.Boolean isDeleted, global::System.String mainRouteStr, global::System.String mainRouteShortStr)
 {
     Trip trip = new Trip();
     trip.Id = id;
     trip.TripType = tripType;
     trip.OwnerId = ownerId;
     trip.TripStatus = tripStatus;
     trip.IsDeleted = isDeleted;
     trip.MainRouteStr = mainRouteStr;
     trip.MainRouteShortStr = mainRouteShortStr;
     return trip;
 }
 public void Insert(Trip entity)
 {
     db.AddToTrip(entity);
 }
 public void Delete(Trip entity)
 {
     throw new NotImplementedException();
 }