resultDetailPageComponent.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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. renderLabel={({ route, focused }) => (
  60. <Text
  61. style={{
  62. color: focused ? '#000000' : '#CCCCCC',
  63. fontWeight: focused ? '300' : 'thin',
  64. fontSize: 17
  65. }}
  66. >
  67. {route.title}
  68. </Text>
  69. )}
  70. indicatorStyle={{
  71. backgroundColor: '#000000',
  72. height: 1
  73. }}
  74. style={{
  75. backgroundColor: 'white',
  76. elevation: 0,
  77. marginHorizontal: 15,
  78. borderBottomWidth: 0.5
  79. }}
  80. />
  81. );
  82. return (
  83. <TabView
  84. navigationState={{ index, routes }}
  85. renderScene={renderScene}
  86. onIndexChange={setIndex}
  87. initialLayout={{ width: layout.width }}
  88. renderTabBar={renderTabBar}
  89. />
  90. );
  91. };
  92. const ResultDetailPageComponent = () => {
  93. const params = useLocalSearchParams();
  94. const chargeStationID = params.chargeStationID as string;
  95. const chargeStationName = params.chargeStationName as string;
  96. const chargeStationAddress = params.chargeStationAddress as string;
  97. const availableConnectorsFromParams = params.availableConnectors;
  98. const imageSource = params.imageSource;
  99. const [isLoading, setIsLoading] = useState(true);
  100. // const chargeStationLat = params.chargeStationLat as string;
  101. // const chargeStationLng = params.chargeStationLng as string;
  102. const [currentLocation, setCurrentLocation] = useState<Location.LocationObject | null>(null);
  103. const [distance, setDistance] = useState<string | null>(null);
  104. const [coordinates, setCoordinates] = useState<StationCoordinates | null>(null);
  105. const [price, setPrice] = useState('');
  106. const [availableConnectors, setAvailableConnectors] = useState<number | null>(
  107. availableConnectorsFromParams ? Number(availableConnectorsFromParams) : null
  108. );
  109. const [newAvailableConnectors, setNewAvailableConnectors] = useState([]);
  110. useEffect(() => {
  111. const getCurrentLocation = async () => {
  112. let { status } = await Location.requestForegroundPermissionsAsync();
  113. if (status !== 'granted') {
  114. console.error('Permission to access location was denied');
  115. return;
  116. }
  117. let location = await Location.getLastKnownPositionAsync({});
  118. setCurrentLocation(location);
  119. };
  120. getCurrentLocation();
  121. }, []);
  122. // useEffect(() => {
  123. // const getDistance = async () => {
  124. // if (currentLocation) {
  125. // let stationLat, stationLng;
  126. // if (params.chargeStationLat && params.chargeStationLng) {
  127. // stationLat = Number(params.chargeStationLat);
  128. // stationLng = Number(params.chargeStationLng);
  129. // } else if (coordinates) {
  130. // stationLat = coordinates.StationLat;
  131. // stationLng = coordinates.StationLng;
  132. // } else {
  133. // console.log('No station coordinates available');
  134. // return;
  135. // }
  136. // try {
  137. // const distance = await calculateDistance(stationLat, stationLng, currentLocation);
  138. // setDistance(formatDistance(distance));
  139. // } catch (error) {
  140. // console.error('Error calculating distance:', error);
  141. // }
  142. // }
  143. // };
  144. // getDistance();
  145. // }, [params.chargeStationLat, params.chargeStationLng, coordinates, currentLocation]);
  146. useEffect(() => {
  147. const fetchPrice = async () => {
  148. try {
  149. const price = await chargeStationService.fetchChargeStationPrice(chargeStationID);
  150. setPrice(price);
  151. } catch (error) {
  152. console.error('Error fetching price:', error);
  153. }
  154. };
  155. fetchPrice();
  156. }, []);
  157. // console.log(chargeStationLat, chargeStationLng);
  158. // const memoizedCoordinates = useMemo(() => {
  159. // if (params.chargeStationLat && params.chargeStationLng) {
  160. // return {
  161. // StationLat: parseFloat(params.chargeStationLat as string),
  162. // StationLng: parseFloat(params.chargeStationLng as string)
  163. // };
  164. // }
  165. // return null;
  166. // }, [params.chargeStationLat, params.chargeStationLng]);
  167. // useEffect(() => {
  168. // const fetchCoordinates = async () => {
  169. // // If coordinates are provided in params, use them
  170. // if (memoizedCoordinates) {
  171. // setCoordinates(memoizedCoordinates);
  172. // } else {
  173. // // If not provided, fetch from API
  174. // try {
  175. // const response = await chargeStationService.fetchChargeStations();
  176. // if (response && response.length > 0) {
  177. // const station = response.find((s) => s.StationID === chargeStationID);
  178. // if (station) {
  179. // setCoordinates({
  180. // StationLat: station.StationLat,
  181. // StationLng: station.StationLng
  182. // });
  183. // }
  184. // }
  185. // } catch (error) {
  186. // console.error('Error fetching coordinates:', error);
  187. // }
  188. // }
  189. // };
  190. // fetchCoordinates();
  191. // }, [chargeStationID, memoizedCoordinates]);
  192. // useEffect(() => {
  193. // const fetchAvailableConnectors = async () => {
  194. // // Skip fetching if we already have the value from params
  195. // if (availableConnectorsFromParams) return;
  196. // try {
  197. // const connectors = await chargeStationService.fetchAvailableConnectors(chargeStationID);
  198. // console.log('connectors number from resultDetailPage', connectors);
  199. // setAvailableConnectors(connectors);
  200. // } catch (error) {
  201. // console.error('Error fetching available connectors:', error);
  202. // setAvailableConnectors(null);
  203. // }
  204. // };
  205. // fetchAvailableConnectors();
  206. // }, [chargeStationID, availableConnectorsFromParams]);
  207. useFocusEffect(
  208. useCallback(() => {
  209. setIsLoading(true);
  210. let isMounted = true; // Simple cleanup flag
  211. const fetchAllConnectors = async () => {
  212. try {
  213. const newAvailableConnectors = await chargeStationService.NewfetchAvailableConnectors();
  214. // Only update state if component is still mounted
  215. if (isMounted) {
  216. setNewAvailableConnectors(newAvailableConnectors);
  217. }
  218. } catch (error) {
  219. console.error('Fetch error:', error);
  220. }
  221. };
  222. fetchAllConnectors();
  223. setIsLoading(false);
  224. // Simple cleanup - prevents state updates if component unmounts
  225. return () => {
  226. isMounted = false;
  227. };
  228. }, []) // Add any missing dependencies here if needed
  229. );
  230. // const formatDistance = (distanceInMeters: number): string => {
  231. // if (distanceInMeters < 1000) {
  232. // return `${Math.round(distanceInMeters)}米`;
  233. // } else {
  234. // const distanceInKm = distanceInMeters / 1000;
  235. // return `${distanceInKm.toFixed(1)}公里`;
  236. // }
  237. // };
  238. const handleNavigationPress = () => {
  239. console.log('starting navigation press in resultDetail', coordinates);
  240. if (coordinates) {
  241. const { StationLat, StationLng } = coordinates;
  242. const label = encodeURIComponent(chargeStationName);
  243. const googleMapsUrl = `https://www.google.com/maps/search/?api=1&query=${StationLat},${StationLng}`;
  244. // Fallback URL for web browser
  245. const webUrl = `https://www.google.com/maps/dir/?api=1&destination=${StationLat},${StationLng}`;
  246. Linking.canOpenURL(googleMapsUrl)
  247. .then((supported) => {
  248. if (supported) {
  249. Linking.openURL(googleMapsUrl);
  250. } else {
  251. Linking.openURL(webUrl).catch((err) => {
  252. console.error('An error occurred', err);
  253. Alert.alert(
  254. 'Error',
  255. "Unable to open Google Maps. Please make sure it's installed on your device.",
  256. [{ text: 'OK' }],
  257. { cancelable: false }
  258. );
  259. });
  260. }
  261. })
  262. .catch((err) => console.error('An error occurred', err));
  263. }
  264. };
  265. const handleNavigaationPress = () => {
  266. const latitude = chargeStationLat;
  267. const longitude = chargeStationLng;
  268. console.log('latitude', latitude);
  269. console.log('longitude', longitude);
  270. const label = encodeURIComponent(chargeStationName);
  271. // Google Maps App URL
  272. const googleMapsUrl = `https://www.google.com/maps/search/?api=1&query=${latitude},${longitude}`;
  273. // Fallback URL for web browser
  274. const webUrl = `https://www.google.com/maps/dir/?api=1&destination=${latitude},${longitude}`;
  275. Linking.canOpenURL(googleMapsUrl)
  276. .then((supported) => {
  277. if (supported) {
  278. Linking.openURL(googleMapsUrl);
  279. } else {
  280. Linking.openURL(webUrl).catch((err) => {
  281. console.error('An error occurred', err);
  282. Alert.alert(
  283. 'Error',
  284. "Unable to open Google Maps. Please make sure it's installed on your device.",
  285. [{ text: 'OK' }],
  286. { cancelable: false }
  287. );
  288. });
  289. }
  290. })
  291. .catch((err) => console.error('An error occurred', err));
  292. };
  293. const handleAddBooking = () => {
  294. if (coordinates) {
  295. router.push({
  296. pathname: 'makingBookingPage',
  297. params: {
  298. chargeStationID: chargeStationID,
  299. chargeStationAddress: chargeStationAddress,
  300. chargeStationName: chargeStationName,
  301. chargeStationLat: coordinates.StationLat.toString(),
  302. chargeStationLng: coordinates.StationLng.toString()
  303. }
  304. });
  305. }
  306. };
  307. return (
  308. <SafeAreaView edges={['top', 'left', 'right']} className="flex-1 bg-white">
  309. <ScrollView className="flex-1 ">
  310. <View className="relative">
  311. <Image
  312. source={{ uri: imageSource }}
  313. resizeMode="cover"
  314. style={{ flex: 1, width: '100%', height: 300 }}
  315. />
  316. <View className="absolute top-8 left-7 ">
  317. <Pressable
  318. onPress={() => {
  319. if (router.canGoBack()) {
  320. router.back();
  321. } else {
  322. router.replace('./');
  323. }
  324. }}
  325. >
  326. <PreviousPageSvg />
  327. </Pressable>
  328. </View>
  329. </View>
  330. <View className="flex-column mx-[5%] mt-[5%]">
  331. <View>
  332. <Text className="text-3xl ">{chargeStationName}</Text>
  333. </View>
  334. <View className="flex-row justify-between items-center">
  335. <Text className="text-base" style={{ color: '#888888' }}>
  336. {chargeStationAddress}
  337. </Text>
  338. <NormalButton
  339. title={
  340. <View className="flex-row items-center justify-center text-center space-x-1">
  341. <DirectionLogoSvg />
  342. <Text className="text-base ">路線</Text>
  343. </View>
  344. }
  345. onPress={handleNavigationPress}
  346. extendedStyle={{
  347. backgroundColor: '#E3F2F8',
  348. borderRadius: 61,
  349. paddingHorizontal: 20,
  350. paddingVertical: 6
  351. }}
  352. />
  353. </View>
  354. <View className="flex-row space-x-2 items-center pb-4 ">
  355. <CheckMarkLogoSvg />
  356. <Text>Walk-In</Text>
  357. {/* <Text>{distance} </Text> */}
  358. </View>
  359. {/* {coordinates ? (
  360. <NormalButton
  361. title={
  362. <View className="pr-2">
  363. <Text
  364. style={{
  365. color: '#FFFFFF',
  366. fontWeight: 700,
  367. fontSize: 20
  368. }}
  369. >
  370. + 新增預約
  371. </Text>
  372. </View>
  373. }
  374. // onPress={() => console.log('ab')}
  375. onPress={handleAddBooking}
  376. />
  377. ) : (
  378. <NormalButton
  379. title={
  380. <View className="pr-2">
  381. <Text
  382. style={{
  383. color: '#FFFFFF',
  384. fontWeight: 700,
  385. fontSize: 20
  386. }}
  387. >
  388. <ActivityIndicator />
  389. </Text>
  390. </View>
  391. }
  392. // onPress={() => console.log('ab')}
  393. onPress={handleAddBooking}
  394. />
  395. )} */}
  396. <View
  397. className="flex-1 flex-row min-h-[20px] border-slate-300 my-6 rounded-2xl"
  398. style={{ borderWidth: 1 }}
  399. >
  400. <View className="flex-1 m-4">
  401. <View className="flex-1 flex-row ">
  402. <View className=" flex-1 flex-column ustify-between">
  403. <Text className="text-xl " style={styles.text}>
  404. 收費
  405. </Text>
  406. <View className="flex-row items-center space-x-2">
  407. <Text className="text-3xl text-[#02677D]">${price}</Text>
  408. <Text style={styles.text}>每度電</Text>
  409. </View>
  410. </View>
  411. <View className="items-center justify-center">
  412. <View className="w-[1px] h-[60%] bg-[#CCCCCC]" />
  413. </View>
  414. <View className=" flex-1 pl-4 flex-column justify-between">
  415. <Text className="text-xl " style={styles.text}>
  416. 現時可用充電槍數目
  417. </Text>
  418. <View className="flex-row items-center space-x-2">
  419. {isLoading ? (
  420. <Text>Loading...</Text>
  421. ) : (
  422. // <ActivityIndicator />
  423. <Text className="text-3xl text-[#02677D]">
  424. {
  425. newAvailableConnectors.find(
  426. (station: any) => station.stationID === chargeStationID
  427. )?.availableConnectors
  428. }
  429. </Text>
  430. )}
  431. </View>
  432. </View>
  433. </View>
  434. </View>
  435. </View>
  436. </View>
  437. <View className="min-h-[300px]">
  438. <Text className="text-xl pb-2 mx-[5%]" style={styles.text}>
  439. 充電站資訊
  440. </Text>
  441. <ChargingStationTabView titles={['預約充電事項', '其他']} />
  442. </View>
  443. </ScrollView>
  444. </SafeAreaView>
  445. );
  446. };
  447. export default ResultDetailPageComponent;
  448. const styles = StyleSheet.create({
  449. text: {
  450. fontWeight: 300,
  451. color: '#000000'
  452. }
  453. });