bookingTabViewComponent.tsx 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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. return {
  30. reservations: Array.isArray(reservations) ? reservations : [],
  31. stations: Array.isArray(stations) ? stations : []
  32. };
  33. } catch (error) {
  34. return { reservations: [], stations: [] };
  35. }
  36. };
  37. const processReservations = (reservations: any [], allStations: string [], isFuture: boolean): TabItem[] => {
  38. // 确保参数是数组类型
  39. const validReservations = Array.isArray(reservations) ? reservations : [];
  40. const validStations = Array.isArray(allStations) ? allStations : [];
  41. const now = Date.now();
  42. return validReservations
  43. .filter((reservation) => {
  44. // 添加安全检查
  45. if (!reservation || !reservation.end_time) return false;
  46. const endTime = Date.parse(reservation.end_time);
  47. if (isNaN(endTime)) return false;
  48. return isFuture ? endTime > now : endTime <= now;
  49. })
  50. .sort((a, b) => {
  51. // 添加安全检查
  52. if (!a?.end_time || !b?.end_time) return 0;
  53. const aTime = Date.parse(a.end_time);
  54. const bTime = Date.parse(b.end_time);
  55. if (isNaN(aTime) || isNaN(bTime)) return 0;
  56. return isFuture ? aTime - bTime : bTime - aTime;
  57. })
  58. .slice(0, 33)
  59. .map((reservation) => {
  60. // 添加对 reservation 的安全检查
  61. if (!reservation) {
  62. return {} as TabItem; // 返回默认对象
  63. }
  64. let snapshot = {} as any;
  65. let snapshot_price = {} as any;
  66. try {
  67. snapshot = reservation.connector.EquipmentID.StationID.snapshot ? JSON.parse(reservation.connector.EquipmentID.StationID.snapshot) : {};
  68. snapshot_price = reservation.snapshot ? JSON.parse(reservation.snapshot) : {};
  69. } catch (e) {
  70. console.warn('Error parsing snapshot:', e);
  71. }
  72. let stationInfo = null;
  73. if (snapshot?.StationID) {
  74. stationInfo = validStations.find((station) => station?.id === snapshot.StationID);
  75. } else if (snapshot?.connector) {
  76. stationInfo = findStationByConnectorId(validStations, snapshot.connector);
  77. }
  78. // 确保时间字段存在
  79. const bookTime = reservation.book_time ? new Date(reservation.book_time) : new Date();
  80. const actualEndTime = reservation.actual_end_time ? new Date(reservation.actual_end_time) : new Date();
  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_price?.current_price || 0,
  104. total_power: reservation.total_power || 0,
  105. id: reservation.id || ''
  106. } as TabItem;
  107. });
  108. };
  109. const BookingTabViewComponentInner: React.FC<BookingTabViewComponentProps> = ({ titles }) => {
  110. const { data, isLoading, error } = useQuery({
  111. queryKey: ['reservationsAndStations'],
  112. queryFn: fetchReservationsAndStations,
  113. staleTime: 0,
  114. gcTime: 0,
  115. refetchOnMount: true,
  116. refetchOnWindowFocus: true
  117. });
  118. if (isLoading) {
  119. return (
  120. <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
  121. <ActivityIndicator size="large" color="#34657b" />
  122. </View>
  123. );
  124. }
  125. if (error) {
  126. console.log('Error fetching data:', error);
  127. return null;
  128. }
  129. if (!data) {
  130. return null;
  131. }
  132. // 确保即使 data 为 undefined 也能安全处理
  133. const reservations = Array.isArray(data?.reservations) ? data.reservations : [];
  134. const stations = Array.isArray(data?.stations) ? data.stations : [];
  135. const futureReservations = processReservations(reservations, stations, true);
  136. const completedReservations = processReservations(reservations, stations, false);
  137. const allReservationItems = [...futureReservations, ...completedReservations];
  138. // const allReservationItems = [...futureReservations];
  139. return (
  140. <TabViewComponent
  141. titles={titles}
  142. tabItems={allReservationItems}
  143. isLoading={false}
  144. />
  145. );
  146. };
  147. const BookingTabViewComponent: React.FC<BookingTabViewComponentProps> = (props) => (
  148. <QueryClientProvider client={queryClient}>
  149. <BookingTabViewComponentInner {...props} />
  150. </QueryClientProvider>
  151. );
  152. export default BookingTabViewComponent;