const PromotionDisplay = (props) => { const { divPromoId, promotion, item_code, config } = props; const lang = commonFunc.getCookies('user_lang') || 'vi'; // Khởi tạo state với giá trị null để tránh nhảy số khi mới render const [remainingTime, setRemainingTime] = useState(null); const [saleActive, setSaleActive] = useState(true); const [durationFlashSale, setDurationFlashSale] = useState(0); const [itemsLeft, setItemsLeft] = useState(1); const [isFlashSale, setIsFlashSale] = useState(false); const [loading, setLoading] = useState(true); // Hàm cập nhật thời gian còn lại chính xác const calculateTimeLeft = useCallback(() => { if (!promotion?.end_date) return 0; const now = new Date().getTime(); const endTime = new Date(promotion.end_date).getTime(); const difference = Math.floor((endTime - now) / 1000); return difference > 0 ? difference : 0; }, [promotion?.end_date]); useEffect(() => { if (!divPromoId || !promotion) return; // 1. Khởi tạo thông số ban đầu const initialTime = calculateTimeLeft(); setRemainingTime(initialTime); if (initialTime <= 0) { setSaleActive(false); setLoading(false); return; } // Tính toán thời gian tổng của promo để làm progress bar const start = new Date().getTime(); const end = new Date(promotion.end_date).getTime(); setDurationFlashSale(Math.floor((end - start) / 1000)); // Kiểm tra loại hình Flash Sale const durationInDays = (end - start) / (1000 * 60 * 60 * 24); if (promotion.is_flash_sale || durationInDays < 4) { setIsFlashSale(true); } // Giả lập lấy tồn kho (anh có thể thay bằng gọi API thực tế tại đây) setItemsLeft(1); // 2. Thiết lập bộ đếm chạy mỗi giây const timer = setInterval(() => { const timeLeft = calculateTimeLeft(); setRemainingTime(timeLeft); if (timeLeft <= 0) { setSaleActive(false); clearInterval(timer); } }, 1000); setLoading(false); return () => clearInterval(timer); }, [promotion, calculateTimeLeft, divPromoId]); const formatTime = (totalSeconds) => { if (!totalSeconds || totalSeconds <= 0) return { days: 0, hours: '00', minutes: '00', secs: '00' }; const days = Math.floor(totalSeconds / (3600 * 24)); const hours = Math.floor((totalSeconds % (3600 * 24)) / 3600); const minutes = Math.floor((totalSeconds % 3600) / 60); const secs = totalSeconds % 60; const pad = (num) => num.toString().padStart(2, '0'); return { days, hours: pad(hours), minutes: pad(minutes), secs: pad(secs) }; }; // Điều kiện dừng render if (!promotion || (remainingTime > 86400 && !isFlashSale)) return null; const { days, hours, minutes, secs } = formatTime(remainingTime); return ( <>
)}