26-1-20/1
This commit is contained in:
@@ -22,6 +22,7 @@ import '../../../print.dart';
|
||||
import '../../../views/home/my_wallet/walet_captain.dart';
|
||||
import '../../../views/widgets/elevated_btn.dart';
|
||||
import '../../firebase/firbase_messge.dart';
|
||||
import '../../functions/background_service.dart';
|
||||
import '../../functions/crud.dart';
|
||||
import '../../functions/location_background_controller.dart';
|
||||
import '../../functions/location_controller.dart';
|
||||
@@ -33,6 +34,7 @@ class HomeCaptainController extends GetxController {
|
||||
Duration activeDuration = Duration.zero;
|
||||
Timer? activeTimer;
|
||||
Map data = {};
|
||||
bool isHomeMapActive = true;
|
||||
BitmapDescriptor carIcon = BitmapDescriptor.defaultMarker;
|
||||
bool isLoading = true;
|
||||
late double kazan = 0;
|
||||
@@ -80,63 +82,75 @@ class HomeCaptainController extends GetxController {
|
||||
void toggleHeatmap() async {
|
||||
isHeatmapVisible = !isHeatmapVisible;
|
||||
if (isHeatmapVisible) {
|
||||
await _fetchAndDrawHeatmap();
|
||||
await fetchAndDrawHeatmap();
|
||||
} else {
|
||||
heatmapPolygons.clear();
|
||||
}
|
||||
update(); // تحديث الواجهة
|
||||
}
|
||||
|
||||
// دالة جلب البيانات ورسمها
|
||||
Future<void> _fetchAndDrawHeatmap() async {
|
||||
isLoading = true;
|
||||
update();
|
||||
// داخل MapDriverController
|
||||
|
||||
// استبدل هذا الرابط برابط ملف JSON الذي يولده كود PHP
|
||||
// مثال: https://your-domain.com/api/driver/heatmap_data.json
|
||||
// متغير لتخزين المربعات
|
||||
// Set<Polygon> heatmapPolygons = {};
|
||||
|
||||
// دالة جلب البيانات ورسم الخريطة
|
||||
Future<void> fetchAndDrawHeatmap() async {
|
||||
// استخدم الرابط المباشر لملف JSON لسرعة قصوى
|
||||
final String jsonUrl =
|
||||
"https://rides.intaleq.xyz/intaleq/ride/heatmap/heatmap_data.json";
|
||||
"https://api.intaleq.xyz/intaleq/ride/rides/heatmap_live.json";
|
||||
|
||||
try {
|
||||
final response = await http.get(Uri.parse(jsonUrl));
|
||||
// نستخدم timestamp لمنع الكاش من الموبايل نفسه
|
||||
final response = await http.get(
|
||||
Uri.parse("$jsonUrl?t=${DateTime.now().millisecondsSinceEpoch}"));
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final List<dynamic> data = json.decode(response.body);
|
||||
_generateGoogleMapPolygons(data);
|
||||
} else {
|
||||
print("Failed to load heatmap data");
|
||||
_generatePolygons(data);
|
||||
}
|
||||
} catch (e) {
|
||||
print("Error fetching heatmap: $e");
|
||||
} finally {
|
||||
isLoading = false;
|
||||
update();
|
||||
print("Heatmap Error: $e");
|
||||
}
|
||||
} // تحويل البيانات إلى مربعات على خريطة جوجل
|
||||
}
|
||||
|
||||
void _generateGoogleMapPolygons(List<dynamic> data) {
|
||||
void _generatePolygons(List<dynamic> data) {
|
||||
Set<Polygon> tempPolygons = {};
|
||||
// نصف قطر المربع (تقريباً 0.0005 يعادل 50-60 متر، مما يعطي مربع 100 متر)
|
||||
// يجب أن يتناسب مع الـ precision المستخدم في PHP
|
||||
|
||||
// الأوفست لرسم المربع (نصف حجم الشبكة)
|
||||
// الشبكة دقتها 0.01 درجة، لذا نصفها 0.005
|
||||
double offset = 0.005;
|
||||
|
||||
for (var point in data) {
|
||||
double lat = double.parse(point['lat'].toString());
|
||||
double lng = double.parse(point['lng'].toString());
|
||||
int count = int.parse(point['count'].toString());
|
||||
|
||||
// تحديد اللون بناءً على الكثافة
|
||||
String intensity = point['intensity'] ?? 'low';
|
||||
int count = int.parse(point['count'].toString()); // ✅ جلب العدد
|
||||
|
||||
Color color;
|
||||
if (count >= 5) {
|
||||
color = Colors.red.withOpacity(0.5); // عالي جداً
|
||||
} else if (count >= 3) {
|
||||
color = Colors.orange.withOpacity(0.5); // متوسط
|
||||
Color strokeColor;
|
||||
|
||||
// 🧠 منطق الألوان: ندمج الذكاء (Intensity) مع العدد (Count)
|
||||
if (intensity == 'high' || count >= 5) {
|
||||
// منطقة مشتعلة (أحمر)
|
||||
// إما فيها طلبات ضائعة (Timeout) أو فيها عدد كبير من الطلبات
|
||||
color = Colors.red.withOpacity(0.35);
|
||||
strokeColor = Colors.red.withOpacity(0.8);
|
||||
} else if (intensity == 'medium' || count >= 3) {
|
||||
// منطقة متوسطة (برتقالي)
|
||||
color = Colors.orange.withOpacity(0.35);
|
||||
strokeColor = Colors.orange.withOpacity(0.8);
|
||||
} else {
|
||||
color = Colors.green.withOpacity(0.4); // منخفض
|
||||
// منطقة خفيفة (أصفر)
|
||||
color = Colors.yellow.withOpacity(0.3);
|
||||
strokeColor = Colors.yellow.withOpacity(0.6);
|
||||
}
|
||||
|
||||
// إنشاء المربع
|
||||
// رسم المربع
|
||||
tempPolygons.add(Polygon(
|
||||
polygonId: PolygonId("$lat-$lng"),
|
||||
consumeTapEvents: true, // للسماح بالضغط عليه مستقبلاً
|
||||
points: [
|
||||
LatLng(lat - offset, lng - offset),
|
||||
LatLng(lat + offset, lng - offset),
|
||||
@@ -144,13 +158,19 @@ class HomeCaptainController extends GetxController {
|
||||
LatLng(lat - offset, lng + offset),
|
||||
],
|
||||
fillColor: color,
|
||||
strokeColor: color.withOpacity(0.8),
|
||||
strokeWidth: 1,
|
||||
visible: true,
|
||||
strokeColor: strokeColor,
|
||||
strokeWidth: 2,
|
||||
));
|
||||
}
|
||||
|
||||
heatmapPolygons = tempPolygons;
|
||||
update(); // تحديث الخريطة
|
||||
}
|
||||
|
||||
// دالة لتشغيل الخريطة الحرارية كل فترة (مثلاً عند فتح الصفحة)
|
||||
void startHeatmapCycle() {
|
||||
fetchAndDrawHeatmap();
|
||||
// يمكن تفعيل Timer هنا لو أردت تحديثها تلقائياً كل 5 دقائق
|
||||
}
|
||||
|
||||
void goToWalletFromConnect() {
|
||||
@@ -179,11 +199,14 @@ class HomeCaptainController extends GetxController {
|
||||
|
||||
String stringActiveDuration = '';
|
||||
void onButtonSelected() {
|
||||
// totalPoints = Get.find<CaptainWalletController>().totalPoints;
|
||||
|
||||
// تم الإصلاح: التأكد من أن المتحكم موجود قبل استخدامه لتجنب الكراش
|
||||
if (!Get.isRegistered<CaptainWalletController>()) {
|
||||
Get.put(CaptainWalletController());
|
||||
}
|
||||
totalPoints = Get.find<CaptainWalletController>().totalPoints;
|
||||
isActive = !isActive;
|
||||
if (isActive) {
|
||||
if (double.parse(totalPoints) > -30000) {
|
||||
if (double.parse(totalPoints) > -200) {
|
||||
locationController.startLocationUpdates();
|
||||
HapticFeedback.heavyImpact();
|
||||
// locationBackController.startBackLocation();
|
||||
@@ -214,6 +237,107 @@ class HomeCaptainController extends GetxController {
|
||||
// }
|
||||
}
|
||||
|
||||
// متغيرات العداد للحظر
|
||||
RxString remainingBlockTimeStr = "".obs;
|
||||
Timer? _blockTimer;
|
||||
|
||||
/// دالة الفحص والدايلوج
|
||||
void checkAndShowBlockDialog() {
|
||||
String? blockStr = box.read(BoxName.blockUntilDate);
|
||||
if (blockStr == null || blockStr.isEmpty) return;
|
||||
|
||||
DateTime blockExpiry = DateTime.parse(blockStr);
|
||||
DateTime now = DateTime.now();
|
||||
|
||||
if (now.isBefore(blockExpiry)) {
|
||||
// 1. إجبار السائق على وضع الأوفلاين
|
||||
box.write(BoxName.statusDriverLocation, 'blocked');
|
||||
update();
|
||||
|
||||
// 2. بدء العداد
|
||||
_startBlockCountdown(blockExpiry);
|
||||
|
||||
// 3. إظهار الديالوج المانع
|
||||
Get.defaultDialog(
|
||||
title: "حسابك مقيد مؤقتاً ⛔",
|
||||
titleStyle:
|
||||
const TextStyle(color: Colors.red, fontWeight: FontWeight.bold),
|
||||
barrierDismissible: false, // 🚫 ممنوع الإغلاق بالضغط خارجاً
|
||||
onWillPop: () async => false, // 🚫 ممنوع زر الرجوع في الأندرويد
|
||||
content: Obx(() => Column(
|
||||
children: [
|
||||
const Icon(Icons.timer_off_outlined,
|
||||
size: 50, color: Colors.orange),
|
||||
const SizedBox(height: 15),
|
||||
const Text(
|
||||
"لقد تجاوزت حد الإلغاء المسموح به (3 مرات).\nلا يمكنك العمل حتى انتهاء العقوبة.",
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Text(
|
||||
remainingBlockTimeStr.value, // 🔥 الوقت يتحدث هنا
|
||||
style: const TextStyle(
|
||||
fontSize: 24,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.black87),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
],
|
||||
)),
|
||||
confirm: Obx(() {
|
||||
// الزر يكون مفعلاً فقط عندما ينتهي الوقت
|
||||
bool isFinished = remainingBlockTimeStr.value == "00:00:00" ||
|
||||
remainingBlockTimeStr.value == "Done";
|
||||
return ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: isFinished ? Colors.green : Colors.grey,
|
||||
),
|
||||
onPressed: isFinished
|
||||
? () {
|
||||
Get.back(); // إغلاق الديالوج
|
||||
box.remove(BoxName.blockUntilDate); // إزالة الحظر
|
||||
Get.snackbar("أهلاً بك", "يمكنك الآن استقبال الطلبات",
|
||||
backgroundColor: Colors.green);
|
||||
}
|
||||
: null, // زر معطل
|
||||
child: Text(isFinished ? "Go Online" : "انتظر انتهاء الوقت"),
|
||||
);
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
// الوقت انتهى أصلاً -> تنظيف
|
||||
box.remove(BoxName.blockUntilDate);
|
||||
}
|
||||
}
|
||||
|
||||
/// دالة العداد التنازلي
|
||||
void _startBlockCountdown(DateTime expiry) {
|
||||
_blockTimer?.cancel();
|
||||
_blockTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
|
||||
DateTime now = DateTime.now();
|
||||
if (now.isAfter(expiry)) {
|
||||
// انتهى الوقت
|
||||
remainingBlockTimeStr.value = "Done";
|
||||
timer.cancel();
|
||||
} else {
|
||||
// حساب الفرق وتنسيقه
|
||||
Duration diff = expiry.difference(now);
|
||||
String twoDigits(int n) => n.toString().padLeft(2, "0");
|
||||
String hours = twoDigits(diff.inHours);
|
||||
String minutes = twoDigits(diff.inMinutes.remainder(60));
|
||||
String seconds = twoDigits(diff.inSeconds.remainder(60));
|
||||
|
||||
remainingBlockTimeStr.value = "$hours:$minutes:$seconds";
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
_blockTimer?.cancel();
|
||||
super.onClose();
|
||||
}
|
||||
|
||||
void getRefusedOrderByCaptain() async {
|
||||
DateTime today = DateTime.now();
|
||||
int todayDay = today.day;
|
||||
@@ -232,7 +356,8 @@ class HomeCaptainController extends GetxController {
|
||||
await sql.getCustomQuery(customQuery);
|
||||
countRefuse = results[0]['count'].toString();
|
||||
update();
|
||||
if (int.parse(countRefuse) > 3 || double.parse(totalPoints) <= -3000) {
|
||||
if (double.parse(totalPoints) <= -200) {
|
||||
// if (int.parse(countRefuse) > 3 || double.parse(totalPoints) <= -200) {
|
||||
locationController.stopLocationUpdates();
|
||||
activeStartTime = null;
|
||||
activeTimer?.cancel();
|
||||
@@ -322,9 +447,9 @@ class HomeCaptainController extends GetxController {
|
||||
isLoading = true;
|
||||
update();
|
||||
// This ensures we try to get a fix, but map doesn't crash if it fails
|
||||
await Get.find<LocationController>().getLocation();
|
||||
await locationController.getLocation();
|
||||
|
||||
var loc = Get.find<LocationController>().myLocation;
|
||||
var loc = locationController.myLocation;
|
||||
if (loc.latitude != 0) {
|
||||
myLocation = loc;
|
||||
}
|
||||
@@ -357,8 +482,35 @@ class HomeCaptainController extends GetxController {
|
||||
}
|
||||
}
|
||||
|
||||
// 3. دالة نستدعيها عند قبول الطلب
|
||||
void pauseHomeMapUpdates() {
|
||||
isHomeMapActive = false;
|
||||
update();
|
||||
}
|
||||
|
||||
// 4. دالة نستدعيها عند العودة للصفحة الرئيسية
|
||||
void resumeHomeMapUpdates() {
|
||||
isHomeMapActive = true;
|
||||
// إنعاش الخريطة عند العودة
|
||||
if (mapHomeCaptainController != null) {
|
||||
onMapCreated(mapHomeCaptainController!);
|
||||
}
|
||||
update();
|
||||
}
|
||||
|
||||
@override
|
||||
void onInit() async {
|
||||
// ✅ طلب الإذونات أولاً
|
||||
bool permissionsGranted = await PermissionsHelper.requestAllPermissions();
|
||||
|
||||
if (permissionsGranted) {
|
||||
// ✅ بدء الخدمة بعد الحصول على الإذونات
|
||||
await BackgroundServiceHelper.startService();
|
||||
print('✅ Background service started successfully');
|
||||
} else {
|
||||
print('❌ لم يتم منح الإذونات - الخدمة لن تعمل');
|
||||
// اعرض رسالة للمستخدم
|
||||
}
|
||||
// await locationBackController.requestLocationPermission();
|
||||
Get.put(FirebaseMessagesController());
|
||||
addToken();
|
||||
@@ -374,24 +526,34 @@ class HomeCaptainController extends GetxController {
|
||||
getCaptainWalletFromBuyPoints();
|
||||
// onMapCreated(mapHomeCaptainController!);
|
||||
// totalPoints = Get.find<CaptainWalletController>().totalPoints.toString();
|
||||
getRefusedOrderByCaptain();
|
||||
// getRefusedOrderByCaptain();
|
||||
// 🔥 الفحص عند تشغيل التطبيق
|
||||
checkAndShowBlockDialog();
|
||||
box.write(BoxName.statusDriverLocation, 'off');
|
||||
// 2. عدل الليسنر ليصبح مشروطاً
|
||||
locationController.addListener(() {
|
||||
// Only animate if active, map is ready, AND location is valid (not 0,0)
|
||||
if (isActive && mapHomeCaptainController != null) {
|
||||
var loc = locationController.myLocation;
|
||||
// الشرط الذهبي: إذا كانت الصفحة غير نشطة أو الخريطة غير موجودة، لا تفعل شيئاً
|
||||
if (!isHomeMapActive || mapHomeCaptainController == null || isClosed)
|
||||
return;
|
||||
|
||||
if (isActive) {
|
||||
// isActive الخاصة بالزر "متصل/غير متصل"
|
||||
var loc = locationController.myLocation;
|
||||
if (loc.latitude != 0 && loc.longitude != 0) {
|
||||
mapHomeCaptainController!.animateCamera(
|
||||
CameraUpdate.newCameraPosition(
|
||||
CameraPosition(
|
||||
target: loc,
|
||||
zoom: 17.5,
|
||||
tilt: 50.0,
|
||||
bearing: locationController.heading,
|
||||
try {
|
||||
mapHomeCaptainController!.animateCamera(
|
||||
CameraUpdate.newCameraPosition(
|
||||
CameraPosition(
|
||||
target: loc,
|
||||
zoom: 17.5,
|
||||
tilt: 50.0,
|
||||
bearing: locationController.heading,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
);
|
||||
} catch (e) {
|
||||
// التقاط الخطأ بصمت إذا حدث أثناء الانتقال
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,245 +1,589 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_overlay_window/flutter_overlay_window.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:sefer_driver/constant/links.dart';
|
||||
import 'package:sefer_driver/main.dart';
|
||||
import 'package:google_maps_flutter/google_maps_flutter.dart';
|
||||
import 'package:geolocator/geolocator.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:just_audio/just_audio.dart';
|
||||
import 'dart:math' as math;
|
||||
import '../../../constant/box_name.dart';
|
||||
import '../../../print.dart';
|
||||
import '../../functions/audio_controller.dart';
|
||||
import '../../functions/crud.dart';
|
||||
import '../../functions/encrypt_decrypt.dart';
|
||||
import '../../functions/location_controller.dart';
|
||||
import 'home_captain_controller.dart';
|
||||
|
||||
class OrderRequestController extends GetxController {
|
||||
double progress = 0;
|
||||
double progressSpeed = 0;
|
||||
import '../../../constant/box_name.dart';
|
||||
import '../../../constant/links.dart';
|
||||
import '../../../main.dart';
|
||||
import '../../../print.dart';
|
||||
import '../../../views/home/Captin/driver_map_page.dart';
|
||||
import '../../../views/home/Captin/orderCaptin/marker_generator.dart';
|
||||
import '../../../views/widgets/mydialoug.dart';
|
||||
import '../../functions/crud.dart';
|
||||
import '../../functions/location_controller.dart';
|
||||
import '../../home/captin/home_captain_controller.dart';
|
||||
import '../../firebase/notification_service.dart';
|
||||
import '../navigation/decode_polyline_isolate.dart';
|
||||
|
||||
class OrderRequestController extends GetxController
|
||||
with WidgetsBindingObserver {
|
||||
// --- متغيرات التايمر ---
|
||||
double progress = 1.0;
|
||||
int duration = 15;
|
||||
int durationSpeed = 20;
|
||||
int remainingTime = 0;
|
||||
int remainingTimeSpeed = 0;
|
||||
String countRefuse = '0';
|
||||
int remainingTime = 15;
|
||||
Timer? _timer;
|
||||
|
||||
bool applied = false;
|
||||
final locationController = Get.put(LocationController());
|
||||
BitmapDescriptor startIcon = BitmapDescriptor.defaultMarker;
|
||||
BitmapDescriptor endIcon = BitmapDescriptor.defaultMarker;
|
||||
final arguments = Get.arguments;
|
||||
var myList;
|
||||
late int hours;
|
||||
late int minutes;
|
||||
GoogleMapController? mapController; // Make it nullable
|
||||
|
||||
// 🔥 متغير لمنع تكرار القبول
|
||||
bool _isRideTakenHandled = false;
|
||||
|
||||
// --- الأيقونات والماركرز ---
|
||||
BitmapDescriptor? driverIcon;
|
||||
Map<MarkerId, Marker> markersMap = {};
|
||||
Set<Marker> get markers => markersMap.values.toSet();
|
||||
|
||||
// --- البيانات والتحكم ---
|
||||
// 🔥 تم إضافة myMapData لدعم السوكيت الجديد
|
||||
List<dynamic>? myList;
|
||||
Map<dynamic, dynamic>? myMapData;
|
||||
|
||||
GoogleMapController? mapController;
|
||||
|
||||
// الإحداثيات (أزلنا late لتجنب الأخطاء القاتلة)
|
||||
double latPassenger = 0.0;
|
||||
double lngPassenger = 0.0;
|
||||
double latDestination = 0.0;
|
||||
double lngDestination = 0.0;
|
||||
|
||||
// --- متغيرات العرض ---
|
||||
String passengerRating = "5.0";
|
||||
String tripType = "Standard";
|
||||
String totalTripDistance = "--";
|
||||
String totalTripDuration = "--";
|
||||
String tripPrice = "--";
|
||||
|
||||
String timeToPassenger = "جاري الحساب...";
|
||||
String distanceToPassenger = "--";
|
||||
|
||||
// --- الخريطة ---
|
||||
Set<Polyline> polylines = {};
|
||||
|
||||
// حالة التطبيق والصوت
|
||||
bool isInBackground = false;
|
||||
final AudioPlayer audioPlayer = AudioPlayer();
|
||||
|
||||
@override
|
||||
Future<void> onInit() async {
|
||||
print('OrderRequestController onInit called');
|
||||
await initializeOrderPage();
|
||||
if (Platform.isAndroid) {
|
||||
bool isOverlayActive = await FlutterOverlayWindow.isActive();
|
||||
if (isOverlayActive) {
|
||||
await FlutterOverlayWindow.closeOverlay();
|
||||
}
|
||||
// 🛑 حماية من الفتح المتكرر لنفس الطلب
|
||||
if (Get.arguments == null) {
|
||||
print("❌ OrderController Error: No arguments received.");
|
||||
Get.back(); // إغلاق الصفحة فوراً
|
||||
return;
|
||||
}
|
||||
|
||||
addCustomStartIcon();
|
||||
addCustomEndIcon();
|
||||
startTimer(
|
||||
myList[6].toString(),
|
||||
myList[16].toString(),
|
||||
);
|
||||
update();
|
||||
super.onInit();
|
||||
WidgetsBinding.instance.addObserver(this);
|
||||
|
||||
_checkOverlay();
|
||||
|
||||
// 🔥 تهيئة البيانات هي الخطوة الأولى والأهم
|
||||
_initializeData();
|
||||
_parseExtraData();
|
||||
|
||||
// 1. تجهيز أيقونة السائق
|
||||
await _prepareDriverIcon();
|
||||
|
||||
// 2. وضع الماركرز المبدئية
|
||||
_updateMarkers(
|
||||
paxTime: "...",
|
||||
paxDist: "",
|
||||
destTime: totalTripDuration,
|
||||
destDist: totalTripDistance);
|
||||
|
||||
// 3. رسم مبدئي
|
||||
_initialMapSetup();
|
||||
|
||||
// 4. الاستماع للسوكيت
|
||||
_listenForRideTaken();
|
||||
|
||||
// 5. حساب المسارين
|
||||
await _calculateFullJourney();
|
||||
|
||||
// 6. تشغيل التايمر
|
||||
startTimer();
|
||||
}
|
||||
|
||||
late LatLngBounds bounds;
|
||||
late List<LatLng> pointsDirection;
|
||||
late String body;
|
||||
late double latPassengerLocation;
|
||||
late double lngPassengerLocation;
|
||||
late double lngPassengerDestination;
|
||||
late double latPassengerDestination;
|
||||
// ----------------------------------------------------------------------
|
||||
// 🔥🔥🔥 Smart Data Handling (List & Map Support) 🔥🔥🔥
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
Future<void> initializeOrderPage() async {
|
||||
final myListString = Get.arguments['myListString'];
|
||||
Log.print('myListString0000: ${myListString}');
|
||||
void _initializeData() {
|
||||
var args = Get.arguments;
|
||||
print("📦 Order Controller Received Type: ${args.runtimeType}");
|
||||
print("📦 Order Controller Data: $args");
|
||||
|
||||
if (Get.arguments['DriverList'] == null ||
|
||||
Get.arguments['DriverList'].isEmpty) {
|
||||
myList = jsonDecode(myListString);
|
||||
Log.print('myList from myListString: ${myList}');
|
||||
} else {
|
||||
myList = Get.arguments['DriverList'];
|
||||
Log.print('myList from DriverList: ${myList}');
|
||||
}
|
||||
|
||||
body = Get.arguments['body'];
|
||||
Duration durationToAdd =
|
||||
Duration(seconds: (double.tryParse(myList[4]) ?? 0).toInt());
|
||||
hours = durationToAdd.inHours;
|
||||
minutes = (durationToAdd.inMinutes % 60).round();
|
||||
startTimerSpeed(myList[6].toString(), body.toString());
|
||||
|
||||
// --- Using the provided logic for initialization ---
|
||||
var cords = myList[0].toString().split(',');
|
||||
var cordDestination = myList[1].toString().split(',');
|
||||
|
||||
double? parseDouble(String value) {
|
||||
try {
|
||||
return double.parse(value);
|
||||
} catch (e) {
|
||||
Log.print("Error parsing value: $value");
|
||||
return null; // or handle the error appropriately
|
||||
if (args != null) {
|
||||
// الحالة 1: قائمة مباشرة (Legacy / Some Firebase formats)
|
||||
if (args is List) {
|
||||
myList = args;
|
||||
}
|
||||
// الحالة 2: خريطة (Map)
|
||||
else if (args is Map) {
|
||||
// أ) هل هي قادمة من Firebase وتحتوي على DriverList؟
|
||||
if (args.containsKey('DriverList')) {
|
||||
var listData = args['DriverList'];
|
||||
if (listData is List) {
|
||||
myList = listData;
|
||||
} else if (listData is String) {
|
||||
// أحياناً تصل كنص مشفر داخل الـ Map
|
||||
try {
|
||||
myList = jsonDecode(listData);
|
||||
} catch (e) {
|
||||
print("Error decoding DriverList: $e");
|
||||
}
|
||||
}
|
||||
}
|
||||
// ب) هل هي قادمة من Socket بالمفاتيح الرقمية ("0", "1", ...)؟
|
||||
else {
|
||||
myMapData = args;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
latPassengerLocation = parseDouble(cords[0]) ?? 0.0;
|
||||
lngPassengerLocation = parseDouble(cords[1]) ?? 0.0;
|
||||
latPassengerDestination = parseDouble(cordDestination[0]) ?? 0.0;
|
||||
lngPassengerDestination = parseDouble(cordDestination[1]) ?? 0.0;
|
||||
// تعبئة الإحداثيات باستخدام الدالة الذكية _getValueAt
|
||||
latPassenger = _parseCoord(_getValueAt(0));
|
||||
lngPassenger = _parseCoord(_getValueAt(1));
|
||||
latDestination = _parseCoord(_getValueAt(3));
|
||||
lngDestination = _parseCoord(_getValueAt(4));
|
||||
|
||||
pointsDirection = [
|
||||
LatLng(latPassengerLocation, lngPassengerLocation),
|
||||
LatLng(latPassengerDestination, lngPassengerDestination)
|
||||
print(
|
||||
"📍 Parsed Coordinates: Pax($latPassenger, $lngPassenger) -> Dest($latDestination, $lngDestination)");
|
||||
}
|
||||
|
||||
/// 🔥 دالة ذكية تجلب القيمة سواء كانت البيانات في List أو Map
|
||||
dynamic _getValueAt(int index) {
|
||||
// الأولوية للقائمة
|
||||
if (myList != null && index < myList!.length) {
|
||||
return myList![index];
|
||||
}
|
||||
// ثم الخريطة (السوكيت) - المفاتيح عبارة عن String
|
||||
if (myMapData != null && myMapData!.containsKey(index.toString())) {
|
||||
return myMapData![index.toString()];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// الدالة التي يستخدمها باقي الكود لجلب البيانات كنصوص
|
||||
String _safeGet(int index) {
|
||||
var val = _getValueAt(index);
|
||||
if (val != null) {
|
||||
return val.toString();
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
double _parseCoord(dynamic val) {
|
||||
if (val == null) return 0.0;
|
||||
String s = val.toString().replaceAll(',', '').trim();
|
||||
if (s.contains(' ')) s = s.split(' ')[0];
|
||||
return double.tryParse(s) ?? 0.0;
|
||||
}
|
||||
|
||||
void _parseExtraData() {
|
||||
passengerRating = _safeGet(33).isEmpty ? "5.0" : _safeGet(33);
|
||||
tripType = _safeGet(31);
|
||||
totalTripDistance = _safeGet(5);
|
||||
totalTripDuration = _safeGet(19);
|
||||
tripPrice = _safeGet(2);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// 🔥🔥🔥 Core Logic: Concurrent API Calls & Bounds 🔥🔥🔥
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
Future<void> _calculateFullJourney() async {
|
||||
try {
|
||||
Position driverPos = await Geolocator.getCurrentPosition(
|
||||
desiredAccuracy: LocationAccuracy.high);
|
||||
LatLng driverLatLng = LatLng(driverPos.latitude, driverPos.longitude);
|
||||
|
||||
updateDriverLocation(driverLatLng, driverPos.heading);
|
||||
|
||||
var pickupFuture = _fetchRouteData(
|
||||
start: driverLatLng,
|
||||
end: LatLng(latPassenger, lngPassenger),
|
||||
color: Colors.amber,
|
||||
id: 'pickup_route');
|
||||
|
||||
var tripFuture = _fetchRouteData(
|
||||
start: LatLng(latPassenger, lngPassenger),
|
||||
end: LatLng(latDestination, lngDestination),
|
||||
color: Colors.green,
|
||||
id: 'trip_route',
|
||||
isDashed: true);
|
||||
|
||||
var results = await Future.wait([pickupFuture, tripFuture]);
|
||||
|
||||
var pickupResult = results[0];
|
||||
var tripResult = results[1];
|
||||
|
||||
if (pickupResult != null) {
|
||||
distanceToPassenger = pickupResult['distance_text'];
|
||||
timeToPassenger = pickupResult['duration_text'];
|
||||
polylines.add(pickupResult['polyline']);
|
||||
}
|
||||
|
||||
if (tripResult != null) {
|
||||
totalTripDistance = tripResult['distance_text'];
|
||||
totalTripDuration = tripResult['duration_text'];
|
||||
polylines.add(tripResult['polyline']);
|
||||
}
|
||||
|
||||
await _updateMarkers(
|
||||
paxTime: timeToPassenger,
|
||||
paxDist: distanceToPassenger,
|
||||
destTime: totalTripDuration,
|
||||
destDist: totalTripDistance);
|
||||
|
||||
zoomToFitRide(driverLatLng);
|
||||
|
||||
update();
|
||||
} catch (e) {
|
||||
print("❌ Error in Journey Calculation: $e");
|
||||
}
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>?> _fetchRouteData(
|
||||
{required LatLng start,
|
||||
required LatLng end,
|
||||
required Color color,
|
||||
required String id,
|
||||
bool isDashed = false}) async {
|
||||
try {
|
||||
// حماية من الإحداثيات الصفرية
|
||||
if (start.latitude == 0 || end.latitude == 0) return null;
|
||||
|
||||
String apiUrl = "https://routesjo.intaleq.xyz/route/v1/driving";
|
||||
String coords =
|
||||
"${start.longitude},${start.latitude};${end.longitude},${end.latitude}";
|
||||
String url = "$apiUrl/$coords?steps=false&overview=full";
|
||||
|
||||
var response = await http.get(Uri.parse(url));
|
||||
if (response.statusCode == 200) {
|
||||
var json = jsonDecode(response.body);
|
||||
if (json['code'] == 'Ok' && json['routes'].isNotEmpty) {
|
||||
var route = json['routes'][0];
|
||||
|
||||
double distM = double.parse(route['distance'].toString());
|
||||
double durS = double.parse(route['duration'].toString());
|
||||
|
||||
String distText = "${(distM / 1000).toStringAsFixed(1)} كم";
|
||||
String durText = "${(durS / 60).toStringAsFixed(0)} دقيقة";
|
||||
|
||||
String geometry = route['geometry'];
|
||||
List<LatLng> points = await compute(decodePolylineIsolate, geometry);
|
||||
|
||||
Polyline polyline = Polyline(
|
||||
polylineId: PolylineId(id),
|
||||
color: color,
|
||||
width: 5,
|
||||
points: points,
|
||||
patterns:
|
||||
isDashed ? [PatternItem.dash(10), PatternItem.gap(5)] : [],
|
||||
startCap: Cap.roundCap,
|
||||
endCap: Cap.roundCap,
|
||||
);
|
||||
|
||||
return {
|
||||
'distance_text': distText,
|
||||
'duration_text': durText,
|
||||
'polyline': polyline
|
||||
};
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
print("Route Fetch Error: $e");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
void zoomToFitRide(LatLng driverPos) {
|
||||
if (mapController == null) return;
|
||||
|
||||
// حماية من النقاط الصفرية
|
||||
if (latPassenger == 0 || latDestination == 0) return;
|
||||
|
||||
List<LatLng> points = [
|
||||
driverPos,
|
||||
LatLng(latPassenger, lngPassenger),
|
||||
LatLng(latDestination, lngDestination),
|
||||
];
|
||||
Log.print('pointsDirection: $pointsDirection');
|
||||
|
||||
calculateBounds();
|
||||
double minLat = points.first.latitude;
|
||||
double maxLat = points.first.latitude;
|
||||
double minLng = points.first.longitude;
|
||||
double maxLng = points.first.longitude;
|
||||
|
||||
for (var p in points) {
|
||||
if (p.latitude < minLat) minLat = p.latitude;
|
||||
if (p.latitude > maxLat) maxLat = p.latitude;
|
||||
if (p.longitude < minLng) minLng = p.longitude;
|
||||
if (p.longitude > maxLng) maxLng = p.longitude;
|
||||
}
|
||||
|
||||
mapController!.animateCamera(CameraUpdate.newLatLngBounds(
|
||||
LatLngBounds(
|
||||
southwest: LatLng(minLat, minLng),
|
||||
northeast: LatLng(maxLat, maxLng),
|
||||
),
|
||||
100.0,
|
||||
));
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Markers & Setup
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
Future<void> _prepareDriverIcon() async {
|
||||
driverIcon = await MarkerGenerator.createDriverMarker();
|
||||
}
|
||||
|
||||
Future<void> _updateMarkers(
|
||||
{required String paxTime,
|
||||
required String paxDist,
|
||||
String? destTime,
|
||||
String? destDist}) async {
|
||||
// حماية إذا لم يتم جلب الإحداثيات
|
||||
if (latPassenger == 0 || latDestination == 0) return;
|
||||
|
||||
final BitmapDescriptor pickupIcon =
|
||||
await MarkerGenerator.createCustomMarkerBitmap(
|
||||
title: paxTime,
|
||||
subtitle: paxDist,
|
||||
color: Colors.green.shade700,
|
||||
iconData: Icons.person_pin_circle,
|
||||
);
|
||||
|
||||
final BitmapDescriptor dropoffIcon =
|
||||
await MarkerGenerator.createCustomMarkerBitmap(
|
||||
title: destTime ?? totalTripDuration,
|
||||
subtitle: destDist ?? totalTripDistance,
|
||||
color: Colors.red.shade800,
|
||||
iconData: Icons.flag,
|
||||
);
|
||||
|
||||
markersMap[const MarkerId('pax')] = Marker(
|
||||
markerId: const MarkerId('pax'),
|
||||
position: LatLng(latPassenger, lngPassenger),
|
||||
icon: pickupIcon,
|
||||
anchor: const Offset(0.5, 0.85),
|
||||
);
|
||||
|
||||
markersMap[const MarkerId('dest')] = Marker(
|
||||
markerId: const MarkerId('dest'),
|
||||
position: LatLng(latDestination, lngDestination),
|
||||
icon: dropoffIcon,
|
||||
anchor: const Offset(0.5, 0.85),
|
||||
);
|
||||
|
||||
update();
|
||||
}
|
||||
|
||||
void _initialMapSetup() async {
|
||||
Position driverPos = await Geolocator.getCurrentPosition();
|
||||
LatLng driverLatLng = LatLng(driverPos.latitude, driverPos.longitude);
|
||||
|
||||
if (driverIcon != null) {
|
||||
markersMap[const MarkerId('driver')] = Marker(
|
||||
markerId: const MarkerId('driver'),
|
||||
position: driverLatLng,
|
||||
icon: driverIcon!,
|
||||
rotation: driverPos.heading,
|
||||
anchor: const Offset(0.5, 0.5),
|
||||
flat: true,
|
||||
zIndex: 10);
|
||||
}
|
||||
|
||||
if (latPassenger != 0 && lngPassenger != 0) {
|
||||
polylines.add(Polyline(
|
||||
polylineId: const PolylineId('temp_line'),
|
||||
points: [driverLatLng, LatLng(latPassenger, lngPassenger)],
|
||||
color: Colors.grey,
|
||||
width: 2,
|
||||
patterns: [PatternItem.dash(10), PatternItem.gap(10)],
|
||||
));
|
||||
|
||||
zoomToFitRide(driverLatLng);
|
||||
}
|
||||
|
||||
update();
|
||||
}
|
||||
|
||||
void updateDriverLocation(LatLng newPos, double heading) {
|
||||
if (driverIcon != null) {
|
||||
markersMap[const MarkerId('driver')] = Marker(
|
||||
markerId: const MarkerId('driver'),
|
||||
position: newPos,
|
||||
icon: driverIcon!,
|
||||
rotation: heading,
|
||||
anchor: const Offset(0.5, 0.5),
|
||||
flat: true,
|
||||
zIndex: 10,
|
||||
);
|
||||
update();
|
||||
}
|
||||
}
|
||||
|
||||
void onMapCreated(GoogleMapController controller) {
|
||||
mapController = controller;
|
||||
animateCameraToBounds();
|
||||
}
|
||||
|
||||
void calculateBounds() {
|
||||
double minLat = math.min(latPassengerLocation, latPassengerDestination);
|
||||
double maxLat = math.max(latPassengerLocation, latPassengerDestination);
|
||||
double minLng = math.min(lngPassengerLocation, lngPassengerDestination);
|
||||
double maxLng = math.max(lngPassengerLocation, lngPassengerDestination);
|
||||
|
||||
bounds = LatLngBounds(
|
||||
southwest: LatLng(minLat, minLng),
|
||||
northeast: LatLng(maxLat, maxLng),
|
||||
);
|
||||
Log.print('Calculated Bounds: $bounds');
|
||||
}
|
||||
|
||||
void animateCameraToBounds() {
|
||||
if (mapController != null) {
|
||||
mapController!.animateCamera(CameraUpdate.newLatLngBounds(bounds, 80.0));
|
||||
} else {
|
||||
Log.print('mapController is null, cannot animate camera.');
|
||||
}
|
||||
}
|
||||
|
||||
getRideDEtailsForBackgroundOrder(String rideId) async {
|
||||
await CRUD().get(link: AppLink.getRidesDetails, payload: {
|
||||
'id': rideId,
|
||||
});
|
||||
}
|
||||
|
||||
void addCustomStartIcon() async {
|
||||
ImageConfiguration config = const ImageConfiguration(size: Size(30, 30));
|
||||
BitmapDescriptor.asset(
|
||||
config,
|
||||
'assets/images/A.png',
|
||||
).then((value) {
|
||||
startIcon = value;
|
||||
update();
|
||||
});
|
||||
}
|
||||
|
||||
void addCustomEndIcon() {
|
||||
ImageConfiguration config = const ImageConfiguration(size: Size(30, 30));
|
||||
BitmapDescriptor.asset(
|
||||
config,
|
||||
'assets/images/b.png',
|
||||
).then((value) {
|
||||
endIcon = value;
|
||||
update();
|
||||
});
|
||||
}
|
||||
|
||||
void changeApplied() {
|
||||
applied = true;
|
||||
update();
|
||||
}
|
||||
|
||||
double mpg = 0;
|
||||
calculateConsumptionFuel() {
|
||||
mpg = Get.find<HomeCaptainController>().fuelPrice / 12;
|
||||
}
|
||||
|
||||
bool _timerActive = false;
|
||||
|
||||
Future<void> startTimer(String driverID, String orderID) async {
|
||||
_timerActive = true;
|
||||
for (int i = 0; i <= duration && _timerActive; i++) {
|
||||
await Future.delayed(const Duration(seconds: 1));
|
||||
progress = i / duration;
|
||||
remainingTime = duration - i;
|
||||
update();
|
||||
}
|
||||
if (remainingTime == 0 && _timerActive) {
|
||||
if (applied == false) {
|
||||
endTimer();
|
||||
//refuseOrder(orderID);
|
||||
// --- قبول الطلب وإدارة التايمر ---
|
||||
void startTimer() {
|
||||
_timer?.cancel();
|
||||
remainingTime = duration;
|
||||
_playAudio();
|
||||
_timer = Timer.periodic(const Duration(seconds: 1), (timer) {
|
||||
if (remainingTime <= 0) {
|
||||
timer.cancel();
|
||||
_stopAudio();
|
||||
if (!applied) Get.back();
|
||||
} else {
|
||||
remainingTime--;
|
||||
progress = remainingTime / duration;
|
||||
update();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void endTimer() => _timer?.cancel();
|
||||
void changeApplied() => applied = true;
|
||||
|
||||
void _playAudio() async {
|
||||
try {
|
||||
await audioPlayer.setAsset('assets/order.mp3', preload: true);
|
||||
await audioPlayer.setLoopMode(LoopMode.one);
|
||||
await audioPlayer.play();
|
||||
} catch (e) {
|
||||
print(e);
|
||||
}
|
||||
}
|
||||
|
||||
void endTimer() {
|
||||
_timerActive = false;
|
||||
void _stopAudio() => audioPlayer.stop();
|
||||
|
||||
void _listenForRideTaken() {
|
||||
if (locationController.socket != null) {
|
||||
locationController.socket!.off('ride_taken');
|
||||
locationController.socket!.on('ride_taken', (data) {
|
||||
if (_isRideTakenHandled) return;
|
||||
String takenRideId = data['ride_id'].toString();
|
||||
String myCurrentRideId = _safeGet(16);
|
||||
String whoTookIt = data['taken_by_driver_id'].toString();
|
||||
String myDriverId = box.read(BoxName.driverID).toString();
|
||||
|
||||
if (takenRideId == myCurrentRideId && whoTookIt != myDriverId) {
|
||||
_isRideTakenHandled = true;
|
||||
endTimer();
|
||||
if (Get.isSnackbarOpen) Get.closeCurrentSnackbar();
|
||||
if (Get.isDialogOpen ?? false) Get.back();
|
||||
Get.back();
|
||||
Get.snackbar("تنبيه", "تم قبول الطلب من قبل سائق آخر",
|
||||
backgroundColor: Colors.orange, colorText: Colors.white);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void startTimerSpeed(String driverID, orderID) async {
|
||||
for (int i = 0; i <= durationSpeed; i++) {
|
||||
await Future.delayed(const Duration(seconds: 1));
|
||||
progressSpeed = i / durationSpeed;
|
||||
remainingTimeSpeed = durationSpeed - i;
|
||||
update();
|
||||
// Lifecycle
|
||||
@override
|
||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||
super.didChangeAppLifecycleState(state);
|
||||
if (state == AppLifecycleState.paused ||
|
||||
state == AppLifecycleState.detached) {
|
||||
isInBackground = true;
|
||||
} else if (state == AppLifecycleState.resumed) {
|
||||
isInBackground = false;
|
||||
FlutterOverlayWindow.closeOverlay();
|
||||
}
|
||||
if (remainingTimeSpeed == 0) {
|
||||
if (applied == false) {
|
||||
}
|
||||
|
||||
void _checkOverlay() async {
|
||||
if (Platform.isAndroid && await FlutterOverlayWindow.isActive()) {
|
||||
await FlutterOverlayWindow.closeOverlay();
|
||||
}
|
||||
}
|
||||
|
||||
// Accept Order Logic
|
||||
Future<void> acceptOrder() async {
|
||||
endTimer();
|
||||
_stopAudio();
|
||||
|
||||
var res = await CRUD()
|
||||
.post(link: "${AppLink.ride}/rides/acceptRide.php", payload: {
|
||||
'id': _safeGet(16),
|
||||
'rideTimeStart': DateTime.now().toString(),
|
||||
'status': 'Apply',
|
||||
'passengerToken': _safeGet(9),
|
||||
'driver_id': box.read(BoxName.driverID),
|
||||
});
|
||||
|
||||
if (res == 'failure') {
|
||||
MyDialog().getDialog("عذراً، الطلب أخذه سائق آخر.", '', () {
|
||||
Get.back();
|
||||
}
|
||||
Get.back();
|
||||
});
|
||||
} else {
|
||||
Get.put(HomeCaptainController()).changeRideId();
|
||||
box.write(BoxName.statusDriverLocation, 'on');
|
||||
changeApplied();
|
||||
|
||||
var rideArgs = {
|
||||
'passengerLocation': '${_safeGet(0)},${_safeGet(1)}',
|
||||
'passengerDestination': '${_safeGet(3)},${_safeGet(4)}',
|
||||
'Duration': totalTripDuration,
|
||||
'totalCost': _safeGet(26),
|
||||
'Distance': totalTripDistance,
|
||||
'name': _safeGet(8),
|
||||
'phone': _safeGet(10),
|
||||
'email': _safeGet(28),
|
||||
'WalletChecked': _safeGet(13),
|
||||
'tokenPassenger': _safeGet(9),
|
||||
'direction':
|
||||
'https://www.google.com/maps/dir/${_safeGet(0)}/${_safeGet(1)}/',
|
||||
'DurationToPassenger': timeToPassenger,
|
||||
'rideId': _safeGet(16),
|
||||
'passengerId': _safeGet(7),
|
||||
'driverId': _safeGet(18),
|
||||
'durationOfRideValue': totalTripDuration,
|
||||
'paymentAmount': _safeGet(2),
|
||||
'paymentMethod': _safeGet(13) == 'true' ? 'visa' : 'cash',
|
||||
'isHaveSteps': _safeGet(20),
|
||||
'step0': _safeGet(21),
|
||||
'step1': _safeGet(22),
|
||||
'step2': _safeGet(23),
|
||||
'step3': _safeGet(24),
|
||||
'step4': _safeGet(25),
|
||||
'passengerWalletBurc': _safeGet(26),
|
||||
'timeOfOrder': DateTime.now().toString(),
|
||||
'totalPassenger': _safeGet(2),
|
||||
'carType': _safeGet(31),
|
||||
'kazan': _safeGet(32),
|
||||
'startNameLocation': _safeGet(29),
|
||||
'endNameLocation': _safeGet(30),
|
||||
};
|
||||
|
||||
box.write(BoxName.rideArguments, rideArgs);
|
||||
Get.off(() => PassengerLocationMapPage(), arguments: rideArgs);
|
||||
}
|
||||
}
|
||||
|
||||
addRideToNotificationDriverString(
|
||||
orderID,
|
||||
String startLocation,
|
||||
String endLocation,
|
||||
String date,
|
||||
String time,
|
||||
String price,
|
||||
String passengerId,
|
||||
String status,
|
||||
String carType,
|
||||
String passengerRate,
|
||||
String priceForPassenger,
|
||||
String distance,
|
||||
String duration,
|
||||
) async {
|
||||
await CRUD().post(link: AppLink.addWaitingRide, payload: {
|
||||
'id': (orderID),
|
||||
'start_location': startLocation,
|
||||
'end_location': endLocation,
|
||||
'date': date,
|
||||
'time': time,
|
||||
'price': price,
|
||||
'passenger_id': (passengerId),
|
||||
'status': status,
|
||||
'carType': carType,
|
||||
'passengerRate': passengerRate,
|
||||
'price_for_passenger': priceForPassenger,
|
||||
'distance': distance,
|
||||
'duration': duration,
|
||||
});
|
||||
@override
|
||||
void onClose() {
|
||||
locationController.socket?.off('ride_taken');
|
||||
audioPlayer.dispose();
|
||||
WidgetsBinding.instance.removeObserver(this);
|
||||
_timer?.cancel();
|
||||
mapController?.dispose();
|
||||
super.onClose();
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -9,6 +9,7 @@ import 'package:sefer_driver/views/home/on_boarding_page.dart';
|
||||
|
||||
import '../../constant/box_name.dart';
|
||||
import '../../main.dart';
|
||||
import '../../onbording_page.dart';
|
||||
import '../../print.dart';
|
||||
import '../functions/encrypt_decrypt.dart';
|
||||
import '../functions/secure_storage.dart';
|
||||
@@ -94,46 +95,33 @@ class SplashScreenController extends GetxController
|
||||
/// is expected to be handled by an internal process (like login).
|
||||
Future<Widget?> _getNavigationTarget() async {
|
||||
try {
|
||||
// ... (التحقق من OnBoarding)
|
||||
// 1) Onboarding
|
||||
final doneOnboarding = box.read(BoxName.onBoarding) == 'yes';
|
||||
if (!doneOnboarding) {
|
||||
// الأفضل: رجّع الواجهة بدل Get.off داخل الدالة
|
||||
return OnBoardingPage();
|
||||
}
|
||||
|
||||
// 2) Login
|
||||
final isDriverDataAvailable = box.read(BoxName.phoneDriver) != null;
|
||||
// final isPhoneVerified = box.read(BoxName.phoneVerified).toString() == '1'; // <-- ⛔️ تم حذف هذا السطر
|
||||
if (!isDriverDataAvailable) {
|
||||
return LoginCaptin();
|
||||
}
|
||||
|
||||
final loginController = Get.put(LoginDriverController());
|
||||
|
||||
// ✅ --- (الحل) ---
|
||||
// تم حذف التحقق من "isPhoneVerified"
|
||||
// هذا يسمح لـ "loginWithGoogleCredential" بتحديد الحالة والتوجيه الصحيح
|
||||
// (إلى Home أو DriverVerificationScreen أو PhoneNumberScreen)
|
||||
if (isDriverDataAvailable) {
|
||||
Log.print('المستخدم مسجل. جارٍ تهيئة الجلسة...');
|
||||
final AppInitializer initializer = AppInitializer();
|
||||
await initializer.initializeApp();
|
||||
await EncryptionHelper.initialize();
|
||||
|
||||
// الخطوة 1: ضمان جلب الـ JWT أولاً
|
||||
// (هذا هو الكود الذي كان في main.dart)
|
||||
final AppInitializer initializer = AppInitializer();
|
||||
await initializer.initializeApp();
|
||||
await EncryptionHelper.initialize();
|
||||
// انتظر حتى ينتهي جلب الـ JWT
|
||||
await loginController.loginWithGoogleCredential(
|
||||
box.read(BoxName.driverID).toString(),
|
||||
box.read(BoxName.emailDriver).toString(),
|
||||
);
|
||||
|
||||
Log.print('تم جلب الـ JWT. جارٍ تسجيل الدخول ببيانات جوجل...');
|
||||
|
||||
// الخطوة 2: الآن قم بتسجيل الدخول وأنت متأكد أن الـ JWT موجود
|
||||
// يجب تعديل "loginWithGoogleCredential" لتعيد "bool" (نجاح/فشل)
|
||||
await loginController.loginWithGoogleCredential(
|
||||
box.read(BoxName.driverID).toString(),
|
||||
box.read(BoxName.emailDriver).toString(),
|
||||
);
|
||||
|
||||
// إذا نجح تسجيل الدخول (سواء لـ Home أو لـ DriverVerification)
|
||||
// فإن "loginWithGoogleCredential" تقوم بالتوجيه بنفسها
|
||||
// ونحن نُرجع "null" هنا لمنع "SplashScreen" من التوجيه مرة أخرى.
|
||||
} else {
|
||||
Log.print('مستخدم غير مسجل. اذهب لصفحة الدخول.');
|
||||
return LoginCaptin();
|
||||
}
|
||||
return null; // لأن loginWithGoogleCredential يوجّه
|
||||
} catch (e) {
|
||||
Log.print("Error during navigation logic: $e");
|
||||
// أي خطأ فادح (مثل خطأ في جلب الـ JWT) سيعيدك للدخول
|
||||
return LoginCaptin();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user