Files
travelplanning/ItineraryTimeline.tsx
T

282 lines
14 KiB
TypeScript

import React from 'react';
import { format, differenceInMinutes, parseISO } from 'date-fns';
import { CheckCircle2, Circle, Clock, MapPin, AlertCircle, Zap, Navigation, Edit2, Trash2, Plus } from 'lucide-react';
import { useTourStore } from './useTourStore.js';
const TimeVariance = ({ planned, actual }: { planned: string, actual: string | null }) => {
if (!actual) return null;
const diff = differenceInMinutes(parseISO(actual), parseISO(planned));
const isLate = diff > 0;
return (
<div className={`flex items-center text-xs font-medium mt-1 ${isLate ? 'text-red-500' : 'text-green-600'}`}>
{isLate ? <AlertCircle className="w-3 h-3 mr-1" /> : <CheckCircle2 className="w-3 h-3 mr-1" />}
<span>
{isLate ? `Trễ ${diff} phút` : diff === 0 ? 'Đúng giờ' : `Sớm ${Math.abs(diff)} phút`}
</span>
</div>
);
};
const calculateDistance = (lat1: number, lon1: number, lat2: number, lon2: number) => {
const p = 0.017453292519943295; // Math.PI / 180
const c = Math.cos;
const a = 0.5 - c((lat2 - lat1) * p) / 2 +
c(lat1 * p) * c(lat2 * p) *
(1 - c((lon2 - lon1) * p)) / 2;
return 12742 * Math.asin(Math.sqrt(a)); // 2 * R; R = 6371 km
};
const formatTravelTime = (minutes: number) => {
if (minutes < 60) return `${minutes} phút`;
const hours = Math.floor(minutes / 60);
const mins = minutes % 60;
return mins > 0 ? `${hours} giờ ${mins} phút` : `${hours} giờ`;
};
export const ItineraryTimeline = () => {
const { currentTour, legs, optimizeRouting, userRole, activeLegId, setActiveLegId, addLeg, updateLeg, deleteLeg } = useTourStore();
const toggleComplete = async (locationId: string) => {
// Gọi API PATCH /api/v1/locations/:id để cập nhật trạng thái
console.log("Toggle status for location:", locationId);
};
const handleAddLeg = async () => {
const note = window.prompt("Nhập ghi chú cho chặng mới:", `Chặng ${legs.length + 1}`);
if (note && currentTour) {
await addLeg(currentTour.id, { note });
}
};
const handleEditLeg = async (leg: any) => {
const note = window.prompt("Sửa ghi chú chặng:", leg.note || "");
if (note !== null) {
await updateLeg(leg.id, { note });
}
};
const handleDeleteLeg = async (legId: string) => {
if (window.confirm("Bạn có chắc chắn muốn xóa chặng này?")) {
try {
await deleteLeg(legId);
} catch (err: any) {
alert(err.message);
}
}
};
const activeLeg = legs.find(l => l.id === activeLegId) || legs[0];
return (
<div className="max-w-2xl mx-auto p-0 bg-gray-50 min-h-screen">
{/* Tầng 1: Horizontal Leg Picker (6.3-A) */}
<div className="sticky top-[136px] z-20 bg-gray-50/80 backdrop-blur-sm pb-4 mb-4">
<div className="flex overflow-x-auto gap-2 px-2 no-scrollbar py-2">
{legs.map((leg) => (
<button
key={leg.id}
onClick={() => setActiveLegId(leg.id)}
className={`flex-shrink-0 px-6 py-2.5 rounded-2xl text-xs font-black uppercase tracking-widest transition-all border ${
activeLegId === leg.id
? 'bg-blue-600 text-white border-blue-600 shadow-lg shadow-blue-100 scale-105'
: 'bg-white text-gray-400 border-gray-100 hover:border-gray-200'
}`}
>
Chặng {leg.sequence}
</button>
))}
{['OWNER', 'MANAGER'].includes(userRole || '') && (
<button
onClick={handleAddLeg}
className="flex-shrink-0 p-2.5 rounded-2xl bg-white text-blue-600 border border-dashed border-blue-200 hover:bg-blue-50 transition-all flex items-center justify-center w-12"
>
<Plus className="w-5 h-5" />
</button>
)}
</div>
</div>
<div className="px-2">
{activeLeg && (
<div className="relative animate-in fade-in slide-in-from-right-4 duration-300">
{/* Leg Info Summary */}
{(() => {
const leg = activeLeg;
const totalDwellMinutes = leg.locations.reduce((acc: number, loc: any) => {
if (loc.plannedStart && loc.plannedEnd) {
return acc + differenceInMinutes(parseISO(loc.plannedEnd), parseISO(loc.plannedStart));
}
return acc;
}, 0);
return (
<>
{/* Leg Header */}
<div className="flex items-center mb-4 px-2">
<div className="font-black text-gray-900 text-lg truncate flex-1">
{leg.note || `Chi tiết Chặng ${leg.sequence}`}
</div>
<div className="flex items-center gap-2 ml-4">
{['OWNER', 'MANAGER'].includes(userRole || '') && (
<>
<button
onClick={() => handleEditLeg(leg)}
className="p-2 text-gray-400 hover:text-blue-600 hover:bg-blue-50 rounded-xl transition-all"
>
<Edit2 className="w-4 h-4" />
</button>
<button
onClick={() => handleDeleteLeg(leg.id)}
className="p-2 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-xl transition-all"
>
<Trash2 className="w-4 h-4" />
</button>
</>
)}
{leg.totalDistance !== undefined && (
<div className="hidden sm:flex items-center gap-2">
<div className="text-xs font-bold text-blue-600 bg-blue-50 px-2 py-1 rounded-lg border border-blue-100">
{leg.totalDistance} km
</div>
<div className="text-xs font-bold text-gray-500 bg-gray-50 px-2 py-1 rounded-lg border border-gray-100 flex items-center gap-1">
<Clock className="w-3 h-3" />
~ {formatTravelTime(Math.round((leg.totalDistance / 35) * 60))}
</div>
</div>
)}
{totalDwellMinutes > 0 && (
<div className="hidden md:flex text-xs font-bold text-amber-600 bg-amber-50 px-2 py-1 rounded-lg border border-amber-100 items-center gap-1">
<Clock className="w-3 h-3" />
Dừng: {formatTravelTime(totalDwellMinutes)}
</div>
)}
</div>
{['OWNER', 'MANAGER'].includes(userRole || '') && legs.length > 0 && (
<button
onClick={() => optimizeRouting(leg.id)}
className="ml-auto flex items-center gap-1.5 text-xs font-bold text-indigo-600 hover:text-indigo-700 bg-indigo-50 hover:bg-indigo-100 px-3 py-1.5 rounded-xl transition-all"
>
<Zap className="w-3 h-3" />
Tối ưu
</button>
)}
</div>
{/* Vertical Line for the whole leg */}
<div className="absolute left-6 top-10 bottom-0 w-0.5 bg-gray-200 -z-0" />
<div className="ml-2">
{leg.locations.map((location, idx) => {
const nextLocation = leg.locations[idx + 1];
const distanceToNext = nextLocation
? calculateDistance(location.latitude, location.longitude, nextLocation.latitude, nextLocation.longitude)
: null;
const averageSpeed = 35; // km/h
const travelTimeMinutes = distanceToNext ? Math.round((distanceToNext / averageSpeed) * 60) : null;
const dwellMinutes = (location.plannedStart && location.plannedEnd)
? differenceInMinutes(parseISO(location.plannedEnd), parseISO(location.plannedStart))
: null;
const isStartPoint = legs[0]?.id === leg.id && idx === 0;
const isEndPoint = legs[legs.length - 1]?.id === leg.id && idx === leg.locations.length - 1;
return (
<div key={location.id}>
<div className="relative flex group mb-6">
{/* Timeline Node */}
<div className="z-10 mt-1.5 mr-4">
<button
onClick={() => toggleComplete(location.id)}
className={`transition-colors duration-200 ${location.status === 'COMPLETED' ? 'text-green-500' : 'text-gray-300 hover:text-blue-500'}`}
>
{location.status === 'COMPLETED' ? (
<CheckCircle2 className="w-8 h-8 bg-white rounded-full" />
) : (
<Circle className="w-8 h-8 bg-white rounded-full fill-white" />
)}
</button>
</div>
{/* Card Content */}
<div className={`flex-1 bg-white p-4 rounded-xl border transition-all duration-200 ${
location.status === 'COMPLETED' ? 'border-green-100 bg-green-50/30' : 'border-gray-100 shadow-sm hover:shadow-md'
}`}>
<div className="flex justify-between items-start">
<div>
{isStartPoint && (
<span className="inline-block px-2 py-0.5 bg-green-100 text-green-700 text-[10px] font-bold rounded-md mb-1 uppercase tracking-wider">Điểm bắt đầu</span>
)}
{isEndPoint && (
<span className="inline-block px-2 py-0.5 bg-red-100 text-red-700 text-[10px] font-bold rounded-md mb-1 uppercase tracking-wider">Điểm kết thúc</span>
)}
<h3 className={`font-semibold text-lg ${location.status === 'COMPLETED' ? 'text-gray-500 line-through' : 'text-gray-800'}`}>
{location.name}
</h3>
<div className="flex items-center text-sm text-gray-500 mt-1">
<MapPin className="w-3 h-3 mr-1" />
<span className="truncate max-w-[200px] sm:max-w-md">{location.address}</span>
</div>
{dwellMinutes !== null && (
<div className="flex items-center text-xs text-amber-600 font-medium mt-1">
<Clock className="w-3 h-3 mr-1" />
<span>Thời gian dừng: {formatTravelTime(dwellMinutes)}</span>
</div>
)}
</div>
<div className="text-right flex flex-col items-end">
<div className="flex items-center text-sm font-medium text-blue-600">
<Clock className="w-3 h-3 mr-1" />
{location.plannedStart ? format(parseISO(location.plannedStart), 'HH:mm') : '--:--'}
</div>
{location.status === 'COMPLETED' && location.actualStart && (
<div className="text-[10px] text-gray-400 mt-1 italic">
Thực tế: {format(parseISO(location.actualStart), 'HH:mm')}
</div>
)}
</div>
</div>
{/* Logic tính toán độ lệch thời gian */}
<TimeVariance planned={location.plannedStart || ''} actual={location.actualStart || null} />
</div>
</div>
{distanceToNext !== null && travelTimeMinutes !== null && (
<div className="ml-4 -mt-4 mb-2 flex items-center gap-3">
<div className="w-8 flex justify-center">
<Navigation className="w-3 h-3 text-blue-400 rotate-180" />
</div>
<div className="flex items-center gap-2">
<span className="text-[10px] font-bold text-blue-500 bg-blue-50 px-2 py-0.5 rounded-full border border-blue-100">
{distanceToNext.toFixed(2)} km
</span>
<span className="text-[10px] font-bold text-gray-500 bg-gray-50 px-2 py-0.5 rounded-full border border-gray-100 flex items-center gap-1">
<Clock className="w-2.5 h-2.5" />
~ {formatTravelTime(travelTimeMinutes)}
</span>
</div>
</div>
)}
</div>
);
})}
</div>
{leg.note && (
<p className="ml-14 mt-4 text-sm text-gray-400 italic">
* {leg.note}
</p>
)}
</>
);
})()}
</div>
)}
</div>
</div>
);
};