resultDetailPageComponent.tsx 18 KB

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