Browse Source

perf: 优化代码

lwxzks 4 months ago
parent
commit
1de613515c

+ 57 - 120
app/(auth)/(tabs)/(home)/scanQrPage.tsx

@@ -12,7 +12,7 @@ import {
     Text,
     Vibration,
     View,
-    Platform,
+    Platform
 } from 'react-native';
 import sha256 from 'crypto-js/sha256';
 import ChooseCarForChargingRow from '../../../../component/global/chooseCarForChargingRow';
@@ -166,15 +166,15 @@ const ScanQrPage = () => {
 
         // Check if the barcode is within the transparent area
         // 在iOS上检查二维码是否在扫描框内,在安卓上跳过位置检查
-          const isIOS = Platform.OS === 'ios';
-          const isWithinScanArea = isIOS ? (
-              origin.x >= transparentAreaX &&
+        const isIOS = Platform.OS === 'ios';
+        const isWithinScanArea = isIOS
+            ? origin.x >= transparentAreaX &&
               origin.y >= transparentAreaY &&
               origin.x + size.width <= transparentAreaX + transparentAreaSize &&
               origin.y + size.height <= transparentAreaY + transparentAreaSize
-          ) : true;
-          
-          if (isWithinScanArea) {
+            : true;
+
+        if (isWithinScanArea) {
             setScanned(true);
             setScannedQrCode(data);
             Vibration.vibrate(100);
@@ -203,68 +203,6 @@ const ScanQrPage = () => {
         }
     };
 
-    const handleDurationSelect = (duration) => {
-        setSelectedDuration(duration);
-        // console.log(duration);
-    };
-    const handleCancel = () => {
-        setSelectedDuration(null);
-        setModalVisible(false);
-        if (router.canGoBack()) {
-            router.back();
-        } else {
-            router.push('/mainPage');
-        }
-    };
-    const handleConfirm = () => {
-        if (selectedDuration !== null) {
-            const now = new Date();
-            let endTime;
-            let fee;
-            let totalPower;
-
-            //i create a planMap2 because i want to move the planMap inside this component but i dont wanna move the outside one because i dont wanna make any potential disruptive changes
-            const planMap2 = {
-                // 3: { duration: 10, kWh: 3, displayDuration: 5, fee: 3 * currentPriceFetchedWhenScanQr },
-                25: { duration: 40, kWh: 20, displayDuration: 25, fee: 20 * currentPriceFetchedWhenScanQr },
-                30: { duration: 45, kWh: 25, displayDuration: 30, fee: 25 * currentPriceFetchedWhenScanQr },
-                40: { duration: 55, kWh: 30, displayDuration: 40, fee: 30 * currentPriceFetchedWhenScanQr },
-                45: { duration: 60, kWh: 40, displayDuration: 45, fee: 40 * currentPriceFetchedWhenScanQr },
-                full: { duration: 120, displayDuration: '充滿停機', fee: 80 * currentPriceFetchedWhenScanQr }
-            };
-
-            if (selectedDuration === 'full') {
-                endTime = new Date(now.getTime() + 2 * 60 * 60 * 1000); // 2 hours for "充滿停機"
-                fee = planMap2.full.fee;
-                totalPower = 80; // Set to 130 for "充滿停機"
-            } else {
-                const durationInMinutes = parseInt(selectedDuration);
-                endTime = new Date(now.getTime() + durationInMinutes * 60 * 1000);
-                // console.log('endTime', endTime);
-                fee = planMap2[selectedDuration].fee;
-                totalPower = planMap2[selectedDuration].kWh;
-            }
-            setTotalFee(fee);
-            console.log('fee in scanQrPage-- this is the total_fee i send to backend', fee);
-            const dataForSubmission = {
-                stationID: '2405311022116801000',
-                connector: scannedResult,
-                user: userID,
-                book_time: now,
-                end_time: endTime,
-                total_power: totalPower,
-                total_fee: fee,
-                // total_fee: 1,
-                promotion_code: '',
-                car: selectedCar,
-                type: 'walking',
-                is_ic_call: false
-            };
-            startCharging(dataForSubmission);
-            setIsConfirmLoading(true);
-        }
-    };
-
     useEffect(() => {
         const subscription = AppState.addEventListener('change', (nextAppState) => {
             if (
@@ -552,57 +490,56 @@ const ScanQrPage = () => {
                     <ActivityIndicator />
                 </View>
             ) : (
-              <View className="flex-1 position-relative">
-                <CameraView
-                    style={styles.camera}
-                    facing="back"
-                    barcodeScannerSettings={{
-                        barcodeTypes: ['qr']
-                    }}
-                    onBarcodeScanned={scanned ? undefined : handleBarCodeScanned}
-                    responsiveOrientationWhenOrientationLocked={true}
-                >
-                </CameraView>
-                <View style={styles.overlay}>
-                  <View style={styles.topOverlay}>
-                      <Pressable
-                          className="absolute top-20 left-10 z-10 p-4"
-                          hitSlop={{ top: 20, bottom: 20, left: 20, right: 20 }} // Added hitSlop
-                          onPress={() => {
-                              if (router.canGoBack()) {
-                                  router.back();
-                              } else {
-                                  router.push('/mainPage');
-                              }
-                          }}
-                      >
-                          <View style={{ transform: [{ scale: 1.5 }] }}>
-                              <CrossLogoWhiteSvg />
-                          </View>
-                      </Pressable>
-                  </View>
-                  <View style={styles.centerRow}>
-                      <View style={styles.leftOverlay}></View>
-                      <View style={styles.transparentArea}></View>
-                      <View style={styles.rightOverlay} />
-                  </View>
-                  <View className="items-center justify-between" style={styles.bottomOverlay}>
-                      <View>
-                          <Text className="text-white text-lg font-bold mt-2 text-center">
-                              請掃瞄充電座上的二維碼
-                          </Text>
-                      </View>
-                      <View className="flex-row space-x-2 items-center ">
-                          <QuestionSvg />
-
-                          <Pressable onPress={() => router.push('assistancePage')}>
-                              <Text className="text-white text-base">需要協助?</Text>
-                          </Pressable>
-                      </View>
-                      <View />
-                  </View>
+                <View className="flex-1 position-relative">
+                    <CameraView
+                        style={styles.camera}
+                        facing="back"
+                        barcodeScannerSettings={{
+                            barcodeTypes: ['qr']
+                        }}
+                        onBarcodeScanned={scanned ? undefined : handleBarCodeScanned}
+                        responsiveOrientationWhenOrientationLocked={true}
+                    ></CameraView>
+                    <View style={styles.overlay}>
+                        <View style={styles.topOverlay}>
+                            <Pressable
+                                className="absolute top-20 left-10 z-10 p-4"
+                                hitSlop={{ top: 20, bottom: 20, left: 20, right: 20 }} // Added hitSlop
+                                onPress={() => {
+                                    if (router.canGoBack()) {
+                                        router.back();
+                                    } else {
+                                        router.push('/mainPage');
+                                    }
+                                }}
+                            >
+                                <View style={{ transform: [{ scale: 1.5 }] }}>
+                                    <CrossLogoWhiteSvg />
+                                </View>
+                            </Pressable>
+                        </View>
+                        <View style={styles.centerRow}>
+                            <View style={styles.leftOverlay}></View>
+                            <View style={styles.transparentArea}></View>
+                            <View style={styles.rightOverlay} />
+                        </View>
+                        <View className="items-center justify-between" style={styles.bottomOverlay}>
+                            <View>
+                                <Text className="text-white text-lg font-bold mt-2 text-center">
+                                    請掃瞄充電座上的二維碼
+                                </Text>
+                            </View>
+                            <View className="flex-row space-x-2 items-center ">
+                                <QuestionSvg />
+
+                                <Pressable onPress={() => router.push('assistancePage')}>
+                                    <Text className="text-white text-base">需要協助?</Text>
+                                </Pressable>
+                            </View>
+                            <View />
+                        </View>
+                    </View>
                 </View>
-              </View>
             )}
         </View>
     );
@@ -619,7 +556,7 @@ const styles = StyleSheet.create({
         flex: 1,
         width: '100%',
         height: '100%',
-        position: 'absolute',
+        position: 'absolute'
     },
     topOverlay: {
         flex: 35,

+ 1 - 1
component/accountPages/myVehiclePageComponent.tsx

@@ -34,7 +34,7 @@ const VehicleRow = ({ car, deviceWidth, deviceHeight, onPress }) => (
                 <View className="flex-1 flex-col pl-2">
                     <Text style={{ fontSize: 22, fontWeight: '600' }}>{car.car_brand.name}</Text>
                     <Text style={{ fontSize: 18 }}>{truncateText(car.car_type.name, 10)}</Text>
-                    <Text style={{ fontSize: 16, color: '#02677D' }}>{car.license_plate}</Text>
+                    <Text style={{ fontSize: 16, color: '#02677D' }}>{car?.license_plate}</Text>
                 </View>
                 <View className="flex-1">
                     <RightArrowIconSvg />

+ 2 - 4
component/homePage/homePage.tsx

@@ -172,7 +172,7 @@ const HomePage: React.FC<HomePageProps> = () => {
             };
 
             fetchData();
-
+            console.log('iiiiiii');
             return () => {
                 isActive = false;
             };
@@ -317,9 +317,7 @@ const HomePage: React.FC<HomePageProps> = () => {
                                 <Text className="text-lg text-left pb-1">你好!</Text>
                                 <View className="relative z-5">
                                     <Pressable
-                                        onPress={() =>
-                                            router.push({pathname: 'notificationPage'})
-                                        }
+                                        onPress={() => router.push({ pathname: 'notificationPage' })}
                                         disabled={isLoadingReservations}
                                         className="z-10 w-10 items-center justify-center"
                                         hitSlop={{ top: 20, bottom: 20, left: 20, right: 20 }}

+ 6 - 1
context/AuthProvider.tsx

@@ -99,6 +99,10 @@ export default function AuthProvider({ children }: { children: ReactNode }) {
     };
 
     const getUserFromAccessToken = async () => {
+        SecureStore.getItemAsync('accessToken').then((aa) => {
+            console.log('sssssss:', aa);
+        });
+
         const token = await SecureStore.getItemAsync('accessToken');
         try {
             const res = await axios.get(`${EXPO_PUBLIC_API_URL}/clients/customer`, {
@@ -106,6 +110,7 @@ export default function AuthProvider({ children }: { children: ReactNode }) {
                     Authorization: `Bearer ${token}`
                 }
             });
+
             const items = {
                 address: res.data.address,
                 birthday: res.data.birthday,
@@ -113,7 +118,7 @@ export default function AuthProvider({ children }: { children: ReactNode }) {
                 email: res.data.email,
                 nickname: res.data.nickname,
                 phone: res.data.phone,
-                car: res.data.defaultCar.license_plate
+                car: res.data?.defaultCar?.license_plate
             };
             return items;
         } catch (error) {

+ 2 - 1
providers/user_store.tsx

@@ -11,7 +11,8 @@ const userStore = create<UserState>((set) => ({
         // firstname: null,
         gender: '',
         nickname: '',
-        phone: null
+        phone: null,
+        car: null
     },
     setUser: (newUserData) =>
         set((state) => ({

+ 1 - 2
service/authService.tsx

@@ -57,7 +57,7 @@ class AuthenticationService {
         }
     }
 
-    async phoneLogin(username: string, password: string, isBinding?: boolean) {
+    async phoneLogin(username: string | null | undefined, password: string, isBinding?: boolean) {
         try {
             const response = await axios.post(
                 // `${this.apiUrl}/public/client/customer/sign-in`,
@@ -424,7 +424,6 @@ class AuthenticationService {
                 }
             });
             if (response.status === 200 || response.status === 201) {
-                // console.log(response);
                 return response;
             } else {
                 console.log('invalid response');

+ 3 - 0
service/chargeStationService.tsx

@@ -480,6 +480,9 @@ class ChargeStationService {
     }
 
     async fetchReservationHistories() {
+        const aa = await SecureStore.getItemAsync('accessToken');
+        console.log('ddddddd:', aa);
+
         try {
             const response = await axios.get(`${this.apiUrl}/clients/reservation/all`, {
                 headers: {