Files
Siro/siro_admin/lib/views/admin/drivers/monitor_ride.dart
T

801 lines
28 KiB
Dart

import 'package:siro_admin/constant/theme.dart';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart';
import 'package:siro_admin/constant/links.dart';
import 'package:siro_admin/controller/functions/crud.dart';
import 'package:siro_admin/views/widgets/snackbar.dart';
class DriverLocation {
final double latitude;
final double longitude;
final double speed;
final double heading;
final String updatedAt;
DriverLocation({
required this.latitude,
required this.longitude,
required this.speed,
required this.heading,
required this.updatedAt,
});
factory DriverLocation.fromJson(Map<String, dynamic> json) {
return DriverLocation(
latitude: double.tryParse(json['latitude'].toString()) ?? 0.0,
longitude: double.tryParse(json['longitude'].toString()) ?? 0.0,
speed: double.tryParse(json['speed'].toString()) ?? 0.0,
heading: double.tryParse(json['heading'].toString()) ?? 0.0,
updatedAt: json['updated_at'] ?? '',
);
}
}
String normalizePhone(String input) {
final clean = input.replaceAll(RegExp(r'\D+'), '');
if (clean.length == 10 && clean.startsWith('09')) {
return '963${clean.substring(1)}';
}
if (clean.length == 12 && clean.startsWith('963')) return clean;
if (clean.length == 9 && clean.startsWith('9')) return '963$clean';
if (clean.length == 10 && clean.startsWith('07')) {
return '962${clean.substring(1)}';
}
if (clean.length == 12 && clean.startsWith('962')) return clean;
if (clean.length == 9 && clean.startsWith('7')) return '962$clean';
if (clean.length == 11 && clean.startsWith('01')) {
return '20${clean.substring(1)}';
}
if (clean.length == 13 && clean.startsWith('20')) return clean;
return clean;
}
class RideMonitorController extends GetxController {
final String apiUrl = "${AppLink.server}/Admin/rides/monitorRide.php";
final TextEditingController phoneInputController = TextEditingController();
var isTracking = false.obs;
var isLoading = false.obs;
var hasError = false.obs;
var errorMessage = ''.obs;
var driverLocation = Rxn<DriverLocation>();
var driverName = "Unknown Driver".obs;
var rideStatus = "Waiting...".obs;
var startPoint = Rxn<LatLng>();
var endPoint = Rxn<LatLng>();
var routePolyline = <LatLng>[].obs;
final MapController mapController = MapController();
Timer? _timer;
bool _isFirstLoad = true;
@override
void onClose() {
_timer?.cancel();
phoneInputController.dispose();
super.onClose();
}
void startSearch() {
if (phoneInputController.text.trim().isEmpty) {
mySnackbarWarning("يرجى إدخال رقم الهاتف أولاً");
return;
}
hasError.value = false;
errorMessage.value = '';
driverLocation.value = null;
startPoint.value = null;
endPoint.value = null;
routePolyline.clear();
driverName.value = "جاري التحميل...";
rideStatus.value = "جاري التحميل...";
_isFirstLoad = true;
isTracking.value = true;
isLoading.value = true;
fetchRideData();
_timer?.cancel();
_timer = Timer.periodic(const Duration(seconds: 10), (timer) {
fetchRideData();
});
}
void stopTracking() {
_timer?.cancel();
isTracking.value = false;
isLoading.value = false;
}
Future<void> fetchRideData() async {
final phone = phoneInputController.text.trim();
if (phone.isEmpty) return;
try {
String normalizedPhone = normalizePhone(phone);
final response = await CRUD().post(
link: apiUrl,
payload: {"phone": normalizedPhone},
);
if (response != 'failure') {
final jsonResponse = response;
if ((jsonResponse['message'] != null &&
jsonResponse['message'] != 'failure') ||
jsonResponse['status'] == 'success') {
final data =
jsonResponse['message'] ?? jsonResponse['data'] ?? jsonResponse;
if (data['driver_details'] != null) {
driverName.value =
data['driver_details']['fullname'] ?? "سائق غير معروف";
}
if (data['ride_details'] != null) {
rideStatus.value = data['ride_details']['status'] ?? "غير معروف";
String? startStr = data['ride_details']['start_location'];
String? endStr = data['ride_details']['end_location'];
LatLng? s = _parseLatLngString(startStr);
LatLng? e = _parseLatLngString(endStr);
if (s != null && e != null) {
startPoint.value = s;
endPoint.value = e;
routePolyline.value = [s, e];
}
}
final locData = data['driver_location'];
if (locData is Map<String, dynamic>) {
final newLocation = DriverLocation.fromJson(locData);
driverLocation.value = newLocation;
_updateMapBounds();
} else {
if (startPoint.value != null && endPoint.value != null) {
_updateMapBounds();
}
}
hasError.value = false;
} else {
hasError.value = true;
errorMessage.value = jsonResponse['message'] ??
"لم يتم العثور على رقم الهاتف أو لا توجد رحلة نشطة.";
}
} else {
hasError.value = true;
errorMessage.value = "فشل الاتصال بالخادم";
}
} catch (e) {
if (isLoading.value) {
hasError.value = true;
errorMessage.value = e.toString();
}
} finally {
isLoading.value = false;
}
}
LatLng? _parseLatLngString(String? str) {
if (str == null || !str.contains(',')) return null;
try {
final parts = str.split(',');
final lat = double.parse(parts[0].trim());
final lng = double.parse(parts[1].trim());
return LatLng(lat, lng);
} catch (e) {
return null;
}
}
void _updateMapBounds() {
if (!_isFirstLoad) return;
List<LatLng> pointsToFit = [];
if (startPoint.value != null) pointsToFit.add(startPoint.value!);
if (endPoint.value != null) pointsToFit.add(endPoint.value!);
if (driverLocation.value != null) {
pointsToFit.add(LatLng(
driverLocation.value!.latitude, driverLocation.value!.longitude));
}
if (pointsToFit.isNotEmpty) {
try {
final bounds = LatLngBounds.fromPoints(pointsToFit);
mapController.fitCamera(
CameraFit.bounds(
bounds: bounds,
padding: const EdgeInsets.all(80.0),
),
);
_isFirstLoad = false;
} catch (e) {
}
}
}
}
class RideMonitorScreen extends StatelessWidget {
const RideMonitorScreen({super.key});
@override
Widget build(BuildContext context) {
final cs = Theme.of(context).colorScheme;
final RideMonitorController controller = Get.put(RideMonitorController());
return Scaffold(
backgroundColor: cs.surface,
body: Obx(() {
if (!controller.isTracking.value) {
return _buildSearchForm(context, controller, cs);
}
return _buildMapTrackingView(context, controller, cs);
}),
);
}
Widget _buildSearchForm(
BuildContext context, RideMonitorController controller, ColorScheme cs) {
return Column(
children: [
Container(
padding: const EdgeInsets.fromLTRB(16, 50, 16, 16),
child: Row(
children: [
GestureDetector(
onTap: () => Get.back(),
child: Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: cs.surfaceContainerHighest,
borderRadius: BorderRadius.circular(10),
border: Border.all(color: cs.outline),
),
child: Icon(Icons.arrow_back_ios_new_rounded,
color: cs.onSurfaceVariant, size: 16),
),
),
const SizedBox(width: 12),
Text(
"مراقبة الرحلات",
style: TextStyle(
color: cs.onSurface,
fontSize: 17,
fontWeight: FontWeight.bold,
),
),
],
),
),
Expanded(
child: Center(
child: SingleChildScrollView(
physics: const BouncingScrollPhysics(),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24.0),
child: Container(
padding: const EdgeInsets.all(32.0),
decoration: BoxDecoration(
color: cs.surface,
borderRadius: BorderRadius.circular(30),
boxShadow: [
BoxShadow(
color: cs.primary.withValues(alpha: 0.08),
blurRadius: 24,
offset: const Offset(0, 10),
)
],
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: cs.primary.withValues(alpha: 0.1),
shape: BoxShape.circle,
),
child: Icon(Icons.radar_rounded, size: 60, color: cs.primary),
),
const SizedBox(height: 24),
Text(
"تتبع رحلة نشطة",
style: TextStyle(
color: cs.onSurface,
fontSize: 22,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 8),
Text(
"أدخل رقم هاتف السائق أو الراكب للبدء",
style: TextStyle(
color: cs.onSurfaceVariant,
fontSize: 14,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 32),
Container(
decoration: BoxDecoration(
color: cs.surface,
borderRadius: BorderRadius.circular(16),
border: Border.all(color: cs.outline, width: 2),
),
child: TextField(
controller: controller.phoneInputController,
keyboardType: TextInputType.phone,
textDirection: TextDirection.ltr,
style: TextStyle(
color: cs.onSurface,
fontSize: 16,
fontWeight: FontWeight.w600,
),
decoration: InputDecoration(
hintText: "مثال: 0992952235...",
hintStyle: TextStyle(color: cs.onSurfaceVariant),
border: InputBorder.none,
contentPadding: const EdgeInsets.symmetric(
vertical: 18, horizontal: 20),
prefixIcon:
Icon(Icons.phone_rounded, color: cs.primary),
),
),
),
const SizedBox(height: 32),
SizedBox(
width: double.infinity,
height: 56,
child: ElevatedButton(
onPressed: controller.startSearch,
style: ElevatedButton.styleFrom(
backgroundColor: cs.primary,
elevation: 0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
),
child: Text(
"بدء المراقبة",
style: TextStyle(
color: cs.onPrimary,
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
),
),
],
),
),
),
),
),
),
],
);
}
Widget _buildMapTrackingView(
BuildContext context, RideMonitorController controller, ColorScheme cs) {
return Stack(
children: [
FlutterMap(
mapController: controller.mapController,
options: MapOptions(
initialCenter: const LatLng(30.0444, 31.2357),
initialZoom: 12.0,
),
children: [
TileLayer(
urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
userAgentPackageName: 'com.siromove.admin',
),
if (controller.routePolyline.isNotEmpty)
PolylineLayer(
polylines: [
Polyline(
points: controller.routePolyline,
strokeWidth: 6.0,
color: cs.primary.withValues(alpha: 0.9),
borderStrokeWidth: 2.0,
borderColor: cs.primary.withValues(alpha: 0.3),
strokeCap: StrokeCap.round,
strokeJoin: StrokeJoin.round,
),
],
),
MarkerLayer(
markers: [
if (controller.startPoint.value != null)
Marker(
point: controller.startPoint.value!,
width: 30,
height: 30,
child: _buildPointMarker(cs.success, cs),
),
if (controller.endPoint.value != null)
Marker(
point: controller.endPoint.value!,
width: 30,
height: 30,
child: _buildPointMarker(cs.danger, cs),
),
if (controller.driverLocation.value != null)
Marker(
point: LatLng(
controller.driverLocation.value!.latitude,
controller.driverLocation.value!.longitude,
),
width: 80,
height: 80,
child: Transform.rotate(
angle: (controller.driverLocation.value!.heading *
(3.14159 / 180)),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: cs.surface,
shape: BoxShape.circle,
boxShadow: [
BoxShadow(
color: cs.onSurface.withValues(alpha: 0.2),
blurRadius: 10,
spreadRadius: 2,
)
],
),
child: Icon(
Icons.directions_car_rounded,
color: cs.primary,
size: 28,
),
),
const SizedBox(height: 4),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: cs.onSurface,
borderRadius: BorderRadius.circular(6),
),
child: Text(
"${controller.driverLocation.value!.speed.toInt()} كم",
style: TextStyle(
color: cs.onPrimary,
fontSize: 10,
fontWeight: FontWeight.bold,
),
textDirection: TextDirection.rtl,
),
)
],
),
),
),
],
),
],
),
Positioned(
top: MediaQuery.of(context).padding.top + 10,
right: 20,
child: Container(
decoration: BoxDecoration(
color: cs.surface,
shape: BoxShape.circle,
boxShadow: [
BoxShadow(
color: cs.onSurface.withValues(alpha: 0.1),
blurRadius: 10,
offset: const Offset(0, 4),
)
],
),
child: IconButton(
icon: Icon(Icons.close_rounded, color: cs.onSurface, size: 24),
onPressed: controller.stopTracking,
tooltip: "إيقاف المراقبة",
),
),
),
if (controller.isLoading.value &&
controller.driverLocation.value == null &&
controller.startPoint.value == null)
Container(
color: cs.surface.withValues(alpha: 0.8),
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
CircularProgressIndicator(
color: cs.primary, strokeWidth: 3),
const SizedBox(height: 16),
Text(
"جاري تحديد الموقع...",
style: TextStyle(
color: cs.onSurface,
fontWeight: FontWeight.bold,
fontSize: 16,
),
)
],
),
),
),
if (controller.hasError.value)
Center(
child: Container(
margin: const EdgeInsets.all(24),
padding: const EdgeInsets.all(24),
decoration: BoxDecoration(
color: cs.surface,
borderRadius: BorderRadius.circular(24),
boxShadow: [
BoxShadow(
color: cs.onSurface.withValues(alpha: 0.1),
blurRadius: 20,
offset: const Offset(0, 10),
)
],
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: cs.error.withValues(alpha: 0.1),
shape: BoxShape.circle,
),
child: Icon(Icons.error_outline_rounded,
color: cs.error, size: 40),
),
const SizedBox(height: 16),
Text(
"حدث خطأ",
style: TextStyle(
color: cs.onSurface,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 8),
Text(
controller.errorMessage.value,
textAlign: TextAlign.center,
style: TextStyle(color: cs.onSurfaceVariant, height: 1.5),
),
const SizedBox(height: 24),
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: controller.stopTracking,
style: ElevatedButton.styleFrom(
backgroundColor: cs.surface,
foregroundColor: cs.onSurface,
elevation: 0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
padding: const EdgeInsets.symmetric(vertical: 14),
),
child: const Text("رجوع للبحث",
style: TextStyle(fontWeight: FontWeight.bold)),
),
)
],
),
),
),
if (!controller.hasError.value && !controller.isLoading.value)
Positioned(
bottom: 30,
left: 20,
right: 20,
child: Container(
decoration: BoxDecoration(
color: cs.surface,
borderRadius: BorderRadius.circular(24),
boxShadow: [
BoxShadow(
color: cs.onSurface.withValues(alpha: 0.08),
blurRadius: 24,
offset: const Offset(0, 10),
)
],
),
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Row(
children: [
Container(
width: 50,
height: 50,
decoration: BoxDecoration(
color: cs.primary.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(15),
),
child: Icon(Icons.person_rounded,
color: cs.primary, size: 28),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
controller.driverName.value,
style: TextStyle(
color: cs.onSurface,
fontSize: 18,
fontWeight: FontWeight.bold,
),
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 4),
Row(
children: [
Container(
width: 8,
height: 8,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: controller.rideStatus.value
.toLowerCase() ==
'begin'
? cs.success
: cs.warning,
),
),
const SizedBox(width: 6),
Text(
controller.rideStatus.value,
style: TextStyle(
color: cs.onSurfaceVariant,
fontSize: 13,
fontWeight: FontWeight.w600,
),
),
],
),
],
),
),
],
),
const Padding(
padding: EdgeInsets.symmetric(vertical: 16),
child: Divider(height: 1, thickness: 1),
),
if (controller.driverLocation.value != null)
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
_buildModernInfoBadge(
Icons.speed_rounded,
"${controller.driverLocation.value!.speed.toStringAsFixed(1)} كم/س",
cs.info,
cs,
),
Container(
width: 1,
height: 30,
color: cs.outline.withValues(alpha: 0.2)),
_buildModernInfoBadge(
Icons.access_time_rounded,
controller.driverLocation.value!.updatedAt
.split(' ')
.last,
const Color(0xFF8B5CF6),
cs,
),
],
)
else
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(
color: cs.primary, strokeWidth: 2),
),
const SizedBox(width: 10),
Text(
"جاري الاتصال بالسائق...",
style: TextStyle(
color: cs.primary,
fontWeight: FontWeight.w600,
fontSize: 13,
),
),
],
),
],
),
),
),
),
],
);
}
Widget _buildPointMarker(Color color, ColorScheme cs) {
return Container(
decoration: BoxDecoration(
color: color.withValues(alpha: 0.3),
shape: BoxShape.circle,
),
child: Center(
child: Container(
width: 12,
height: 12,
decoration: BoxDecoration(
color: color,
shape: BoxShape.circle,
border: Border.all(color: cs.surface, width: 2),
boxShadow: [
BoxShadow(
color: color.withValues(alpha: 0.5),
blurRadius: 6,
spreadRadius: 1,
)
],
),
),
),
);
}
Widget _buildModernInfoBadge(
IconData icon, String text, Color iconColor, ColorScheme cs) {
return Row(
children: [
Container(
padding: const EdgeInsets.all(6),
decoration: BoxDecoration(
color: iconColor.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(8),
),
child: Icon(icon, size: 16, color: iconColor),
),
const SizedBox(width: 8),
Text(
text,
style: TextStyle(
color: cs.onSurface,
fontSize: 14,
fontWeight: FontWeight.bold,
),
textDirection: TextDirection.ltr,
),
],
);
}
}