resultDetailPageComponent.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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 { calculateDistance } from '../global/distanceCalculator';
  23. interface ChargingStationTabViewProps {
  24. titles: string[];
  25. }
  26. interface StationCoordinates {
  27. StationLat: number;
  28. StationLng: number;
  29. }
  30. const ChargingStationTabView: React.FC<ChargingStationTabViewProps> = ({ titles }) => {
  31. const layout = useWindowDimensions();
  32. //tab 1
  33. const FirstRoute = () => (
  34. <ScrollView style={{ flex: 1, marginHorizontal: '5%' }}>
  35. <Text className="text-lg" style={styles.text}>
  36. 由於充電站車流眾多, 敬請客戶務必於預約時間的十五分鐘內到達充電站。
  37. 若客戶逾時超過15分鐘,系統將視作自動放棄預約,客戶需要重新預約一次。 本公司有權保留全數費用,恕不退還。
  38. </Text>
  39. </ScrollView>
  40. );
  41. //tab 2
  42. const SecondRoute = () => (
  43. <ScrollView style={{ flex: 1, marginHorizontal: '5%' }}>
  44. <Text className="text-lg " style={styles.text}></Text>
  45. </ScrollView>
  46. );
  47. const renderScene = SceneMap({
  48. firstRoute: FirstRoute,
  49. secondRoute: SecondRoute
  50. });
  51. const [routes] = React.useState([
  52. { key: 'firstRoute', title: titles[0] },
  53. { key: 'secondRoute', title: titles[1] }
  54. ]);
  55. const [index, setIndex] = React.useState(0);
  56. const renderTabBar = (props: any) => (
  57. <TabBar
  58. {...props}
  59. indicatorStyle={{
  60. backgroundColor: '#000000',
  61. height: 1
  62. }}
  63. style={{
  64. backgroundColor: 'white',
  65. elevation: 0,
  66. marginHorizontal: 15,
  67. borderBottomWidth: 0.5
  68. }}
  69. />
  70. );
  71. return (
  72. <TabView
  73. navigationState={{ index, routes }}
  74. renderScene={renderScene}
  75. onIndexChange={setIndex}
  76. initialLayout={{ width: layout.width }}
  77. renderTabBar={renderTabBar}
  78. commonOptions={{
  79. label: ({ route, focused }) => (
  80. <Text
  81. style={{
  82. color: focused ? '#000000' : '#CCCCCC',
  83. fontWeight: focused ? '300' : 'thin',
  84. fontSize: 17
  85. }}
  86. >
  87. {route.title}
  88. </Text>
  89. )
  90. }}
  91. />
  92. );
  93. };
  94. const ResultDetailPageComponent = () => {
  95. const params = useLocalSearchParams();
  96. const chargeStationID = params.chargeStationID as string;
  97. const chargeStationName = params.chargeStationName as string;
  98. const chargeStationAddress = params.chargeStationAddress as string;
  99. const availableConnectorsFromParams = params.availableConnectors;
  100. const imageSourceProps = params.imageSource;
  101. const stationLng = params.stationLng as string;
  102. const stationLat = params.stationLat as string;
  103. const [isLoading, setIsLoading] = useState(true);
  104. const [imageSource, setImageSource] = useState();
  105. // const chargeStationLat = params.chargeStationLat as string;
  106. // const chargeStationLng = params.chargeStationLng as string;
  107. const [currentLocation, setCurrentLocation] = useState<Location.LocationObject | null>(null);
  108. const [distance, setDistance] = useState<string | null>(null);
  109. const [coordinates, setCoordinates] = useState<StationCoordinates | null>(null);
  110. const [price, setPrice] = useState('');
  111. const [availableConnectors, setAvailableConnectors] = useState<number | null>(
  112. availableConnectorsFromParams ? Number(availableConnectorsFromParams) : null
  113. );
  114. const [newAvailableConnectors, setNewAvailableConnectors] = useState([]);
  115. useEffect(() => {
  116. const imgObj = imageSourceProps? {uri: imageSourceProps} : require('../../assets/dummyStationPicture.png')
  117. setImageSource(imgObj);
  118. }, [imageSourceProps])
  119. useEffect(() => {
  120. const fetchPrice = async () => {
  121. try {
  122. const price = await chargeStationService.fetchChargeStationPrice(chargeStationID);
  123. setPrice(price);
  124. } catch (error) {
  125. console.error('Error fetching price:', error);
  126. }
  127. };
  128. const getCurrentLocation = async () => {
  129. let { status } = await Location.requestForegroundPermissionsAsync();
  130. if (status !== 'granted') {
  131. console.error('Permission to access location was denied');
  132. return;
  133. }
  134. let location = await Location.getLastKnownPositionAsync({});
  135. setCurrentLocation(location);
  136. };
  137. getCurrentLocation();
  138. fetchPrice();
  139. }, []);
  140. useFocusEffect(
  141. useCallback(() => {
  142. setIsLoading(true);
  143. let isMounted = true; // Simple cleanup flag
  144. const fetchAllConnectors = async () => {
  145. try {
  146. const newAvailableConnectors = await chargeStationService.NewfetchAvailableConnectors();
  147. // Only update state if component is still mounted
  148. if (isMounted) {
  149. setNewAvailableConnectors(newAvailableConnectors);
  150. }
  151. } catch (error) {
  152. console.error('Fetch error:', error);
  153. }
  154. };
  155. fetchAllConnectors();
  156. setIsLoading(false);
  157. // Simple cleanup - prevents state updates if component unmounts
  158. return () => {
  159. isMounted = false;
  160. };
  161. }, []) // Add any missing dependencies here if needed
  162. );
  163. const handleNavigationPress = (StationLat: string, StationLng: string) => {
  164. console.log('starting navigation press in resultDetail', StationLat, StationLng);
  165. if (StationLat && StationLng) {
  166. const label = encodeURIComponent(chargeStationName);
  167. const googleMapsUrl = `https://www.google.com/maps/search/?api=1&query=${StationLat},${StationLng}`;
  168. // Fallback URL for web browser
  169. const webUrl = `https://www.google.com/maps/dir/?api=1&destination=${StationLat},${StationLng}`;
  170. Linking.canOpenURL(googleMapsUrl)
  171. .then((supported) => {
  172. if (supported) {
  173. Linking.openURL(googleMapsUrl);
  174. } else {
  175. Linking.openURL(webUrl).catch((err) => {
  176. console.error('An error occurred', err);
  177. Alert.alert(
  178. 'Error',
  179. "Unable to open Google Maps. Please make sure it's installed on your device.",
  180. [{ text: 'OK' }],
  181. { cancelable: false }
  182. );
  183. });
  184. }
  185. })
  186. .catch((err) => console.error('An error occurred', err));
  187. }
  188. };
  189. return (
  190. <SafeAreaView edges={['top', 'left', 'right']} className="flex-1 bg-white">
  191. <ScrollView className="flex-1 ">
  192. <View className="relative">
  193. <Image
  194. source={ imageSource }
  195. resizeMode="cover"
  196. style={{ flex: 1, width: '100%', height: 300 }}
  197. />
  198. <View className="absolute top-8 left-7 ">
  199. <Pressable
  200. onPress={() => {
  201. if (router.canGoBack()) {
  202. router.back();
  203. } else {
  204. router.replace('./');
  205. }
  206. }}
  207. >
  208. <PreviousPageSvg />
  209. </Pressable>
  210. </View>
  211. </View>
  212. <View className="flex-column mx-[5%] mt-[5%]">
  213. <View>
  214. <Text className="text-3xl ">{chargeStationName}</Text>
  215. </View>
  216. <View className="flex-row justify-between items-center">
  217. <Text className="text-base" style={{ color: '#888888' }}>
  218. {chargeStationAddress}
  219. </Text>
  220. <NormalButton
  221. title={
  222. <View className="flex-row items-center justify-center text-center space-x-1">
  223. <DirectionLogoSvg />
  224. <Text className="text-base ">路線</Text>
  225. </View>
  226. }
  227. onPress={() => handleNavigationPress(stationLat, stationLng)}
  228. extendedStyle={{
  229. backgroundColor: '#E3F2F8',
  230. borderRadius: 61,
  231. paddingHorizontal: 20,
  232. paddingVertical: 6
  233. }}
  234. />
  235. </View>
  236. <View className="flex-row space-x-2 items-center pb-4 ">
  237. <CheckMarkLogoSvg />
  238. <Text>Walk-In</Text>
  239. {/* <Text>{distance} </Text> */}
  240. </View>
  241. <View
  242. className="flex-1 flex-row min-h-[20px] border-slate-300 my-6 rounded-2xl"
  243. style={{ borderWidth: 1 }}
  244. >
  245. <View className="flex-1 m-4">
  246. <View className="flex-1 flex-row ">
  247. <View className=" flex-1 flex-column ustify-between">
  248. <Text className="text-xl " style={styles.text}>
  249. 收費
  250. </Text>
  251. <View className="flex-row items-center space-x-2">
  252. <Text className="text-3xl text-[#02677D]">${price}</Text>
  253. <Text style={styles.text}>每度電</Text>
  254. </View>
  255. </View>
  256. <View className="items-center justify-center">
  257. <View className="w-[1px] h-[60%] bg-[#CCCCCC]" />
  258. </View>
  259. <View className=" flex-1 pl-4 flex-column justify-between">
  260. <Text className="text-xl " style={styles.text}>
  261. 現時可用充電槍數目
  262. </Text>
  263. <View className="flex-row items-center space-x-2">
  264. {isLoading ? (
  265. <Text>Loading...</Text>
  266. ) : (
  267. // <ActivityIndicator />
  268. <Text className="text-3xl text-[#02677D]">
  269. {
  270. newAvailableConnectors.find(
  271. (station: any) => station.stationID === chargeStationID
  272. )?.availableConnectors
  273. }
  274. </Text>
  275. )}
  276. </View>
  277. </View>
  278. </View>
  279. </View>
  280. </View>
  281. </View>
  282. <View className="min-h-[300px]">
  283. <Text className="text-xl pb-2 mx-[5%]" style={styles.text}>
  284. 充電站資訊
  285. </Text>
  286. <ChargingStationTabView titles={['預約充電事項', '其他']} />
  287. </View>
  288. </ScrollView>
  289. </SafeAreaView>
  290. );
  291. };
  292. export default ResultDetailPageComponent;
  293. const styles = StyleSheet.create({
  294. text: {
  295. fontWeight: 300,
  296. color: '#000000'
  297. }
  298. });