resultDetailPageComponent.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. import {
  2. View,
  3. Text,
  4. ScrollView,
  5. Image,
  6. useWindowDimensions,
  7. StyleSheet,
  8. Pressable,
  9. Platform,
  10. Linking,
  11. ActivityIndicator,
  12. Alert
  13. } from 'react-native';
  14. import React, { useCallback, useEffect, useMemo, useState } from 'react';
  15. import { SceneMap, TabBar, TabView } from 'react-native-tab-view';
  16. import NormalButton from '../global/normal_button';
  17. import { router, useFocusEffect, useLocalSearchParams } from 'expo-router';
  18. import { CheckMarkLogoSvg, DirectionLogoSvg, PreviousPageSvg } from '../global/SVG';
  19. import { SafeAreaView } from 'react-native-safe-area-context';
  20. import { chargeStationService } from '../../service/chargeStationService';
  21. import * as Location from 'expo-location';
  22. import { ChargingDetails, Remark, PriceWeek, Special } from '../../service/type/chargeStationType';
  23. import { useTranslation } from '../../util/hooks/useTranslation';
  24. interface ChargingStationTabViewProps {
  25. titles: string[];
  26. pricemodel_id: string;
  27. }
  28. interface ChargingPeriod{
  29. event_name: string;
  30. price: number;
  31. from: string;
  32. to: string;
  33. }
  34. const ChargingStationTabView: React.FC<ChargingStationTabViewProps> = ({ titles, pricemodel_id }) => {
  35. const layout = useWindowDimensions();
  36. const [list, setList] = useState<ChargingPeriod []>([])
  37. const [strWeek, setStrWeek] = useState<string>('')
  38. const { t } = useTranslation();
  39. // 添加AM/PM标识但保持24小时制
  40. const addPeriodToTime = (timeString: string): string => {
  41. // 假设输入格式为 HH.mm 或 HH:mm
  42. const [hours] = timeString.split(/[.:]/).map(Number);
  43. if (isNaN(hours)) return timeString;
  44. const period = hours >= 12 ? 'PM' : 'AM';
  45. return `${timeString}${period}`;
  46. };
  47. useEffect(() => {
  48. chargeStationService.fetchElectricityPrice(pricemodel_id || 'a').then(res => {
  49. const date = new Date();
  50. const str = (date.toLocaleString('en-US', { weekday: 'short' })).toLowerCase();
  51. setStrWeek(date.toLocaleString('zh', { weekday: 'long' }))
  52. const newList = [] as ChargingPeriod[]
  53. res?.forEach((item) => {
  54. const obj = item[str as keyof PriceWeek]
  55. newList.push({event_name: item.event_name, price: obj.price, from: addPeriodToTime(obj.from),to: addPeriodToTime(obj.to)})
  56. setList(newList)
  57. })
  58. })
  59. }, [pricemodel_id])
  60. //tab 1
  61. const FirstRoute = () => (
  62. <ScrollView style={{ flex: 1, marginHorizontal: '5%' }}>
  63. <View>
  64. <View className='w-full flex-row justify-between mt-4'>
  65. <Text style={styles.leftLable}>{t('charging.result_detail_page.time_period')}</Text>
  66. <Text style={styles.rightLable}>{t('charging.result_detail_page.price_per_kwh')}</Text>
  67. </View>
  68. {
  69. list.map((item, index) => (
  70. <View key={index} className='w-full flex-row justify-between mt-3'>
  71. <Text style={styles.leftLable}>{item.from} - {item.to}</Text>
  72. <Text style={styles.rightLable}>${item.price}</Text>
  73. </View>
  74. ))
  75. }
  76. </View>
  77. </ScrollView>
  78. );
  79. //tab 2
  80. const SecondRoute = () => (
  81. <ScrollView style={{ flex: 1, marginHorizontal: '5%' }}>
  82. <Text className="text-lg " style={styles.text}></Text>
  83. </ScrollView>
  84. );
  85. const renderScene = SceneMap({
  86. firstRoute: FirstRoute,
  87. secondRoute: SecondRoute
  88. });
  89. const [routes] = React.useState([
  90. { key: 'firstRoute', title: titles[0] },
  91. { key: 'secondRoute', title: titles[1] }
  92. ]);
  93. const [index, setIndex] = React.useState(0);
  94. const renderTabBar = (props: any) => (
  95. <TabBar
  96. {...props}
  97. indicatorStyle={{
  98. backgroundColor: '#000000',
  99. height: 1
  100. }}
  101. style={{
  102. backgroundColor: 'white',
  103. elevation: 0,
  104. marginHorizontal: 15,
  105. borderBottomWidth: 0.5
  106. }}
  107. />
  108. );
  109. return (
  110. <TabView
  111. navigationState={{ index, routes }}
  112. renderScene={renderScene}
  113. onIndexChange={setIndex}
  114. initialLayout={{ width: layout.width }}
  115. renderTabBar={renderTabBar}
  116. commonOptions={{
  117. label: ({ route, focused }) => (
  118. <Text
  119. style={{
  120. color: focused ? '#000000' : '#CCCCCC',
  121. fontWeight: focused ? '300' : 'thin',
  122. fontSize: 17
  123. }}
  124. >
  125. {route.title}
  126. </Text>
  127. )
  128. }}
  129. />
  130. );
  131. };
  132. const ResultDetailPageComponent = () => {
  133. const params = useLocalSearchParams();
  134. const chargeStationID = params.chargeStationID as string;
  135. const chargeStationName = params.chargeStationName as string;
  136. const chargeStationAddress = params.chargeStationAddress as string;
  137. const pricemodel_id = params.pricemodel_id as string;
  138. const imageSourceProps = params.imageSource;
  139. const stationLng = params.stationLng as string;
  140. const stationLat = params.stationLat as string;
  141. const [isLoading, setIsLoading] = useState(true);
  142. const [imageSource, setImageSource] = useState();
  143. const [currentLocation, setCurrentLocation] = useState<Location.LocationObject | null>(null);
  144. const [price, setPrice] = useState('');
  145. const [newAvailableConnectors, setNewAvailableConnectors] = useState<any>([]);
  146. const { t } = useTranslation();
  147. useEffect(() => {
  148. const imgObj = imageSourceProps? {uri: imageSourceProps} : require('../../assets/dummyStationPicture.png')
  149. setImageSource(imgObj);
  150. }, [imageSourceProps])
  151. useEffect(() => {
  152. const fetchPrice = async () => {
  153. try {
  154. const price = await chargeStationService.fetchChargeStationPrice(chargeStationID);
  155. setPrice(price);
  156. } catch (error) {
  157. console.error('Error fetching price:', error);
  158. }
  159. };
  160. const getCurrentLocation = async () => {
  161. let { status } = await Location.requestForegroundPermissionsAsync();
  162. if (status !== 'granted') {
  163. console.error('Permission to access location was denied');
  164. return;
  165. }
  166. let location = await Location.getLastKnownPositionAsync({});
  167. setCurrentLocation(location);
  168. };
  169. getCurrentLocation();
  170. fetchPrice();
  171. }, []);
  172. useFocusEffect(
  173. useCallback(() => {
  174. setIsLoading(true);
  175. let isMounted = true; // Simple cleanup flag
  176. const fetchAllConnectors = async () => {
  177. try {
  178. const newAvailableConnectors = await chargeStationService.NewfetchAvailableConnectors();
  179. // Only update state if component is still mounted
  180. if (isMounted) {
  181. setNewAvailableConnectors(newAvailableConnectors);
  182. }
  183. } catch (error) {
  184. console.error('Fetch error:', error);
  185. }
  186. };
  187. fetchAllConnectors();
  188. setIsLoading(false);
  189. // Simple cleanup - prevents state updates if component unmounts
  190. return () => {
  191. isMounted = false;
  192. };
  193. }, [])
  194. );
  195. const handleNavigationPress = (StationLat: string, StationLng: string) => {
  196. console.log('starting navigation press in resultDetail', StationLat, StationLng);
  197. if (StationLat && StationLng) {
  198. const label = encodeURIComponent(chargeStationName);
  199. const googleMapsUrl = `https://www.google.com/maps/search/?api=1&query=${StationLat},${StationLng}`;
  200. // Fallback URL for web browser
  201. const webUrl = `https://www.google.com/maps/dir/?api=1&destination=${StationLat},${StationLng}`;
  202. Linking.canOpenURL(googleMapsUrl)
  203. .then((supported) => {
  204. if (supported) {
  205. Linking.openURL(googleMapsUrl);
  206. } else {
  207. Linking.openURL(webUrl).catch((err) => {
  208. console.error('An error occurred', err);
  209. Alert.alert(
  210. t('common.error'),
  211. t('charging.result_detail_page.unable_open_maps'),
  212. [{ text: t('common.ok') }],
  213. { cancelable: false }
  214. );
  215. });
  216. }
  217. })
  218. .catch((err) => console.error('An error occurred', err));
  219. }
  220. };
  221. return (
  222. <SafeAreaView edges={['top', 'left', 'right']} className="flex-1 bg-white">
  223. <ScrollView className="flex-1 ">
  224. <View className="relative">
  225. <Image
  226. source={ imageSource }
  227. resizeMode="cover"
  228. style={{ flex: 1, width: '100%', height: 300 }}
  229. />
  230. <View className="absolute top-8 left-7 ">
  231. <Pressable
  232. onPress={() => {
  233. if (router.canGoBack()) {
  234. router.back();
  235. } else {
  236. router.replace('./');
  237. }
  238. }}
  239. >
  240. <PreviousPageSvg />
  241. </Pressable>
  242. </View>
  243. </View>
  244. <View className="flex-column mx-[5%] mt-[5%]">
  245. <View>
  246. <Text className="text-3xl ">{chargeStationName}</Text>
  247. </View>
  248. <View className="flex-row justify-between items-center">
  249. <Text className="text-base" style={{ color: '#888888' }}>
  250. {chargeStationAddress}
  251. </Text>
  252. <NormalButton
  253. title={
  254. <View className="flex-row items-center justify-center text-center space-x-1">
  255. <DirectionLogoSvg />
  256. <Text className="text-base ">{t('charging.result_detail_page.route')}</Text>
  257. </View>
  258. }
  259. onPress={() => handleNavigationPress(stationLat, stationLng)}
  260. extendedStyle={{
  261. backgroundColor: '#E3F2F8',
  262. borderRadius: 61,
  263. paddingHorizontal: 20,
  264. paddingVertical: 6
  265. }}
  266. />
  267. </View>
  268. <View className="flex-row space-x-2 items-center pb-4 ">
  269. <CheckMarkLogoSvg />
  270. <Text>Walk-In</Text>
  271. {/* <Text>{distance} </Text> */}
  272. </View>
  273. <View
  274. className="flex-1 flex-row min-h-[20px] border-slate-300 my-6 rounded-2xl"
  275. style={{ borderWidth: 1 }}
  276. >
  277. <View className="flex-1 m-4">
  278. <View className="flex-1 flex-row ">
  279. <View className=" flex-1 flex-column ustify-between">
  280. <Text className="text-xl " style={styles.text}>
  281. {t('charging.result_detail_page.charging_fee')}
  282. </Text>
  283. <View className="flex-row items-center space-x-2">
  284. <Text className="text-3xl text-[#02677D]">${price}</Text>
  285. <Text style={styles.text}>{t('charging.result_detail_page.per_kwh')}</Text>
  286. </View>
  287. </View>
  288. <View className="items-center justify-center">
  289. <View className="w-[1px] h-[60%] bg-[#CCCCCC]" />
  290. </View>
  291. <View className=" flex-1 pl-4 flex-column justify-between">
  292. <Text className="text-xl " style={styles.text}>
  293. {t('charging.result_detail_page.available_connectors')}
  294. </Text>
  295. <View className="flex-row items-center space-x-2">
  296. {isLoading ? (
  297. <Text>{t('charging.result_detail_page.loading')}</Text>
  298. ) : (
  299. // <ActivityIndicator />
  300. <Text className="text-3xl text-[#02677D]">
  301. {
  302. newAvailableConnectors.find(
  303. (station: any) => station.stationID === chargeStationID
  304. )?.availableConnectors
  305. }
  306. </Text>
  307. )}
  308. </View>
  309. </View>
  310. </View>
  311. </View>
  312. </View>
  313. </View>
  314. <View className="min-h-[300px]">
  315. <Text className="text-xl pb-2 mx-[5%]" style={styles.text}>
  316. {t('charging.result_detail_page.station_info')}
  317. </Text>
  318. <ChargingStationTabView titles={[t('charging.result_detail_page.pricing_details'), t('charging.result_detail_page.others')]} pricemodel_id={pricemodel_id} />
  319. </View>
  320. </ScrollView>
  321. </SafeAreaView>
  322. );
  323. };
  324. export default ResultDetailPageComponent;
  325. const styles = StyleSheet.create({
  326. text: {
  327. fontWeight: 300,
  328. color: '#000000'
  329. },
  330. leftLable: {
  331. width: '65%',
  332. fontSize: 17,
  333. color:'#000000',
  334. textAlign: 'center'
  335. },
  336. rightLable: {
  337. fontSize: 17,
  338. width: '30%',
  339. textAlign: 'center',
  340. borderLeftWidth: 1,
  341. paddingLeft: 0,
  342. },
  343. });