bookingTabViewComponent.tsx 7.1 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. // 更新 findStationByConnectorId 函数以增加安全性
  8. const findStationByConnectorId = (allStations: any[], targetConnectorId: string) => {
  9. if (!Array.isArray(allStations) || !targetConnectorId) {
  10. return undefined;
  11. }
  12. return allStations.find((station) =>
  13. station?.snapshot?.EquipmentInfos?.some((equipment: any) =>
  14. equipment?.ConnectorInfos?.some((connector: any) => connector?.ConnectorID === targetConnectorId)
  15. )
  16. );
  17. };
  18. const fetchReservationsAndStations = async () => {
  19. try {
  20. const [reservationResponse, allStationsResponse] = await Promise.allSettled([
  21. chargeStationService.fetchReservationHistories(),
  22. chargeStationService.fetchAllChargeStations()
  23. ]);
  24. const reservations = reservationResponse.status === 'fulfilled' ? reservationResponse.value : [];
  25. const stations = allStationsResponse.status === 'fulfilled' ? allStationsResponse.value : [];
  26. return {
  27. reservations: Array.isArray(reservations) ? reservations : [],
  28. stations: Array.isArray(stations) ? stations : []
  29. };
  30. } catch (error) {
  31. return { reservations: [], stations: [] };
  32. }
  33. };
  34. const processReservations = (reservations: any [], allStations: string [], isFuture: boolean): TabItem[] => {
  35. // 确保参数是数组类型
  36. const validReservations = Array.isArray(reservations) ? reservations : [];
  37. const validStations = Array.isArray(allStations) ? allStations : [];
  38. const now = Date.now();
  39. return validReservations
  40. .filter((reservation) => {
  41. // 添加安全检查
  42. if (!reservation || !reservation.end_time) return false;
  43. const endTime = Date.parse(reservation.end_time);
  44. if (isNaN(endTime)) return false;
  45. return isFuture ? endTime > now : endTime <= now;
  46. })
  47. .sort((a, b) => {
  48. // 添加安全检查
  49. if (!a?.end_time || !b?.end_time) return 0;
  50. const aTime = Date.parse(a.end_time);
  51. const bTime = Date.parse(b.end_time);
  52. if (isNaN(aTime) || isNaN(bTime)) return 0;
  53. return isFuture ? aTime - bTime : bTime - aTime;
  54. })
  55. .slice(0, 33)
  56. .map((reservation) => {
  57. // 添加对 reservation 的安全检查
  58. if (!reservation) {
  59. return {} as TabItem; // 返回默认对象
  60. }
  61. let snapshot = {} as any;
  62. let snapshot_price = {} as any;
  63. try {
  64. snapshot = reservation.connector.EquipmentID.StationID.snapshot ? JSON.parse(reservation.connector.EquipmentID.StationID.snapshot) : {};
  65. snapshot_price = reservation.snapshot ? JSON.parse(reservation.snapshot) : {};
  66. } catch (e) {
  67. console.warn('Error parsing snapshot:', e);
  68. }
  69. let stationInfo = null;
  70. if (snapshot?.StationID) {
  71. stationInfo = validStations.find((station: any) => station?.id === snapshot.StationID);
  72. } else if (snapshot?.connector) {
  73. stationInfo = findStationByConnectorId(validStations, snapshot.connector);
  74. }
  75. // 确保时间字段存在
  76. const bookTime = reservation.book_time ? new Date(reservation.book_time) : new Date();
  77. const actualEndTime = reservation.actual_end_time ? new Date(reservation.actual_end_time) : new Date();
  78. const img = stationInfo?.image
  79. ? { uri: stationInfo?.image }
  80. : require('../../assets/dummyStationPicture.png');
  81. return {
  82. imgURL: img,
  83. date: `${bookTime.getMonth() + 1}月${bookTime.getDate()}`,
  84. time: bookTime.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false }),
  85. actual_end_time: actualEndTime.toLocaleTimeString('zh-CN', {
  86. hour: '2-digit',
  87. minute: '2-digit',
  88. hour12: false
  89. }),
  90. chargeStationName: stationInfo?.snapshot?.StationName || 'Unknown Station',
  91. chargeStationAddress: stationInfo?.snapshot?.Address || 'Unknown Address',
  92. stationLng: stationInfo?.snapshot?.StationLng || '',
  93. stationLat: stationInfo?.snapshot?.StationLat || '',
  94. distance: '',
  95. format_order_id: reservation.format_order_id || '',
  96. actual_total_power: reservation.actual_total_power || 0,
  97. total_fee: reservation.total_fee || 0,
  98. withdraw_fee: reservation.withdraw_fee || 0,
  99. actual_fee: (reservation.total_fee || 0) - (reservation.withdraw_fee || 0),
  100. current_price: snapshot_price?.current_price || 0,
  101. total_power: reservation.total_power || 0,
  102. id: reservation.id || '',
  103. status: reservation.status || {}
  104. } as TabItem;
  105. });
  106. };
  107. const BookingTabViewComponentInner: React.FC = () => {
  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. // const allReservationItems = [...futureReservations];
  137. console.log('All Reservation Items Processed:', allReservationItems);
  138. return (
  139. <TabViewComponent
  140. tabItems={allReservationItems}
  141. isLoading={false}
  142. />
  143. );
  144. };
  145. const BookingTabViewComponent: React.FC = (props) => (
  146. <QueryClientProvider client={queryClient}>
  147. <BookingTabViewComponentInner {...props} />
  148. </QueryClientProvider>
  149. );
  150. export default BookingTabViewComponent;