bookingTabViewComponent.tsx 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  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 './chargingRecord';
  5. import { chargeStationService } from '../../service/chargeStationService';
  6. const queryClient = new QueryClient();
  7. interface BookingTabViewComponentProps {
  8. titles: string[];
  9. }
  10. // 更新 findStationByConnectorId 函数以增加安全性
  11. const findStationByConnectorId = (allStations, targetConnectorId) => {
  12. if (!Array.isArray(allStations) || !targetConnectorId) {
  13. return undefined;
  14. }
  15. return allStations.find((station) =>
  16. station?.snapshot?.EquipmentInfos?.some((equipment) =>
  17. equipment?.ConnectorInfos?.some((connector) => connector?.ConnectorID === targetConnectorId)
  18. )
  19. );
  20. };
  21. const fetchReservationsAndStations = async () => {
  22. try {
  23. const [reservationResponse, allStationsResponse] = await Promise.allSettled([
  24. chargeStationService.fetchReservationHistories(),
  25. chargeStationService.fetchAllChargeStations()
  26. ]);
  27. const reservations = reservationResponse.status === 'fulfilled' ? reservationResponse.value : [];
  28. const stations = allStationsResponse.status === 'fulfilled' ? allStationsResponse.value : [];
  29. console.log('received data', reservationResponse);
  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: any [], allStations: string [], isFuture: boolean): 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 = {} as any;
  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. const img = stationInfo?.image
  81. ? { uri: stationInfo?.image }
  82. : require('../../assets/dummyStationPicture.png');
  83. return {
  84. imgURL: img,
  85. date: `${bookTime.getMonth() + 1}月${bookTime.getDate()}`,
  86. time: bookTime.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false }),
  87. actual_end_time: actualEndTime.toLocaleTimeString('zh-CN', {
  88. hour: '2-digit',
  89. minute: '2-digit',
  90. hour12: false
  91. }),
  92. chargeStationName: stationInfo?.snapshot?.StationName || 'Unknown Station',
  93. chargeStationAddress: stationInfo?.snapshot?.Address || 'Unknown Address',
  94. stationLng: stationInfo?.snapshot?.StationLng || '',
  95. stationLat: stationInfo?.snapshot?.StationLat || '',
  96. distance: '',
  97. format_order_id: reservation.format_order_id || '',
  98. actual_total_power: reservation.actual_total_power || 0,
  99. total_fee: reservation.total_fee || 0,
  100. withdraw_fee: reservation.withdraw_fee || 0,
  101. actual_fee: (reservation.total_fee || 0) - (reservation.withdraw_fee || 0),
  102. current_price: snapshot?.current_price || 0,
  103. total_power: reservation.total_power || 0
  104. } as TabItem;
  105. });
  106. };
  107. const BookingTabViewComponentInner: React.FC<BookingTabViewComponentProps> = ({ titles }) => {
  108. const { data, isLoading, error } = useQuery({
  109. queryKey: ['reservationsAndStations'],
  110. queryFn: fetchReservationsAndStations,
  111. staleTime: 0,
  112. gcTime: 0,
  113. refetchOnMount: true,
  114. refetchOnWindowFocus: true
  115. });
  116. if (isLoading) {
  117. return (
  118. <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
  119. <ActivityIndicator size="large" color="#34657b" />
  120. </View>
  121. );
  122. }
  123. if (error) {
  124. console.log('Error fetching data:', error);
  125. return null;
  126. }
  127. if (!data) {
  128. return null;
  129. }
  130. // 确保即使 data 为 undefined 也能安全处理
  131. const reservations = Array.isArray(data?.reservations) ? data.reservations : [];
  132. const stations = Array.isArray(data?.stations) ? data.stations : [];
  133. const futureReservations = processReservations(reservations, stations, true);
  134. const completedReservations = processReservations(reservations, stations, false);
  135. const allReservationItems = [...futureReservations, ...completedReservations];
  136. return (
  137. <TabViewComponent
  138. titles={titles}
  139. tabItems={allReservationItems}
  140. isLoading={false}
  141. />
  142. );
  143. };
  144. const BookingTabViewComponent: React.FC<BookingTabViewComponentProps> = (props) => (
  145. <QueryClientProvider client={queryClient}>
  146. <BookingTabViewComponentInner {...props} />
  147. </QueryClientProvider>
  148. );
  149. export default BookingTabViewComponent;