This commit is contained in:
Hamza-Ayed
2024-11-17 12:02:54 +02:00
parent bf8a29b814
commit f796f4bc48
13 changed files with 611 additions and 493 deletions

View File

@@ -1,8 +1,11 @@
import 'dart:async';
import 'dart:convert';
import 'dart:math' show Random, cos, pi, pow, sin, sqrt;
import 'dart:math' show Random, cos, max, min, pi, pow, sin, sqrt;
import 'dart:math' as math;
import 'dart:ui';
import 'package:SEFER/constant/univeries_polygon.dart';
import 'package:SEFER/controller/firebase/local_notification.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_confetti/flutter_confetti.dart';
import 'package:vector_math/vector_math.dart' show radians, degrees;
@@ -1364,7 +1367,7 @@ class MapPassengerController extends GetxController {
Set<String> notifiedDrivers = {};
confirmRideForAllDriverAvailable() async {
confirmRideForAllDriverAvailable11() async {
// Fetch car locations
await getCarsLocationByPassengerAndReloadMarker(
box.read(BoxName.carType), 3000);
@@ -1419,7 +1422,7 @@ class MapPassengerController extends GetxController {
// Timer for 5 iterations, runs every 2 seconds
int iteration = 0;
Timer.periodic(const Duration(seconds: 2), (timer) async {
if (iteration >= 5) {
if (iteration >= 10) {
timer.cancel();
return;
}
@@ -1539,94 +1542,117 @@ class MapPassengerController extends GetxController {
}
}
confirmRideForAllDriverAvailable1() async {
int attempts = 0;
const int maxAttempts = 4;
const Duration delayDuration = Duration(seconds: 2);
Future<void> confirmRideForAllDriverAvailable() async {
// Try to fetch car locations up to 4 times with a 2-second delay
bool driversFound = false;
for (int attempt = 0; attempt < 4; attempt++) {
await getCarsLocationByPassengerAndReloadMarker(
box.read(BoxName.carType), 3000);
// Initial data fetch
await getCarsLocationByPassengerAndReloadMarker(
box.read(BoxName.carType), 3000);
if (dataCarsLocationByPassenger != null &&
dataCarsLocationByPassenger != 'failure') {
PaymentController paymentController = Get.find<PaymentController>();
rideConfirm = true;
shouldFetch = true;
isBottomSheetShown = false;
timeToPassengerFromDriverAfterApplied = 60;
// Create a set to keep track of notified driver IDs
Set<String> notifiedDriverIds = {};
// Send the initial ride request once
rideId = await CRUD().post(
link: "${AppLink.seferCairoServer}/ride/rides/add.php",
payload: {
"start_location":
'${data[0]["start_location"]['lat']},${data[0]["start_location"]['lng']}',
"end_location":
'${data[0]["end_location"]['lat']},${data[0]["end_location"]['lng']}',
"date": DateTime.now().toString(),
"time": DateTime.now().toString(),
"endtime": durationToAdd.toString(),
"price": totalPassenger.toStringAsFixed(2),
"passenger_id": box.read(BoxName.passengerID).toString(),
"driver_id": dataCarsLocationByPassenger['data'][carsOrder]
['driver_id']
.toString(),
"status": "waiting",
'carType': box.read(BoxName.carType),
"price_for_driver": totalPassenger.toString(),
"price_for_passenger": totalME.toString(),
"distance": distance.toString(),
"paymentMethod": paymentController.isWalletChecked.toString(),
}).then((value) => jsonDecode(value)['message']);
if (AppLink.endPoint != AppLink.seferCairoServer) {
CRUD().post(link: '${AppLink.endPoint}/ride/rides/add.php', payload: {
"start_location": //'${data[0]['start_address']}',
'${data[0]["start_location"]['lat']},${data[0]["start_location"]['lng']}',
"end_location": //'${data[0]['end_address']}',
'${data[0]["end_location"]['lat']},${data[0]["end_location"]['lng']}',
"date": DateTime.now().toString(),
"time": DateTime.now().toString(),
"endtime": durationToAdd.toString(),
"price": totalPassenger.toStringAsFixed(2),
"passenger_id": box.read(BoxName.passengerID).toString(),
"driver_id": dataCarsLocationByPassenger['data'][carsOrder]
['driver_id']
.toString(),
"status": "waiting",
'carType': box.read(BoxName.carType),
"price_for_driver": totalPassenger.toString(),
"price_for_passenger": totalME.toString(),
"distance": distance.toString(),
"paymentMethod": paymentController.isWalletChecked.toString(),
});
}
// Add the initially available drivers to the notified set
for (var driver in dataCarsLocationByPassenger['data']) {
notifiedDriverIds.add(driver['driver_id'].toString());
// Check if dataCarsLocationByPassenger is valid and contains drivers
if (dataCarsLocationByPassenger != 'failure' &&
dataCarsLocationByPassenger != null &&
dataCarsLocationByPassenger.containsKey('data') &&
dataCarsLocationByPassenger['data'] != null) {
driversFound = true;
break; // Exit loop if drivers are found
}
// Periodically check for new drivers
Timer.periodic(delayDuration, (Timer timer) async {
attempts++;
// Wait 2 seconds before next attempt
await Future.delayed(const Duration(seconds: 2));
}
// If no drivers were found after 4 attempts, show a dialog
if (!driversFound) {
Get.dialog(
BackdropFilter(
filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5),
child: CupertinoAlertDialog(
title: Text(
"No Car or Driver Found in your area.".tr,
style: AppStyle.title.copyWith(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
content: Text(
"No Car or Driver Found in your area.".tr,
style: AppStyle.title.copyWith(fontSize: 16),
),
actions: [
CupertinoDialogAction(
onPressed: () {
Get.back();
Get.offAll(() => const MapPagePassenger());
},
child: Text('OK'.tr,
style: const TextStyle(color: AppColor.greenColor)),
),
],
),
),
barrierDismissible: false,
);
return;
}
// Proceed with the rest of the function if drivers are found
PaymentController paymentController = Get.find<PaymentController>();
rideConfirm = true;
shouldFetch = true;
isBottomSheetShown = false;
timeToPassengerFromDriverAfterApplied = 60;
// Add ride to database
await CRUD()
.post(link: "${AppLink.seferCairoServer}/ride/rides/add.php", payload: {
"start_location":
'${data[0]["start_location"]['lat']},${data[0]["start_location"]['lng']}',
"end_location":
'${data[0]["end_location"]['lat']},${data[0]["end_location"]['lng']}',
"date": DateTime.now().toString(),
"time": DateTime.now().toString(),
"endtime": durationToAdd.toString(),
"price": totalPassenger.toStringAsFixed(2),
"passenger_id": box.read(BoxName.passengerID).toString(),
"driver_id": dataCarsLocationByPassenger['data'][carsOrder]['driver_id']
.toString(),
"status": "waiting",
'carType': box.read(BoxName.carType),
"price_for_driver": totalPassenger.toString(),
"price_for_passenger": totalME.toString(),
"distance": distance.toString(),
"paymentMethod": paymentController.isWalletChecked.toString(),
}).then((value) {
if (value is String) {
final parsedValue = jsonDecode(value);
rideId = parsedValue['message'];
} else if (value is Map) {
rideId = value['message'];
} else {
Log.print('Unexpected response type: ${value.runtimeType}');
}
// Timer to notify drivers every 2 seconds for 5 iterations
int iteration = 0;
Timer.periodic(const Duration(seconds: 2), (timer) async {
if (iteration >= 5) {
timer.cancel();
return;
}
iteration++;
// Reload driver locations and notify available drivers
await getCarsLocationByPassengerAndReloadMarker(
box.read(BoxName.carType), 3000);
if (dataCarsLocationByPassenger != 'failure') {
// Check for new drivers and notify them
for (var driver in dataCarsLocationByPassenger['data']) {
String driverId = driver['driver_id'].toString();
// Only notify new drivers
if (!notifiedDriverIds.contains(driverId)) {
notifiedDriverIds.add(driverId);
// Prepare notification body
if (dataCarsLocationByPassenger != null &&
dataCarsLocationByPassenger.containsKey('data') &&
dataCarsLocationByPassenger['data'] != null) {
for (var driverData in dataCarsLocationByPassenger['data']) {
String driverId = driverData['driver_id'].toString();
if (!notifiedDrivers.contains(driverId)) {
notifiedDrivers.add(driverId);
List<String> body = [
'${data[0]["start_location"]['lat']},${data[0]["start_location"]['lng']}',
'${data[0]["end_location"]['lat']},${data[0]["end_location"]['lng']}',
@@ -1642,10 +1668,11 @@ class MapPassengerController extends GetxController {
durationByPassenger.toString(),
distanceByPassenger.toString(),
paymentController.isWalletChecked.toString(),
driver['token'].toString(),
driverData['token'].toString(),
durationToPassenger.toString(),
rideId,
rideTimerBegin.toString(),
driverId,
durationToRide.toString(),
Get.find<WayPointController>().wayPoints.length > 1
? 'haveSteps'
@@ -1656,10 +1683,10 @@ class MapPassengerController extends GetxController {
placesCoordinate[3],
placesCoordinate[4],
costForDriver.toStringAsFixed(2),
double.parse(box.read(BoxName.passengerWalletTotal)) < 0
(double.parse(box.read(BoxName.passengerWalletTotal)) < 0
? double.parse(box.read(BoxName.passengerWalletTotal))
.toStringAsFixed(2)
: '0',
: '0'),
box.read(BoxName.email).toString(),
data[0]['start_address'],
data[0]['end_address'],
@@ -1667,37 +1694,43 @@ class MapPassengerController extends GetxController {
kazan.toStringAsFixed(0),
passengerRate.toStringAsFixed(2),
];
// Send notification to the new driver
FirebaseMessagesController().sendNotificationToDriverMAP(
'OrderSpeed',
rideId.toString(),
driver['token'].toString(),
rideId,
driverData['token'].toString(),
body,
'order.wav',
);
}
}
} else {
MyDialog().getDialog("No Car or Driver Found in your area.".tr,
"No Car or Driver Found in your area.".tr, () {
Get.back();
Get.offAll(const MapPagePassenger());
});
}
// Stop after max attempts
if (attempts >= maxAttempts) {
timer.cancel();
}
});
} else {
MyDialog().getDialog("No Car or Driver Found in your area.".tr,
"No Car or Driver Found in your area.".tr, () {
Get.back();
Get.offAll(const MapPagePassenger());
});
// If an additional endpoint is available, post data there as well
if (AppLink.endPoint != AppLink.seferCairoServer) {
CRUD().post(link: '${AppLink.endPoint}/ride/rides/add.php', payload: {
"start_location":
'${data[0]["start_location"]['lat']},${data[0]["start_location"]['lng']}',
"end_location":
'${data[0]["end_location"]['lat']},${data[0]["end_location"]['lng']}',
"date": DateTime.now().toString(),
"time": DateTime.now().toString(),
"endtime": durationToAdd.toString(),
"price": totalPassenger.toStringAsFixed(2),
"passenger_id": box.read(BoxName.passengerID).toString(),
"driver_id": dataCarsLocationByPassenger['data'][carsOrder]['driver_id']
.toString(),
"status": "waiting",
'carType': box.read(BoxName.carType),
"price_for_driver": totalPassenger.toString(),
"price_for_passenger": totalME.toString(),
"distance": distance.toString(),
"paymentMethod": paymentController.isWalletChecked.toString(),
});
}
delayAndFetchRideStatusForAllDriverAvailable(rideId);
update();
}
icreaseForSameRideAndDelay() {
@@ -1781,7 +1814,7 @@ class MapPassengerController extends GetxController {
confirmRideForAllDriverAvailable();
// delayAndFetchRideStatusForAllDriverAvailable(rideId);
} else if (rideStatusDelayed == 'Apply' || statusRide == 'Apply') {
Log.print('rideStatusDelayed == Apply: ${rideStatusDelayed}');
Log.print('rideStatusDelayed == Apply: $rideStatusDelayed');
// todo play sound
Get.find<AudioRecorderController>()
.playSoundFromAssets('assets/start.wav');
@@ -1837,17 +1870,29 @@ class MapPassengerController extends GetxController {
int attemptCounter = 0;
bool isApplied = false;
tick = 0;
Log.print('tick delayAndFetchRideStatusForAllDriverAvailable: $tick');
bool shouldContinueSearching = true; // Flag to control searching
void fetchRideStatus() async {
if (attemptCounter < maxAttempts && isApplied == false || tick < 15) {
if (attemptCounter < maxAttempts &&
!isApplied &&
shouldContinueSearching) {
attemptCounter++;
tick++;
var res = await getRideStatus(rideId);
String rideStatusDelayed = res.toString();
if (rideStatusDelayed == 'Apply' || rideStatusDelayed == 'Applied') {
if (rideStatusDelayed == 'Cancel') {
shouldContinueSearching = false; // Stop searching
attemptCounter = maxAttempts + 1;
NotificationController().showNotification(
"Order Cancelled".tr, "you canceled order".tr, 'ding');
} else if (rideStatusDelayed == 'Apply' ||
rideStatusDelayed == 'Applied') {
await getUpdatedRideForDriverApply(rideId);
NotificationController().showNotification(
'Order Accepted'.tr,
'$driverName ${'accepted your order at price'.tr} ${totalPassenger.toStringAsFixed(1)} ${'with type'.tr} ${box.read(BoxName.carType)}',
'ding');
isApplied = true;
shouldFetch = false;
statusRide = 'Apply';
@@ -1855,89 +1900,14 @@ class MapPassengerController extends GetxController {
isSearchingWindow = false;
startTimer();
update();
startTimerFromDriverToPassengerAfterApplied();
shouldContinueSearching = false; // Stop searching if applied
} else if (attemptCounter >= maxAttempts &&
rideStatusDelayed != 'Cancel') {
shouldFetch = false;
// If the status is still not "Apply" after 15 attempts
MyDialog().getDialog('upgrade price'.tr,
'You can upgrade price to may driver accept your order'.tr, () {
Get.back();
Get.defaultDialog(
barrierDismissible: false,
title: "Increase Your Trip Fee (Optional)".tr,
titleStyle: AppStyle.title,
content: Column(
children: [
Text(
"We haven't found any drivers yet. Consider increasing your trip fee to make your offer more attractive to drivers."
.tr,
style: AppStyle.title,
textAlign: TextAlign.center,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
IconButton(
onPressed: () {
increasFeeFromPassenger.text =
(totalPassenger + 6).toStringAsFixed(1);
update();
},
icon: Column(
children: [
Text(
'6',
style: AppStyle.number,
),
Container(
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: AppColor.greenColor),
child: const Icon(
Icons.arrow_circle_up,
size: 30,
color: AppColor.secondaryColor,
),
),
],
),
),
SizedBox(
width: 100,
child: Form(
key: increaseFeeFormKey,
child: MyTextForm(
controller: increasFeeFromPassenger,
label: totalPassenger.toStringAsFixed(2),
hint: totalPassenger.toStringAsFixed(2),
type: TextInputType.number),
),
),
],
)
],
),
actions: [
MyElevatedButton(
title: "No, thanks",
onPressed: () async {
await cancelRide();
Get.back();
}),
MyElevatedButton(
title: "Increase Fee".tr,
kolor: AppColor.greenColor,
onPressed: () {
increaseFeeByPassengerAndReOrder();
})
],
);
});
shouldContinueSearching = false; // Stop searching
// Show dialog to increase fee...
update();
print('Stopped fetching ride status after 15 attempts.');
} else {
Timer(const Duration(seconds: 2), fetchRideStatus);
}
@@ -2026,7 +1996,7 @@ class MapPassengerController extends GetxController {
FirebaseMessagesController().sendNotificationToDriverMAP(
'Order Applied'.tr,
'$driverName Apply order\nTake attention in other order'.tr,
driverToken,
driverToken.toString(),
[],
'start.wav',
);
@@ -2912,7 +2882,7 @@ class MapPassengerController extends GetxController {
FirebaseMessagesController().sendNotificationToDriverMAP(
'Cancel Trip'.tr,
'Trip Cancelled'.tr,
driverToken,
driverToken.toString(),
[],
'cancel.wav',
);
@@ -3313,23 +3283,56 @@ class MapPassengerController extends GetxController {
// Log.print('BoxName.serverChosen: ${box.read(BoxName.serverChosen)}');
newStartPointLocation = passengerLocation;
Log.print('passengerLocation: ${passengerLocation}');
Log.print('passengerLocation: $passengerLocation');
speed = _locationData.speed!;
// //print location details
isLoading = false;
update();
}
// LatLngBounds calculateBounds(double lat, double lng, double radiusInMeters) {
// const double earthRadius = 6378137.0; // Earth's radius in meters
// double latDelta = radiusInMeters / earthRadius * (180 / pi);
// double lngDelta =
// radiusInMeters / (earthRadius * cos(pi * lat / 180)) * (180 / pi);
// return LatLngBounds(
// southwest: LatLng(lat - latDelta, lng - lngDelta),
// northeast: LatLng(lat + latDelta, lng + lngDelta),
// );
// }
LatLngBounds calculateBounds(double lat, double lng, double radiusInMeters) {
const double earthRadius = 6378137.0; // Earth's radius in meters
double latDelta = radiusInMeters / earthRadius * (180 / pi);
double latDelta = (radiusInMeters / earthRadius) * (180 / pi);
double lngDelta =
radiusInMeters / (earthRadius * cos(pi * lat / 180)) * (180 / pi);
(radiusInMeters / (earthRadius * cos(pi * lat / 180))) * (180 / pi);
double minLat = lat - latDelta;
double maxLat = lat + latDelta;
double minLng = lng - lngDelta;
double maxLng = lng + lngDelta;
// Ensure the latitude is between -90 and 90
minLat = max(-90.0, minLat);
maxLat = min(90.0, maxLat);
// Ensure the longitude is between -180 and 180
minLng = (minLng + 180) % 360 - 180;
maxLng = (maxLng + 180) % 360 - 180;
// Ensure the bounds are in the correct order
if (minLng > maxLng) {
double temp = minLng;
minLng = maxLng;
maxLng = temp;
}
return LatLngBounds(
southwest: LatLng(lat - latDelta, lng - lngDelta),
northeast: LatLng(lat + latDelta, lng + lngDelta),
southwest: LatLng(minLat, minLng),
northeast: LatLng(maxLat, maxLng),
);
}
@@ -3470,7 +3473,7 @@ class MapPassengerController extends GetxController {
i < dataCarsLocationByPassenger['message'].length;
i++) {
var carLocation = dataCarsLocationByPassenger['message'][i];
Log.print('carLocation: ${carLocation}');
Log.print('carLocation: $carLocation');
// Calculate distance between passenger's location and current driver's location
final distance = Geolocator.distanceBetween(
@@ -3482,8 +3485,8 @@ class MapPassengerController extends GetxController {
// Calculate duration assuming an average speed of 25 km/h (adjust as needed)
int durationToPassenger = (distance * 25 * (1000 / 3600)).round();
Log.print('distance: ${distance}');
Log.print('durationToPassenger: ${durationToPassenger}');
Log.print('distance: $distance');
Log.print('durationToPassenger: $durationToPassenger');
// Update the UI with the distance and duration for each car
update();
@@ -3499,7 +3502,7 @@ class MapPassengerController extends GetxController {
latitude: double.parse(carLocation['latitude']),
longitude: double.parse(carLocation['longitude']),
);
Log.print('nearestCar: ${nearestCar}');
Log.print('nearestCar: $nearestCar');
// Update the UI with the nearest driver
update();
}
@@ -4283,7 +4286,7 @@ class MapPassengerController extends GetxController {
totalCostPassenger = totalDriver1 + (totalDriver1 * kazan / 100);
totalPassenger = costSpeed + (costSpeed * kazan / 100);
if (isInUniversity) {
Log.print('isInUniversity: ${isInUniversity}');
Log.print('isInUniversity: $isInUniversity');
totalPassengerComfort =
20 + (costComfort + (costComfort * kazan / 100)).ceilToDouble();
totalPassengerLady =
@@ -4325,7 +4328,7 @@ class MapPassengerController extends GetxController {
totalME = totalCostPassenger - tax;
costForDriver = fuelPrice * (20 / 210) * distance;
} else {
Log.print('isInUniversity: ${isInUniversity}');
Log.print('isInUniversity: $isInUniversity');
totalPassengerComfort =
(costComfort + (costComfort * kazan / 100)).ceilToDouble();
totalPassengerLady =