resultDetailPageComponent.tsx 18 KB

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