bookingTabViewComponent.tsx 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. import React, { useState, useCallback, useEffect } from 'react';
  2. import { ActivityIndicator, View, RefreshControl } from 'react-native';
  3. import { useQuery, QueryClient, QueryClientProvider } from '@tanstack/react-query';
  4. import TabViewComponent, { TabItem } from './tabView';
  5. import { chargeStationService } from '../../service/chargeStationService';
  6. import { EXPO_PUBLIC_API_URL } from '@env';
  7. const queryClient = new QueryClient();
  8. interface BookingTabViewComponentProps {
  9. titles: string[];
  10. }
  11. // 更新 findStationByConnectorId 函数以增加安全性
  12. const findStationByConnectorId = (allStations, targetConnectorId) => {
  13. if (!Array.isArray(allStations) || !targetConnectorId) {
  14. return undefined;
  15. }
  16. return allStations.find((station) =>
  17. station?.snapshot?.EquipmentInfos?.some((equipment) =>
  18. equipment?.ConnectorInfos?.some((connector) => connector?.ConnectorID === targetConnectorId)
  19. )
  20. );
  21. };
  22. const fetchReservationsAndStations = async () => {
  23. try {
  24. const [reservationResponse, allStationsResponse] = await Promise.allSettled([
  25. chargeStationService.fetchReservationHistories(),
  26. chargeStationService.fetchAllChargeStations()
  27. ]);
  28. const reservations = reservationResponse.status === 'fulfilled' ? reservationResponse.value : [];
  29. const stations = allStationsResponse.status === 'fulfilled' ? allStationsResponse.value : [];
  30. return {
  31. reservations: Array.isArray(reservations) ? reservations : [],
  32. stations: Array.isArray(stations) ? stations : []
  33. };
  34. } catch (error) {
  35. return { reservations: [], stations: [] };
  36. }
  37. };
  38. const processReservations = (reservations, allStations, isFuture): TabItem[] => {
  39. // 确保参数是数组类型
  40. const validReservations = Array.isArray(reservations) ? reservations : [];
  41. const validStations = Array.isArray(allStations) ? allStations : [];
  42. const now = Date.now();
  43. return validReservations
  44. .filter((reservation) => {
  45. // 添加安全检查
  46. if (!reservation || !reservation.end_time) return false;
  47. const endTime = Date.parse(reservation.end_time);
  48. if (isNaN(endTime)) return false;
  49. return isFuture ? endTime > now : endTime <= now;
  50. })
  51. .sort((a, b) => {
  52. // 添加安全检查
  53. if (!a?.end_time || !b?.end_time) return 0;
  54. const aTime = Date.parse(a.end_time);
  55. const bTime = Date.parse(b.end_time);
  56. if (isNaN(aTime) || isNaN(bTime)) return 0;
  57. return isFuture ? aTime - bTime : bTime - aTime;
  58. })
  59. .slice(0, 33)
  60. .map((reservation) => {
  61. // 添加对 reservation 的安全检查
  62. if (!reservation) {
  63. return {} as TabItem; // 返回默认对象
  64. }
  65. let snapshot = {};
  66. try {
  67. snapshot = reservation.snapshot ? JSON.parse(reservation.snapshot) : {};
  68. } catch (e) {
  69. console.warn('Error parsing snapshot:', e);
  70. }
  71. let stationInfo = null;
  72. if (snapshot?.stationID) {
  73. stationInfo = validStations.find((station) => station?.id === snapshot.stationID);
  74. } else if (snapshot?.connector) {
  75. stationInfo = findStationByConnectorId(validStations, snapshot.connector);
  76. }
  77. // 确保时间字段存在
  78. const bookTime = reservation.book_time ? new Date(reservation.book_time) : new Date();
  79. const actualEndTime = reservation.actual_end_time ? new Date(reservation.actual_end_time) : new Date();
  80. // console.log('stationInfosssss', stationInfo.image);
  81. const img = stationInfo.image
  82. ? { uri: stationInfo.image }
  83. : require('../../assets/dummyStationPicture.png');
  84. return {
  85. imgURL: img,
  86. date: `${bookTime.getMonth() + 1}月${bookTime.getDate()}`,
  87. time: bookTime.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false }),
  88. actual_end_time: actualEndTime.toLocaleTimeString('zh-CN', {
  89. hour: '2-digit',
  90. minute: '2-digit',
  91. hour12: false
  92. }),
  93. chargeStationName: stationInfo?.snapshot?.StationName || 'Unknown Station',
  94. chargeStationAddress: stationInfo?.snapshot?.Address || 'Unknown Address',
  95. stationLng: stationInfo?.snapshot?.StationLng || '',
  96. stationLat: stationInfo?.snapshot?.StationLat || '',
  97. distance: '',
  98. format_order_id: reservation.format_order_id || '',
  99. actual_total_power: reservation.actual_total_power || 0,
  100. total_fee: reservation.total_fee || 0,
  101. withdraw_fee: reservation.withdraw_fee || 0,
  102. actual_fee: (reservation.total_fee || 0) - (reservation.withdraw_fee || 0),
  103. current_price: snapshot?.current_price || 0,
  104. total_power: reservation.total_power || 0
  105. } as TabItem;
  106. });
  107. };
  108. const BookingTabViewComponentInner: React.FC<BookingTabViewComponentProps> = ({ titles }) => {
  109. const { data, isLoading, error } = useQuery({
  110. queryKey: ['reservationsAndStations'],
  111. queryFn: fetchReservationsAndStations,
  112. staleTime: 0,
  113. gcTime: 0,
  114. refetchOnMount: true,
  115. refetchOnWindowFocus: true
  116. });
  117. if (isLoading) {
  118. return (
  119. <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
  120. <ActivityIndicator size="large" color="#34657b" />
  121. </View>
  122. );
  123. }
  124. if (error) {
  125. console.log('Error fetching data:', error);
  126. return null;
  127. }
  128. if (!data) {
  129. return null;
  130. }
  131. // 确保即使 data 为 undefined 也能安全处理
  132. const reservations = Array.isArray(data?.reservations) ? data.reservations : [];
  133. const stations = Array.isArray(data?.stations) ? data.stations : [];
  134. const tabItems = processReservations(reservations, stations, true);
  135. const completedReservationTabItems = processReservations(reservations, stations, false);
  136. return (
  137. <TabViewComponent
  138. titles={titles}
  139. tabItems={tabItems}
  140. completedReservationTabItems={completedReservationTabItems}
  141. isLoading={false}
  142. />
  143. );
  144. };
  145. const BookingTabViewComponent: React.FC<BookingTabViewComponentProps> = (props) => (
  146. <QueryClientProvider client={queryClient}>
  147. <BookingTabViewComponentInner {...props} />
  148. </QueryClientProvider>
  149. );
  150. export default BookingTabViewComponent;