209 lines
9.8 KiB
TypeScript
209 lines
9.8 KiB
TypeScript
import React, { useState, useEffect, useRef } from 'react';
|
|
import { X, MapPin, Loader2, Clock, Map as MapIcon } from 'lucide-react';
|
|
import { useTourStore } from './useTourStore.js';
|
|
import { MapContainer, TileLayer, Marker, useMapEvents, useMap } from 'react-leaflet';
|
|
import L from 'leaflet';
|
|
|
|
// Component Helper xử lý việc chọn vị trí trên mini map bằng chuột phải
|
|
const MapPicker = ({ onPick, center }: { onPick: (latlng: L.LatLng) => void, center: [number, number] }) => {
|
|
const [menuPos, setMenuPos] = useState<{ x: number, y: number, latlng: L.LatLng } | null>(null);
|
|
const menuRef = useRef<HTMLDivElement>(null);
|
|
const map = useMap();
|
|
|
|
useMapEvents({
|
|
contextmenu: (e) => {
|
|
L.DomEvent.preventDefault(e.originalEvent);
|
|
L.DomEvent.stopPropagation(e.originalEvent);
|
|
setMenuPos({ x: e.containerPoint.x, y: e.containerPoint.y, latlng: e.latlng });
|
|
},
|
|
click: () => setMenuPos(null),
|
|
dragstart: () => setMenuPos(null),
|
|
});
|
|
|
|
useEffect(() => {
|
|
if (menuPos && menuRef.current) {
|
|
L.DomEvent.disableClickPropagation(menuRef.current);
|
|
}
|
|
}, [menuPos]);
|
|
|
|
useEffect(() => {
|
|
map.setView(center, map.getZoom());
|
|
}, [center]);
|
|
|
|
return (
|
|
<>
|
|
{menuPos && (
|
|
<div
|
|
ref={menuRef}
|
|
className="absolute z-[3000] bg-white rounded-xl shadow-xl border border-gray-100 py-1 w-44 animate-in zoom-in-95 duration-200"
|
|
style={{ top: menuPos.y, left: menuPos.x }}
|
|
>
|
|
<button
|
|
type="button"
|
|
onClick={() => { onPick(menuPos.latlng); setMenuPos(null); }}
|
|
className="w-full text-left px-4 py-2 hover:bg-blue-50 text-xs font-bold text-blue-600 flex items-center gap-2"
|
|
>
|
|
<MapPin className="w-3 h-3" /> Thêm vào chặng hiện tại
|
|
</button>
|
|
</div>
|
|
)}
|
|
</>
|
|
);
|
|
};
|
|
|
|
export const AddLocationModal = ({ isOpen, onClose, tourId, initialLegId }: { isOpen: boolean, onClose: () => void, tourId: string, initialLegId?: string }) => {
|
|
const [formData, setFormData] = useState({
|
|
name: '',
|
|
address: '',
|
|
latitude: 10.7769,
|
|
longitude: 106.7009,
|
|
type: 'VISIT',
|
|
legId: '',
|
|
plannedStart: '',
|
|
plannedEnd: ''
|
|
});
|
|
const [isLoading, setIsLoading] = useState(false);
|
|
|
|
// Gom các selector lại để giảm số lượng Hook gọi nội bộ và tăng hiệu năng
|
|
const { legs, addLocation, mapCenter } = useTourStore();
|
|
|
|
// 1. Luôn khai báo Hook ở cấp cao nhất, không đặt code logic/return giữa các Hook
|
|
useEffect(() => {
|
|
// Chỉ cập nhật nếu giá trị thực sự thay đổi để tránh vòng lặp re-render
|
|
if (initialLegId && formData.legId !== initialLegId) {
|
|
setFormData(prev => ({ ...prev, legId: initialLegId }));
|
|
}
|
|
}, [initialLegId, isOpen]);
|
|
|
|
useEffect(() => {
|
|
if (isOpen && !formData.name) {
|
|
setFormData(prev => ({ ...prev, latitude: mapCenter[0], longitude: mapCenter[1] }));
|
|
}
|
|
}, [isOpen, mapCenter]);
|
|
|
|
// 2. Thực hiện các tính toán và hàm xử lý
|
|
const currentLegId = formData.legId || (legs.length > 0 ? legs[0].id : '');
|
|
const targetLeg = legs.find(l => l.id === currentLegId);
|
|
const titleText = initialLegId ? `Thêm địa điểm cho ${targetLeg?.note || `Chặng ${targetLeg?.sequence}`}` : 'Thêm địa điểm mới';
|
|
const buttonText = initialLegId ? 'Xác nhận thêm vào chặng' : 'Thêm địa điểm';
|
|
|
|
const handlePickLocation = async (latlng: L.LatLng) => {
|
|
setFormData(prev => ({ ...prev, latitude: latlng.lat, longitude: latlng.lng }));
|
|
|
|
// Tự động lấy tên địa điểm từ tọa độ vừa chọn
|
|
try {
|
|
const res = await fetch(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${latlng.lat}&lon=${latlng.lng}`);
|
|
const data = await res.json();
|
|
const addr = data.address;
|
|
const detectedName = addr.amenity || addr.building || addr.historic || addr.tourist ||
|
|
addr.shop || addr.office || addr.leisure || addr.attraction ||
|
|
addr.road || addr.neighbourhood || addr.suburb ||
|
|
data.display_name?.split(',')[0] || "";
|
|
|
|
setFormData(prev => ({ ...prev, name: detectedName || prev.name, address: data.display_name || prev.address }));
|
|
} catch (e) {}
|
|
};
|
|
|
|
// 3. Early return phải nằm SAU tất cả các khai báo Hook
|
|
if (!isOpen) return null;
|
|
|
|
const handleSubmit = async (e: React.FormEvent) => {
|
|
e.preventDefault();
|
|
setIsLoading(true);
|
|
try {
|
|
await addLocation(tourId, {
|
|
...formData,
|
|
legId: currentLegId,
|
|
latitude: parseFloat(formData.latitude as any),
|
|
longitude: parseFloat(formData.longitude as any),
|
|
});
|
|
onClose();
|
|
} catch (error) {
|
|
alert('Lỗi khi thêm địa điểm');
|
|
} finally {
|
|
setIsLoading(false);
|
|
}
|
|
};
|
|
|
|
return (
|
|
<div className="fixed inset-0 z-[2000] flex items-center justify-center p-4">
|
|
<div className="absolute inset-0 bg-gray-900/60 backdrop-blur-sm" onClick={onClose} />
|
|
<div className="relative w-full max-w-lg bg-white rounded-3xl shadow-2xl overflow-hidden p-8 max-h-[90vh] overflow-y-auto">
|
|
<div className="flex justify-between items-center mb-6">
|
|
<h2 className="text-2xl font-bold text-gray-900 flex items-center gap-2">
|
|
<MapIcon className="w-6 h-6 text-blue-600" /> {titleText}
|
|
</h2>
|
|
<button onClick={onClose} className="p-2 hover:bg-gray-100 rounded-full transition-colors">
|
|
<X className="w-6 h-6 text-gray-400" />
|
|
</button>
|
|
</div>
|
|
|
|
{/* Mini Map Picker */}
|
|
<div className="h-48 w-full rounded-2xl overflow-hidden mb-6 border border-gray-100 relative shadow-inner group">
|
|
<MapContainer center={[formData.latitude, formData.longitude]} zoom={13} className="h-full w-full">
|
|
<TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
|
|
<Marker position={[formData.latitude, formData.longitude]} />
|
|
<MapPicker center={[formData.latitude, formData.longitude]} onPick={handlePickLocation} />
|
|
</MapContainer>
|
|
<div className="absolute bottom-2 left-2 z-[1000] bg-white/90 backdrop-blur-sm px-2 py-1 rounded-lg text-[10px] font-black text-gray-500 shadow-sm border border-gray-100">
|
|
CHUỘT PHẢI ĐỂ CHỌN VỊ TRÍ
|
|
</div>
|
|
</div>
|
|
|
|
<form onSubmit={handleSubmit} className="space-y-4">
|
|
<div>
|
|
<label className="block text-sm font-bold text-gray-700 mb-1">Tên địa điểm</label>
|
|
<input required className="w-full px-4 py-3 bg-gray-50 border border-gray-100 rounded-xl outline-none"
|
|
value={formData.name} onChange={e => setFormData({...formData, name: e.target.value})} />
|
|
</div>
|
|
<div>
|
|
<label className="block text-sm font-bold text-gray-700 mb-1">Địa chỉ</label>
|
|
<input className="w-full px-4 py-3 bg-gray-50 border border-gray-100 rounded-xl outline-none"
|
|
value={formData.address} onChange={e => setFormData({...formData, address: e.target.value})} />
|
|
</div>
|
|
<div>
|
|
<label className="block text-sm font-bold text-gray-700 mb-1">Gán vào chặng</label>
|
|
<select required className="w-full px-4 py-3 bg-gray-50 border border-gray-100 rounded-xl outline-none"
|
|
value={currentLegId} onChange={e => setFormData({...formData, legId: e.target.value})}>
|
|
{legs.map(leg => (
|
|
<option key={leg.id} value={leg.id}>Chặng {leg.sequence}: {leg.note || 'Không có tên'}</option>
|
|
))}
|
|
</select>
|
|
</div>
|
|
<div className="grid grid-cols-2 gap-4">
|
|
<div>
|
|
<label className="block text-sm font-bold text-gray-700 mb-1">Vĩ độ</label>
|
|
<input type="number" step="any" required className="w-full px-4 py-3 bg-gray-50 border border-gray-100 rounded-xl outline-none"
|
|
value={formData.latitude} onChange={e => setFormData({...formData, latitude: e.target.value as any})} />
|
|
</div>
|
|
<div>
|
|
<label className="block text-sm font-bold text-gray-700 mb-1">Kinh độ</label>
|
|
<input type="number" step="any" required className="w-full px-4 py-3 bg-gray-50 border border-gray-100 rounded-xl outline-none"
|
|
value={formData.longitude} onChange={e => setFormData({...formData, longitude: e.target.value as any})} />
|
|
</div>
|
|
</div>
|
|
<div>
|
|
<label className="block text-sm font-bold text-gray-700 mb-1">Loại</label>
|
|
<select className="w-full px-4 py-3 bg-gray-50 border border-gray-100 rounded-xl outline-none"
|
|
value={formData.type} onChange={e => setFormData({...formData, type: e.target.value as any})}>
|
|
<option value="VISIT">Tham quan</option>
|
|
<option value="EAT">Ăn uống</option>
|
|
<option value="REST">Nghỉ ngơi</option>
|
|
<option value="MOVE">Di chuyển</option>
|
|
</select>
|
|
</div>
|
|
<div className="grid grid-cols-2 gap-4">
|
|
<div>
|
|
<label className="block text-sm font-bold text-gray-700 mb-1">Bắt đầu</label>
|
|
<input type="datetime-local" className="w-full px-4 py-3 bg-gray-50 border border-gray-100 rounded-xl outline-none"
|
|
value={formData.plannedStart} onChange={e => setFormData({...formData, plannedStart: e.target.value})} />
|
|
</div>
|
|
</div>
|
|
<button disabled={isLoading} className="w-full py-4 bg-blue-600 hover:bg-blue-700 text-white font-bold rounded-2xl flex items-center justify-center gap-2 mt-4">
|
|
{isLoading ? <Loader2 className="w-5 h-5 animate-spin" /> : buttonText}
|
|
</button>
|
|
</form>
|
|
</div>
|
|
</div>
|
|
);
|
|
}; |