// component/chargingPage/paymentSummaryPageComponent.tsx import { View, Text, ScrollView, StyleSheet, Pressable } from 'react-native'; import { SafeAreaView } from 'react-native-safe-area-context'; import { Alert } from 'react-native'; import NormalButton from '../global/normal_button'; import { router, useLocalSearchParams } from 'expo-router'; import { GrayRightArrowIconSvg, RightArrowIconSvg, TickLogoSvg } from '../global/SVG'; import { useEffect, useRef, useState } from 'react'; import useBookingStore from '../../providers/booking_store'; import useCouponStore from '../../providers/coupon_store'; import { walletService } from '../../service/walletService'; import { parseISO, subHours, format } from 'date-fns'; import { chargeStationService } from '../../service/chargeStationService'; import { useTranslation } from '../../util/hooks/useTranslation'; const PaymentSummaryPageComponent = () => { const { t } = useTranslation(); const selectedCouponName = useCouponStore((state) => state.selectedCouponName); const selectedCouponRedeemCode = useCouponStore((state) => state.selectedCouponRedeemCode); const selectedCouponPrice = useCouponStore((state) => state.selectedCouponPrice); const params = useLocalSearchParams(); const setBookingInfo = useBookingStore((state) => state.setBookingInfo); const initialSetupDone = useRef(false); const [selectedCar, setSelectedCar] = useState(''); const [formatOrderId, setFormatOrderId] = useState(''); useEffect(() => { if (!initialSetupDone.current && Object.keys(params).length > 0) { const bookingInfo = { bookTime: params.bookTime as string, endTime: params.endTime as string, date: params.date as string, carID: params.carID as string, chargingWatt: params.chargingWatt as string, connectorID: params.connectorID as string, price: params.price as string, stationID: params.stationID as string, user: params.userID as string, paymentFee: params.paymentFee as string, carCapacitance: params.carCapacitance as string }; setBookingInfo(bookingInfo); console.log('Booking info stored:', bookingInfo); initialSetupDone.current = true; } }, [params, setBookingInfo]); useEffect(() => { const fetchDefaultCar = async () => { try { const response = await chargeStationService.getUserDefaultCars(); if (response) { console.log('default car', response.data.id); setSelectedCar(response.data.id); } } catch (error) { console.log(error); } }; fetchDefaultCar(); }, []); const { bookTime, date, carID, chargingWatt, connectorID, price, stationID, user, paymentFee, carCapacitance } = useBookingStore(); const calculateFinalFee = (): string => { console.log('selected coupon price:', selectedCouponPrice); if (selectedCouponRedeemCode && selectedCouponPrice) { const difference = parseFloat(paymentFee) - parseFloat(selectedCouponPrice); return Math.max(0, difference).toFixed(2); } else { return paymentFee; } }; const finalFee = calculateFinalFee(); const total_power = chargingWatt === '' ? carCapacitance : parseFloat(chargingWatt.split('~')[0]); const promotion_code = selectedCouponRedeemCode || ''; const total_fee = parseInt(finalFee, 10); function convertToUTC(date: string, time: string): Date { const [year, month, day] = date.split('-').map(Number); if (isNaN(year) || isNaN(month) || isNaN(day)) { console.error('Invalid date format:', date); return new Date(NaN); // Return invalid date } const [hours, minutes] = time.split(':').map(Number); if (isNaN(hours) || isNaN(minutes)) { console.error('Invalid time format:', time); return new Date(NaN); // Return invalid date } // Create a date in local time const localDate = new Date(year, month - 1, day, hours, minutes); // Convert to UTC const utcDate = new Date(localDate.toUTCString()); return utcDate; } const handleSubmitPayment = async () => { console.log('hi'); let type = 'reservation'; let is_ic_call = false; const utcBookTime = convertToUTC(params.date as string, params.bookTime as string); const utcEndTime = convertToUTC(params.date as string, params.endTime as string); if (isNaN(utcBookTime.getTime()) || isNaN(utcEndTime.getTime())) { console.error('Invalid date or time'); // Handle the error appropriately, maybe show an alert to the user return; } try { const response = await walletService.submitPayment( stationID, connectorID, user, utcBookTime, utcEndTime, total_power, total_fee, promotion_code, selectedCar, type, is_ic_call ); if (response.status === 200 || response.status === 201) { router.push({ pathname: '/paymentFinishPage', params: { formatOrderId: response.data.format_order_id } }); } else if (response.status === 400) { console.log('400 error in paymentSummaryPageComponent'); Alert.alert(t('payment_summary.insufficient_balance_title'), t('payment_summary.insufficient_balance_message')); } else { console.log('submit payment failed:', response); } } catch (error) { console.log('submit payment error:', error); } }; return ( {t('payment_summary.title')} router.push('selectCouponPage')}> {t('payment_summary.coupon')} {selectedCouponName === '' ? ( {t('payment_summary.select_coupon')} ) : ( {selectedCouponName} )} {t('payment_summary.fee_summary')} {t('payment_summary.charging_fee')} HK ${finalFee} {chargingWatt === '' ? ( {t('payment_summary.estimated_full_charge')} ) : ( {t('payment_summary.settled_per_kwh')}{chargingWatt?.split('~')[0]} )} {t('payment_summary.total')} HK$ {finalFee} {t('payment_summary.proceed_to_payment')} } onPress={ // () => router.push('/paymentFinishPage') handleSubmitPayment } extendedStyle={{ padding: 24 }} /> ); }; export default PaymentSummaryPageComponent; const styles = StyleSheet.create({ grayColor: { color: '#888888' }, greenColor: { color: '#02677D' } });