Browse Source

perf: 图片动态化

zengkunsen 4 months ago
parent
commit
ceddaa80d3

+ 1 - 4
app/(auth)/(tabs)/(home)/notificationPage.tsx

@@ -17,8 +17,6 @@ import { chargeStationService } from '../../../../service/chargeStationService';
 import NotificationTabView from '../../../../component/global/notificationTabViewComponent';
 const NotificationPageComponent = () => {
     const screenHeight = Dimensions.get('window').height;
-    const [loading, setLoading] = useState(false);
-    const [loading1, setLoading1] = useState(false);
     const [reservationAfter2025, setReservationAfter2025] = useState([]);
     const [passingThisPromotionToBell, setPassingThisPromotionToBell] = useState([]);
     const fetchData = async () => {
@@ -27,7 +25,6 @@ const NotificationPageComponent = () => {
                 chargeStationService.fetchReservationHistories(),
                 chargeStationService.getAdvertise()
             ]);
-            console.log('results', results);
             // Handle reservation data
             if (results[0].status === 'fulfilled') {
                 const year2025 = new Date('2025-02-01T00:00:00.000Z');
@@ -58,7 +55,7 @@ const NotificationPageComponent = () => {
       fetchData()
     }, [])
     return (
-        <SafeAreaView className="flex-1 bg-white" edges={['top']}>
+        <SafeAreaView className="flex-1 bg-white" edges={['top', 'left', 'right']}>
             <View style={{ minHeight: screenHeight, flex: 1 }} className="mx-[5%]">
                 <View style={{ marginTop: 25 }}>
                     <Pressable

+ 1 - 351
component/bookingMenuPage/makingBookingPageComponent.tsx

@@ -219,121 +219,6 @@ const MakingBookingPageComponent = () => {
         getCurrentLocation();
     }, []);
 
-    //getDefaultCar
-    // useEffect(() => {
-    //     const fetchDefaultCar = async () => {
-    //         setIsDefaultCarLoading(true);
-    //         try {
-    //             const response = await chargeStationService.getUserDefaultCars();
-    //             if (response && response.data) {
-    //                 setDefaultCar(response.data.id);
-    //                 setSelectedCarID(response.data.id);
-    //                 setCarCapacitance(response.data.car_type.capacitance);
-    //                 setSelectedCar(response.data.id);
-    //                 console.log('*******', response.data.car_type.capacitance);
-    //             }
-    //         } catch (error) {
-    //             console.log('Error fetching default car:', error);
-    //         } finally {
-    //             setIsDefaultCarLoading(false);
-    //         }
-    //     };
-    //     fetchDefaultCar();
-    // }, []);
-    // const formatDistance = (distanceInMeters: number): string => {
-    //     if (distanceInMeters < 1000) {
-    //         return `${Math.round(distanceInMeters)}米`;
-    //     } else {
-    //         const distanceInKm = distanceInMeters / 1000;
-    //         return `${distanceInKm.toFixed(1)}公里`;
-    //     }
-    // };
-    // const getUpcomingReservations = (reservations: any, daysAhead = 3) => {
-    //     const today = new Date();
-    //     const threeDaysLater = new Date(today);
-    //     threeDaysLater.setDate(today.getDate() + daysAhead);
-
-    //     return reservations
-    //         .filter((reservation) => {
-    //             const reservationDate = new Date(reservation.book_time);
-    //             return reservationDate >= today && reservationDate <= threeDaysLater;
-    //         })
-    //         .sort((a, b) => new Date(a.reservationDate) - new Date(b.reservationDate));
-    // };
-
-    //USE BELOW to find  upcoming reservations, then I filter availableDate and time based on the upcoming ones so user cannot book the same time twice.
-    // const formatReservations = (reservations) => {
-    //     const formattedReservations = {};
-
-    //     reservations.forEach((reservation) => {
-    //         const bookTime = new Date(reservation.book_time);
-    //         const date = formatDate(bookTime);
-    //         const time = formatTime(bookTime);
-
-    //         if (!formattedReservations[date]) {
-    //             formattedReservations[date] = [];
-    //         }
-    //         formattedReservations[date].push(time);
-    //     });
-
-    //     return Object.entries(formattedReservations).map(([date, times]) => ({
-    //         date,
-    //         times
-    //     }));
-    // };
-
-    // const formatDate = (date) => {
-    //     const month = String(date.getMonth() + 1).padStart(2, '0');
-    //     const day = String(date.getDate()).padStart(2, '0');
-    //     return `${month}/${day}`;
-    // };
-
-    // const formatTime = (date) => {
-    //     return date.toTimeString().slice(0, 5);
-    // };
-
-    // useEffect(() => {
-    //     const fetchReservationHistories = async () => {
-    //         try {
-    //             const response = await chargeStationService.fetchReservationHistories();
-    //             if (response) {
-    //                 // console.log('response', response);
-    //                 // console.log('Reservation histories:', response);
-    //                 const upcomingReservations = getUpcomingReservations(response);
-    //                 // console.log('upcomingReservations', upcomingReservations);
-    //                 const formattedReservations = formatReservations(upcomingReservations);
-    //                 // console.log('formattedReservations', formattedReservations);
-    //                 setUpcomingReservation(formattedReservations);
-    //             }
-    //             2;
-    //         } catch (error) {
-    //             console.log(error);
-    //         }
-    //     };
-    //     fetchReservationHistories();
-    // }, []);
-
-    //USE ABOVE to find upcoming reservations, then I filter availableDate and time based on the upcoming ones so user cannot book the same time twice.
-
-    // useEffect(() => {
-    //     const getDistance = async () => {
-    //         if (currentLocation) {
-    //             try {
-    //                 const distance = await calculateDistance(
-    //                     Number(params.chargeStationLat),
-    //                     Number(params.chargeStationLng),
-    //                     currentLocation
-    //                 );
-    //                 setDistance(formatDistance(distance));
-    //             } catch (error) {
-    //                 console.error('Error calculating distance:', error);
-    //             }
-    //         }
-    //     };
-
-    //     getDistance();
-    // }, [params.chargeStationLat, params.chargeStationLng, currentLocation]);
-
     useEffect(() => {
         const fetchPrice = async () => {
             try {
@@ -346,155 +231,7 @@ const MakingBookingPageComponent = () => {
         fetchPrice();
     }, []);
 
-    // function appendImageUrlToCarResult(carData, updatedVehicles) {
-    //     return carData.map((car) => {
-    //         const matchingVehicle = updatedVehicles.find((vehicle) => vehicle.car_type.name === car.car_name);
-    //         if (matchingVehicle) {
-    //             return {
-    //                 ...car,
-    //                 type_image_url: matchingVehicle.car_type.type_image_url
-    //             };
-    //         }
-    //         return car;
-    //     });
-    // }
-
-    // useEffect(() => {
-    //     setCarLoadingState(true);
-
-    //     const fetchUserInfoAndCarData = async () => {
-    //         try {
-    //             const fetchedUserInfo = await authenticationService.getUserInfo();
-    //             const userData = fetchedUserInfo?.data;
-    //             // console.log('userData', userData);
-    //             if (userData) {
-    //                 setUserID(userData.id);
-
-    //                 const carData = userData.cars.map((car: any) => ({
-    //                     car_name: car.name,
-    //                     car_capacitance: car.capacitance,
-    //                     car_id: car.id,
-    //                     isDefault: car.id === userData.defaultCar?.id
-    //                 }));
-    //                 // console.log('carDarta', carData);
-    //                 setCar(carData);
-
-    //                 const carResult = await chargeStationService.getUserCars();
-    //                 let updatedVehicles = [...carResult.data];
-    //                 // console.log('updatedVehiaacles', updatedVehicles);
-
-    //                 const updatedCarResult = appendImageUrlToCarResult(carData, updatedVehicles);
-    //                 setCar(updatedCarResult);
-
-    //                 let updatedCarResultWithProcessedUrl = [...updatedCarResult];
-
-    //                 for (let i = 0; i < updatedCarResultWithProcessedUrl.length; i++) {
-    //                     const car = updatedCarResultWithProcessedUrl[i];
-    //                     const processedUrl = await chargeStationService.getProcessedImageUrl(car.type_image_url);
-    //                     updatedCarResultWithProcessedUrl[i] = {
-    //                         ...car,
-    //                         processedImageUrl: processedUrl
-    //                     };
-    //                 }
-    //                 // console.log(updatedCarResultWithProcessedUrl);
-    //                 setCar(updatedCarResultWithProcessedUrl);
-    //             }
-    //         } catch (error) {
-    //             console.error('Error fetching user info:', error);
-    //         } finally {
-    //             setCarLoadingState(false);
-    //         }
-    //     };
-    //     fetchUserInfoAndCarData();
-    // }, []);
-
-    // useEffect(() => {
-    //     const fetchingAvailableTimeSlots = async () => {
-    //         setIsLoading(true);
-    //         try {
-    //             const fetchedTimeSlots = await chargeStationService.fetchAvailableTimeSlots(
-    //                 chargeStationID,
-    //                 selectedDate
-    //             );
-    //             const now = new Date();
-    //             const today = `${String(now.getMonth() + 1).padStart(2, '0')}/${String(now.getDate()).padStart(
-    //                 2,
-    //                 '0'
-    //             )}`;
-
-    //             let filteredTimeSlots = fetchedTimeSlots;
-
-    //             //filter out today's time slots that have already passed
-    //             if (selectedDate === today) {
-    //                 const currentHours = now.getHours();
-    //                 const currentMinutes = now.getMinutes();
-
-    //                 filteredTimeSlots = fetchedTimeSlots.filter((time) => {
-    //                     const [hours, minutes] = time.split(':').map(Number);
-    //                     if (hours > currentHours) return true;
-    //                     if (hours === currentHours && minutes > currentMinutes) return true;
-    //                     return false;
-    //                 });
-    //             }
-    //             //filter out time slots that are already fully booked
-    //             const reservedSlotsForDate = upcomingReservations.find((res) => res.date === selectedDate);
-
-    //             if (reservedSlotsForDate) {
-    //                 filteredTimeSlots = filteredTimeSlots.filter((time) => !reservedSlotsForDate.times.includes(time));
-    //             }
-    //             setAvailableTimeSlots(filteredTimeSlots);
-    //         } catch (error) {
-    //             console.error('Error fetching time slots:', error);
-    //         } finally {
-    //             setIsLoading(false);
-    //         }
-    //     };
-
-    //     if (selectedDate) {
-    //         fetchingAvailableTimeSlots();
-    //     }
-    // }, [selectedDate]);
-
-    // useEffect(() => {
-    //     const fetchConnectorOptions = async () => {
-    //         try {
-    //             const fetchedData = await chargeStationService.fetchSpecificChargeStation(chargeStationID);
-    //             console.log('fetchedDate', fetchedData);
-    //             const dateObject = fetchedData.find((item) => item.date === selectedDate);
-    //             console.log('dateObject', dateObject);
-    //             if (!dateObject) {
-    //                 setAvailableConnectorDropdownOptions([]);
-    //                 return;
-    //             }
-
-    //             const rangeObject = dateObject.range.find((range) => range.start === selectedTime);
-    //             console.log('rangeObject', rangeObject);
-    //             if (!rangeObject) {
-    //                 setAvailableConnectorDropdownOptions([]);
-    //                 return;
-    //             }
-
-    //             const connectorIDs = rangeObject.connectors
-    //                 .filter((connector) => connector.Status === '待机')
-    //                 .map((connector) => connector.ConnectorID);
-
-    //             console.log('connectorIDs', connectorIDs);
-
-    //             setAvailableConnectorDropdownOptions(connectorIDs);
-    //         } catch (error) {
-    //             console.error('Error fetching charge station data:', error);
-    //             setAvailableConnectorDropdownOptions([]);
-    //         }
-    //     };
-
-    //     fetchConnectorOptions();
-    // }, [chargeStationID, selectedDate, selectedTime]);
-
-    // old
-    // const formattedConnectorDropdownOptions = availableConnectorDropdownOptions.map((id, index) => ({
-    //     label: (index + 1).toString(),
-    //     value: id
-    // }));
+    
     const connectorIDToLabelMap = {
         '101708240502475001': '1',
         '101708240502476001': '2',
@@ -517,30 +254,9 @@ const MakingBookingPageComponent = () => {
         return `${month}/${day}`;
     };
 
-    // useEffect(() => {
-    //     const fetchingAvailableDates = async () => {
-    //         setIsDateLoading(true);
-    //         try {
-    //             const fetchedDates = await chargeStationService.fetchAvailableDates(chargeStationID);
-    //             console.log('fetchedDates', fetchedDates);
-    //             setAvailableDate(fetchedDates);
-
-    //             console.log(fetchedDates.slice(0, 3));
-    //         } catch (error) {
-    //             console.error('Error fetching available dates:', error);
-    //         } finally {
-    //             setIsDateLoading(false);
-    //         }
-    //     };
-
-    //     fetchingAvailableDates();
-    // }, [chargeStationID]);
-
     const handleNavigationPress = () => {
         const latitude = chargeStationLat;
         const longitude = chargeStationLng;
-        // console.log('latitude', latitude);
-        // console.log('longitude', longitude);
         const label = encodeURIComponent(chargeStationName);
 
         // Google Maps App URL
@@ -694,72 +410,6 @@ const MakingBookingPageComponent = () => {
                 </View>
 
                 <View>
-                    {/* {selectedCar !== '' ? (
-                        <>
-                            <Pressable
-                                onPress={() => {
-                                    setSelectedCar('');
-                                    setSelectedWatt('');
-                                    setOpenDrawer(0);
-                                    setSelectedDrawer(0);
-                                    setSelectedDuration('');
-                                    setChargingBasedOnWatt(false);
-                                    setStopChargingUponBatteryFull(false);
-                                    setSelectedDate('');
-                                    setSelectedTime('');
-                                }}
-                            >
-                                <View className="mx-[5%]">
-                                    <View className="flex-row items-center pt-4">
-                                        <Text className="text-lg pr-2 text-[#34667c]">選擇充電車輛</Text>
-                                        <CheckMarkLogoSvg />
-                                    </View>
-                                    <Text className="text-lg pb-4">{selectedCar}</Text>
-                                </View>
-                            </Pressable>
-                        </>
-                    ) : (
-                        <AccordionItem
-                            title="選擇充電車輛"
-                            isOpen={openDrawer === 0}
-                            onToggle={() => toggleDrawer(0)}
-                            isSelected={selectedDrawer === 0}
-                        >
-                            {carLoadingState ? (
-                                <View>
-                                    <ActivityIndicator color="#34657b" />
-                                </View>
-                            ) : (
-                                <ScrollView
-                                    horizontal={true}
-                                    contentContainerStyle={{
-                                        alignItems: 'center',
-                                        flexDirection: 'row',
-                                        marginVertical: 8
-                                    }}
-                                    className="space-x-2 "
-                                >
-                                    {car
-                                        .sort((a, b) => (b.isDefault ? 1 : 0) - (a.isDefault ? 1 : 0))
-                                        .map((car, index) => (
-                                            <ChooseCarForChargingRow
-                                                onPress={() => {
-                                                    setSelectedCar(car.car_name);
-                                                    setSelectedCarID(car.car_id);
-                                                    setCarCapacitance(car.car_capacitance);
-                                                    setSelectedDrawer(1);
-                                                    setOpenDrawer(1);
-                                                }}
-                                                image={car.processedImageUrl}
-                                                key={`${car.car_name}+${index}`}
-                                                VehicleName={car.car_name}
-                                                isDefault={car.isDefault}
-                                            />
-                                        ))}
-                                </ScrollView>
-                            )}
-                        </AccordionItem>
-                    )} */}
 
                     {stopChargingUponBatteryFull === true || selectedWatt !== '' ? (
                         <Pressable

+ 0 - 26
component/chargingPage/noChargingOngoingPageComponent.tsx

@@ -48,17 +48,6 @@ const NoChargingOngoingPageComponent = () => {
     );
 
     const StationRow = ({ item }: { item: any }) => {
-        //use different image for different station based on station id, if not found, use default image.
-        const stationID = item.stationID;
-
-        const stationImages = {
-            //沙頭角
-            '2501161430118231000': require('../../assets/dummyStationPicture5.jpeg'),
-            //黃竹坑
-            '2411291610329331000': require('../../assets/dummyStationPicture4.jpeg'),
-            //觀塘
-            '2405311022116801000': require('../../assets/dummyStationPicture.png')
-        };
         // const imageSource = stationImages[stationID] || require('../../assets/dummyStationPicture.png');
         const imgObj = item.image? {uri: item.image} : require('../../assets/dummyStationPicture.png')
         return (
@@ -158,18 +147,3 @@ const styles = StyleSheet.create({
 });
 
 export default NoChargingOngoingPageComponent;
-// const styles = StyleSheet.create({
-//     container: {
-//         flexDirection: 'row',
-//         width: '100%',
-//         flex: 1
-//     },
-
-//     textContainer: {
-//         flex: 1,
-//         flexDirection: 'column',
-//         gap: 8,
-//         marginTop: 20,
-//         marginRight: 8 // Add right margin to prevent text from touching the edge
-//     }
-// });

+ 3 - 2
component/global/bookingTabViewComponent.tsx

@@ -3,6 +3,7 @@ import { ActivityIndicator, View, RefreshControl } from 'react-native';
 import { useQuery, QueryClient, QueryClientProvider } from '@tanstack/react-query';
 import TabViewComponent, { TabItem } from './tabView';
 import { chargeStationService } from '../../service/chargeStationService';
+import { EXPO_PUBLIC_API_URL, EXPO_PUBLIC_API_IMG_URL } from '@env';
 
 const queryClient = new QueryClient();
 
@@ -86,9 +87,9 @@ const processReservations = (reservations, allStations, isFuture): TabItem[] =>
             // 确保时间字段存在
             const bookTime = reservation.book_time ? new Date(reservation.book_time) : new Date();
             const actualEndTime = reservation.actual_end_time ? new Date(reservation.actual_end_time) : new Date();
-            
+            const img = stationInfo.image? {uri: `${EXPO_PUBLIC_API_IMG_URL}${stationInfo.image}`} : require('../../assets/dummyStationPicture.png')
             return {
-                imgURL: require('../../assets/dummyStationPicture.png'),
+                imgURL: img,
                 date: `${bookTime.getMonth() + 1}月${bookTime.getDate()}`,
                 time: bookTime.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false }),
                 actual_end_time: actualEndTime.toLocaleTimeString('zh-CN', {

+ 42 - 44
component/global/notificationTabViewComponent.tsx

@@ -2,7 +2,7 @@
 
 import * as React from 'react';
 import { View, Text, useWindowDimensions, StyleSheet, ScrollView, ActivityIndicator, Pressable } from 'react-native';
-import { TabView, TabBar } from 'react-native-tab-view';
+import { TabView, SceneMap, TabBar } from 'react-native-tab-view';
 
 import { formatToChineseDateTime } from '../../util/lib';
 import { useCallback, useMemo, useEffect, useState } from 'react';
@@ -72,7 +72,7 @@ const ReservationRow = ({
     viewedNotifications: any;
 }) => {
     const isViewed = viewedNotifications.some(
-        (notification: any) => notification.id === reservationObj.id && notification.type === 'reservation'
+        (notification: any) => notification?.id === reservationObj?.id && notification.type === 'reservation'
     );
     const handlePress = async () => {
         await notificationStorage.markAsViewed(reservationObj.id, 'reservation');
@@ -130,49 +130,47 @@ const FirstRoute = ({ loading, reservationAfter2025 }: { loading: boolean; reser
         }, [])
     );
     return (
-        <View className="flex-1">
-            <ScrollView
-                style={{ flex: 1, backgroundColor: 'white', marginTop: 14 }}
-                contentContainerStyle={{ paddingBottom: 120 }}
-            >
-                <View className="flex-1 flex-col">
-                    {loading ? (
-                        <View className="items-center justify-center">
-                            <ActivityIndicator />
-                        </View>
-                    ) : (
+        <ScrollView
+            style={{ flex: 1, backgroundColor: 'white', marginTop: 14 }}
+            contentContainerStyle={{ paddingBottom: 120 }}
+        >
+            <View className="flex-1 flex-col">
+                {loading ? (
+                    <View className="items-center justify-center">
+                        <ActivityIndicator />
+                    </View>
+                ) : (
+                    <View>
                         <View>
-                            <View>
-                                {reservationAfter2025.length === 0 ? (
-                                    <Text className="pl-4">暫時沒有充電資訊。</Text>
-                                ) : (
-                                    reservationAfter2025
-                                        .sort(
-                                            (a: any, b: any) =>
-                                                new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
-                                        )
-                                        .filter(
-                                            (reservationObj: any) =>
-                                                reservationObj.status.id === '7' ||
-                                                reservationObj.status.id === '8' ||
-                                                reservationObj.status.id === '13'
-                                        )
-                                        .slice(0, 30)
-                                        .map((reservationObj: any, index: any) => (
-                                            <ReservationRow
-                                                reservationObj={reservationObj}
-                                                index={index}
-                                                key={reservationObj.id}
-                                                viewedNotifications={viewedNotifications}
-                                            />
-                                        ))
-                                )}
-                            </View>
+                            {reservationAfter2025.length === 0 ? (
+                                <Text className="pl-4">暫時沒有充電資訊。</Text>
+                            ) : (
+                                reservationAfter2025
+                                    .sort(
+                                        (a: any, b: any) =>
+                                            new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
+                                    )
+                                    .filter(
+                                        (reservationObj: any) =>
+                                            reservationObj.status.id === '7' ||
+                                            reservationObj.status.id === '8' ||
+                                            reservationObj.status.id === '13'
+                                    )
+                                    .slice(0, 30)
+                                    .map((reservationObj: any, index: any) => (
+                                        <ReservationRow
+                                            reservationObj={reservationObj}
+                                            index={index}
+                                            key={reservationObj.id}
+                                            viewedNotifications={viewedNotifications}
+                                        />
+                                    ))
+                            )}
                         </View>
-                    )}
-                </View>
-            </ScrollView>
-        </View>
+                    </View>
+                )}
+            </View>
+        </ScrollView>
     );
 };
 
@@ -274,10 +272,10 @@ const NotificationTabView: React.FC<TabViewComponentProps> = ({
     return (
         <TabView
             navigationState={{ index, routes }}
+            renderTabBar={renderTabBar}
             renderScene={renderScene}
             onIndexChange={setIndex}
             initialLayout={{ width: layout.width }}
-            renderTabBar={renderTabBar}
             commonOptions={{
                 label: ({ route, focused }) => (
                     <Text