makingBookingPageComponent.tsx 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  1. import {
  2. View,
  3. Text,
  4. ScrollView,
  5. Pressable,
  6. StyleSheet,
  7. Image,
  8. Dimensions,
  9. ActivityIndicator,
  10. Platform,
  11. Linking,
  12. Alert
  13. } from 'react-native';
  14. import { SafeAreaView } from 'react-native-safe-area-context';
  15. import { router, useLocalSearchParams } from 'expo-router';
  16. import NormalButton from '../global/normal_button';
  17. import { CheckMarkLogoSvg, DirectionLogoSvg, PreviousPageBlackSvg } from '../global/SVG';
  18. import { ChargingStationTabView } from '../global/chargingStationTabView';
  19. import ChooseCarForChargingRow from '../global/chooseCarForChargingRow';
  20. import { useEffect, useState } from 'react';
  21. import DropdownSelect from '../global/dropdown_select';
  22. import { chargeStationService } from '../../service/chargeStationService';
  23. import { authenticationService } from '../../service/authService';
  24. import * as Location from 'expo-location';
  25. import { calculateDistance } from '../global/distanceCalculator';
  26. import Modal from 'react-native-modal';
  27. import useUserInfoStore from '../../providers/userinfo_store';
  28. interface AccordionItemProps {
  29. title: string;
  30. children: React.ReactNode;
  31. isOpen: boolean;
  32. onToggle: () => void;
  33. isSelected: boolean;
  34. }
  35. const AccordionItem: React.FC<AccordionItemProps> = ({ title, children, isOpen, onToggle, isSelected }) => (
  36. <View className={`${isSelected ? 'bg-[#e7f5f8]' : 'bg-white'}`}>
  37. <View className="mx-[5%]">
  38. <Pressable onPress={onToggle}>
  39. <Text className={` pt-2 text-lg ${isSelected ? 'text-[#222222]' : 'text-[#888888] '}}`}>{title}</Text>
  40. </Pressable>
  41. {isOpen && <View>{children}</View>}
  42. </View>
  43. </View>
  44. );
  45. const MakingBookingPageComponent = () => {
  46. const [isModalVisible, setModalVisible] = useState(false);
  47. const [routerParams, setRouterParams] = useState(null);
  48. const [openDrawer, setOpenDrawer] = useState<number | null>(1);
  49. const [selectedTime, setSelectedTime] = useState<string>('');
  50. const [availableTimeSlots, setAvailableTimeSlots] = useState<string[]>([]);
  51. const [selectedDrawer, setSelectedDrawer] = useState<number>(1);
  52. const [isLoading, setIsLoading] = useState(true);
  53. const [selectedDate, setSelectedDate] = useState<string>('');
  54. const toggleDrawer = (index: number) => {
  55. setOpenDrawer(openDrawer === index ? null : index);
  56. setSelectedDrawer(index);
  57. };
  58. const [defaultCar, setDefaultCar] = useState(null);
  59. const [isDefaultCarLoading, setIsDefaultCarLoading] = useState(true);
  60. const [availableDate, setAvailableDate] = useState<string[]>([]);
  61. const [car, setCar] = useState([]);
  62. const [selectedCarID, setSelectedCarID] = useState('');
  63. const [selectedChargingGun, setSelectedChargingGun] = useState('');
  64. const [chargingBasedOnWatt, setChargingBasedOnWatt] = useState(true);
  65. const [stopChargingUponBatteryFull, setStopChargingUponBatteryFull] = useState(false);
  66. const [selectedCar, setSelectedCar] = useState('');
  67. const [selectedDuration, setSelectedDuration] = useState('');
  68. const { width: screenWidth, height: screenHeight } = Dimensions.get('window');
  69. const [price, setPrice] = useState(0);
  70. const layoutWidth = screenWidth;
  71. const layoutHeight = screenHeight * 0.32;
  72. const { userID, setUserID } = useUserInfoStore();
  73. const params = useLocalSearchParams();
  74. const chargeStationID = params.chargeStationID as string;
  75. const chargeStationName = params.chargeStationName as string;
  76. const chargeStationAddress = params.chargeStationAddress as string;
  77. const chargeStationLat = params.chargeStationLat as string;
  78. const chargeStationLng = params.chargeStationLng as string;
  79. const [selectedWatt, setSelectedWatt] = useState('');
  80. const [availableConnectorDropdownOptions, setAvailableConnectorDropdownOptions] = useState([]);
  81. const [carCapacitance, setCarCapacitance] = useState('');
  82. const [currentLocation, setCurrentLocation] = useState<Location.LocationObject | null>(null);
  83. const [distance, setDistance] = useState<string | null>(null);
  84. const [upcomingReservations, setUpcomingReservation] = useState([]);
  85. const [carLoadingState, setCarLoadingState] = useState(false);
  86. const [isDateLoading, setIsDateLoading] = useState(true);
  87. useEffect(() => {
  88. const getCurrentLocation = async () => {
  89. let { status } = await Location.requestForegroundPermissionsAsync();
  90. if (status !== 'granted') {
  91. console.error('Permission to access location was denied');
  92. return;
  93. }
  94. let location = await Location.getLastKnownPositionAsync({});
  95. setCurrentLocation(location);
  96. };
  97. getCurrentLocation();
  98. }, []);
  99. //getDefaultCar
  100. useEffect(() => {
  101. const fetchDefaultCar = async () => {
  102. setIsDefaultCarLoading(true);
  103. try {
  104. const response = await chargeStationService.getUserDefaultCars();
  105. if (response && response.data) {
  106. setDefaultCar(response.data.id);
  107. setSelectedCarID(response.data.id);
  108. setCarCapacitance(response.data.car_type.capacitance);
  109. setSelectedCar(response.data.id);
  110. console.log('*******', response.data.car_type.capacitance);
  111. }
  112. } catch (error) {
  113. console.log('Error fetching default car:', error);
  114. } finally {
  115. setIsDefaultCarLoading(false);
  116. }
  117. };
  118. fetchDefaultCar();
  119. }, []);
  120. const formatDistance = (distanceInMeters: number): string => {
  121. if (distanceInMeters < 1000) {
  122. return `${Math.round(distanceInMeters)}米`;
  123. } else {
  124. const distanceInKm = distanceInMeters / 1000;
  125. return `${distanceInKm.toFixed(1)}公里`;
  126. }
  127. };
  128. const getUpcomingReservations = (reservations: any, daysAhead = 3) => {
  129. const today = new Date();
  130. const threeDaysLater = new Date(today);
  131. threeDaysLater.setDate(today.getDate() + daysAhead);
  132. return reservations
  133. .filter((reservation) => {
  134. const reservationDate = new Date(reservation.book_time);
  135. return reservationDate >= today && reservationDate <= threeDaysLater;
  136. })
  137. .sort((a, b) => new Date(a.reservationDate) - new Date(b.reservationDate));
  138. };
  139. //USE BELOW to find upcoming reservations, then I filter availableDate and time based on the upcoming ones so user cannot book the same time twice.
  140. const formatReservations = (reservations) => {
  141. const formattedReservations = {};
  142. reservations.forEach((reservation) => {
  143. const bookTime = new Date(reservation.book_time);
  144. const date = formatDate(bookTime);
  145. const time = formatTime(bookTime);
  146. if (!formattedReservations[date]) {
  147. formattedReservations[date] = [];
  148. }
  149. formattedReservations[date].push(time);
  150. });
  151. return Object.entries(formattedReservations).map(([date, times]) => ({
  152. date,
  153. times
  154. }));
  155. };
  156. const formatDate = (date) => {
  157. const month = String(date.getMonth() + 1).padStart(2, '0');
  158. const day = String(date.getDate()).padStart(2, '0');
  159. return `${month}/${day}`;
  160. };
  161. const formatTime = (date) => {
  162. return date.toTimeString().slice(0, 5);
  163. };
  164. useEffect(() => {
  165. const fetchReservationHistories = async () => {
  166. try {
  167. const response = await chargeStationService.fetchReservationHistories();
  168. if (response) {
  169. // console.log('response', response);
  170. // console.log('Reservation histories:', response);
  171. const upcomingReservations = getUpcomingReservations(response);
  172. // console.log('upcomingReservations', upcomingReservations);
  173. const formattedReservations = formatReservations(upcomingReservations);
  174. // console.log('formattedReservations', formattedReservations);
  175. setUpcomingReservation(formattedReservations);
  176. }
  177. 2;
  178. } catch (error) {
  179. console.log(error);
  180. }
  181. };
  182. fetchReservationHistories();
  183. }, []);
  184. //USE ABOVE to find upcoming reservations, then I filter availableDate and time based on the upcoming ones so user cannot book the same time twice.
  185. useEffect(() => {
  186. const getDistance = async () => {
  187. if (currentLocation) {
  188. try {
  189. const distance = await calculateDistance(
  190. Number(params.chargeStationLat),
  191. Number(params.chargeStationLng),
  192. currentLocation
  193. );
  194. setDistance(formatDistance(distance));
  195. } catch (error) {
  196. console.error('Error calculating distance:', error);
  197. }
  198. }
  199. };
  200. getDistance();
  201. }, [params.chargeStationLat, params.chargeStationLng, currentLocation]);
  202. useEffect(() => {
  203. const fetchPrice = async () => {
  204. try {
  205. const price = await chargeStationService.fetchChargeStationPrice(chargeStationID);
  206. setPrice(price);
  207. } catch (error) {
  208. console.error('Error fetching price:', error);
  209. }
  210. };
  211. fetchPrice();
  212. }, []);
  213. function appendImageUrlToCarResult(carData, updatedVehicles) {
  214. return carData.map((car) => {
  215. const matchingVehicle = updatedVehicles.find((vehicle) => vehicle.car_type.name === car.car_name);
  216. if (matchingVehicle) {
  217. return {
  218. ...car,
  219. type_image_url: matchingVehicle.car_type.type_image_url
  220. };
  221. }
  222. return car;
  223. });
  224. }
  225. // useEffect(() => {
  226. // setCarLoadingState(true);
  227. // const fetchUserInfoAndCarData = async () => {
  228. // try {
  229. // const fetchedUserInfo = await authenticationService.getUserInfo();
  230. // const userData = fetchedUserInfo?.data;
  231. // // console.log('userData', userData);
  232. // if (userData) {
  233. // setUserID(userData.id);
  234. // const carData = userData.cars.map((car: any) => ({
  235. // car_name: car.name,
  236. // car_capacitance: car.capacitance,
  237. // car_id: car.id,
  238. // isDefault: car.id === userData.defaultCar?.id
  239. // }));
  240. // // console.log('carDarta', carData);
  241. // setCar(carData);
  242. // const carResult = await chargeStationService.getUserCars();
  243. // let updatedVehicles = [...carResult.data];
  244. // // console.log('updatedVehiaacles', updatedVehicles);
  245. // const updatedCarResult = appendImageUrlToCarResult(carData, updatedVehicles);
  246. // setCar(updatedCarResult);
  247. // let updatedCarResultWithProcessedUrl = [...updatedCarResult];
  248. // for (let i = 0; i < updatedCarResultWithProcessedUrl.length; i++) {
  249. // const car = updatedCarResultWithProcessedUrl[i];
  250. // const processedUrl = await chargeStationService.getProcessedImageUrl(car.type_image_url);
  251. // updatedCarResultWithProcessedUrl[i] = {
  252. // ...car,
  253. // processedImageUrl: processedUrl
  254. // };
  255. // }
  256. // // console.log(updatedCarResultWithProcessedUrl);
  257. // setCar(updatedCarResultWithProcessedUrl);
  258. // }
  259. // } catch (error) {
  260. // console.error('Error fetching user info:', error);
  261. // } finally {
  262. // setCarLoadingState(false);
  263. // }
  264. // };
  265. // fetchUserInfoAndCarData();
  266. // }, []);
  267. useEffect(() => {
  268. const fetchingAvailableTimeSlots = async () => {
  269. setIsLoading(true);
  270. try {
  271. const fetchedTimeSlots = await chargeStationService.fetchAvailableTimeSlots(
  272. chargeStationID,
  273. selectedDate
  274. );
  275. const now = new Date();
  276. const today = `${String(now.getMonth() + 1).padStart(2, '0')}/${String(now.getDate()).padStart(
  277. 2,
  278. '0'
  279. )}`;
  280. let filteredTimeSlots = fetchedTimeSlots;
  281. //filter out today's time slots that have already passed
  282. if (selectedDate === today) {
  283. const currentHours = now.getHours();
  284. const currentMinutes = now.getMinutes();
  285. filteredTimeSlots = fetchedTimeSlots.filter((time) => {
  286. const [hours, minutes] = time.split(':').map(Number);
  287. if (hours > currentHours) return true;
  288. if (hours === currentHours && minutes > currentMinutes) return true;
  289. return false;
  290. });
  291. }
  292. //filter out time slots that are already fully booked
  293. const reservedSlotsForDate = upcomingReservations.find((res) => res.date === selectedDate);
  294. if (reservedSlotsForDate) {
  295. filteredTimeSlots = filteredTimeSlots.filter((time) => !reservedSlotsForDate.times.includes(time));
  296. }
  297. setAvailableTimeSlots(filteredTimeSlots);
  298. } catch (error) {
  299. console.error('Error fetching time slots:', error);
  300. } finally {
  301. setIsLoading(false);
  302. }
  303. };
  304. if (selectedDate) {
  305. fetchingAvailableTimeSlots();
  306. }
  307. }, [selectedDate]);
  308. useEffect(() => {
  309. const fetchConnectorOptions = async () => {
  310. try {
  311. const fetchedData = await chargeStationService.fetchSpecificChargeStation(chargeStationID);
  312. console.log('fetchedDate', fetchedData);
  313. const dateObject = fetchedData.find((item) => item.date === selectedDate);
  314. console.log('dateObject', dateObject);
  315. if (!dateObject) {
  316. setAvailableConnectorDropdownOptions([]);
  317. return;
  318. }
  319. const rangeObject = dateObject.range.find((range) => range.start === selectedTime);
  320. console.log('rangeObject', rangeObject);
  321. if (!rangeObject) {
  322. setAvailableConnectorDropdownOptions([]);
  323. return;
  324. }
  325. const connectorIDs = rangeObject.connectors
  326. .filter((connector) => connector.Status === '待机')
  327. .map((connector) => connector.ConnectorID);
  328. console.log('connectorIDs', connectorIDs);
  329. setAvailableConnectorDropdownOptions(connectorIDs);
  330. } catch (error) {
  331. console.error('Error fetching charge station data:', error);
  332. setAvailableConnectorDropdownOptions([]);
  333. }
  334. };
  335. fetchConnectorOptions();
  336. }, [chargeStationID, selectedDate, selectedTime]);
  337. // old
  338. // const formattedConnectorDropdownOptions = availableConnectorDropdownOptions.map((id, index) => ({
  339. // label: (index + 1).toString(),
  340. // value: id
  341. // }));
  342. const connectorIDToLabelMap = {
  343. '101708240502475001': '1',
  344. '101708240502476001': '2',
  345. '101708240502477001': '3',
  346. '101708240502478001': '4',
  347. '101708240502474001': '5',
  348. '101708240502474002': '6'
  349. };
  350. console.log('availableConnectorDropdownOptions', availableConnectorDropdownOptions);
  351. const formattedConnectorDropdownOptions = availableConnectorDropdownOptions
  352. .map((id) => ({
  353. label: connectorIDToLabelMap[id] || '',
  354. value: id
  355. }))
  356. .filter((option) => option.label !== '')
  357. .sort((a, b) => parseInt(a.label) - parseInt(b.label));
  358. console.log('formattedConnectorDropdownOptions', formattedConnectorDropdownOptions);
  359. useEffect(() => {
  360. const fetchingAvailableDates = async () => {
  361. setIsDateLoading(true);
  362. try {
  363. const fetchedDates = await chargeStationService.fetchAvailableDates(chargeStationID);
  364. console.log('fetchedDates', fetchedDates);
  365. setAvailableDate(fetchedDates);
  366. console.log(fetchedDates.slice(0, 3));
  367. } catch (error) {
  368. console.error('Error fetching available dates:', error);
  369. } finally {
  370. setIsDateLoading(false);
  371. }
  372. };
  373. fetchingAvailableDates();
  374. }, [chargeStationID]);
  375. const handleNavigationPress = () => {
  376. const latitude = chargeStationLat;
  377. const longitude = chargeStationLng;
  378. // console.log('latitude', latitude);
  379. // console.log('longitude', longitude);
  380. const label = encodeURIComponent(chargeStationName);
  381. // Google Maps App URL
  382. const googleMapsUrl = `https://www.google.com/maps/search/?api=1&query=${latitude},${longitude}`;
  383. // Fallback URL for web browser
  384. const webUrl = `https://www.google.com/maps/dir/?api=1&destination=${latitude},${longitude}`;
  385. Linking.canOpenURL(googleMapsUrl)
  386. .then((supported) => {
  387. if (supported) {
  388. Linking.openURL(googleMapsUrl);
  389. } else {
  390. Linking.openURL(webUrl).catch((err) => {
  391. console.error('An error occurred', err);
  392. Alert.alert(
  393. 'Error',
  394. "Unable to open Google Maps. Please make sure it's installed on your device.",
  395. [{ text: 'OK' }],
  396. { cancelable: false }
  397. );
  398. });
  399. }
  400. })
  401. .catch((err) => console.error('An error occurred', err));
  402. };
  403. const handleConfirmation = (value: any) => {
  404. setModalVisible(true);
  405. const selectedOption = formattedConnectorDropdownOptions.find((option) => option.value === value);
  406. const label = selectedOption ? selectedOption.label : '';
  407. setRouterParams({
  408. pathname: '/bookingConfirmationPage',
  409. params: {
  410. chargeStationName,
  411. chargeStationAddress,
  412. chargeStationID,
  413. connectorID: value,
  414. connectorLabel: label,
  415. userID,
  416. carCapacitance: carCapacitance,
  417. carID: selectedCarID,
  418. carName: selectedCar,
  419. date: selectedDate,
  420. bookTime: selectedTime,
  421. chargingMethod: stopChargingUponBatteryFull ? 'stopChargingUponBatteryFull' : 'chargingBasedOnWatt',
  422. chargingWatt: selectedWatt || '',
  423. price: price
  424. }
  425. });
  426. };
  427. const handleModalConfirm = () => {
  428. // Alert.alert('提示', '此功能正在準備中,敬請期待', [{ text: '確定', onPress: () => router.push('/mainPage') }], {
  429. // cancelable: false
  430. // });
  431. setModalVisible(false);
  432. if (routerParams) {
  433. router.push(routerParams);
  434. }
  435. };
  436. return (
  437. <SafeAreaView
  438. style={{
  439. flex: 1,
  440. backgroundColor: 'white'
  441. }}
  442. edges={['right', 'top', 'left']}
  443. >
  444. <ScrollView className="flex-1 bg-white" showsVerticalScrollIndicator={false}>
  445. <View className="pb-4 ">
  446. <View className="ml-[5%] pt-8">
  447. <Pressable
  448. style={{ alignSelf: 'flex-start' }}
  449. onPress={() => {
  450. if (router.canGoBack()) {
  451. router.back();
  452. } else {
  453. router.replace('./');
  454. }
  455. }}
  456. >
  457. <PreviousPageBlackSvg />
  458. </Pressable>
  459. <Text className="text-3xl mt-8">{chargeStationName}</Text>
  460. <View className="flex-column">
  461. <View className="flex-row justify-between items-center mr-[5%]">
  462. <Text className="text-base" style={styles.grayColor}>
  463. {chargeStationAddress}
  464. </Text>
  465. <NormalButton
  466. title={
  467. <View className="flex-row items-center justify-center text-center space-x-1">
  468. <DirectionLogoSvg />
  469. <Text className="text-base">路線</Text>
  470. </View>
  471. }
  472. // onPress={() => console.log('路線')}
  473. onPress={handleNavigationPress}
  474. extendedStyle={{
  475. backgroundColor: '#E3F2F8',
  476. borderRadius: 61,
  477. paddingHorizontal: 20,
  478. paddingVertical: 8
  479. }}
  480. />
  481. </View>
  482. <View className="flex-row space-x-2 items-center">
  483. <CheckMarkLogoSvg />
  484. <Text>Walk-In</Text>
  485. {/* <Text>{distance}</Text> */}
  486. </View>
  487. </View>
  488. </View>
  489. </View>
  490. <View>
  491. {/* {selectedCar !== '' ? (
  492. <>
  493. <Pressable
  494. onPress={() => {
  495. setSelectedCar('');
  496. setSelectedWatt('');
  497. setOpenDrawer(0);
  498. setSelectedDrawer(0);
  499. setSelectedDuration('');
  500. setChargingBasedOnWatt(false);
  501. setStopChargingUponBatteryFull(false);
  502. setSelectedDate('');
  503. setSelectedTime('');
  504. }}
  505. >
  506. <View className="mx-[5%]">
  507. <View className="flex-row items-center pt-4">
  508. <Text className="text-lg pr-2 text-[#34667c]">選擇充電車輛</Text>
  509. <CheckMarkLogoSvg />
  510. </View>
  511. <Text className="text-lg pb-4">{selectedCar}</Text>
  512. </View>
  513. </Pressable>
  514. </>
  515. ) : (
  516. <AccordionItem
  517. title="選擇充電車輛"
  518. isOpen={openDrawer === 0}
  519. onToggle={() => toggleDrawer(0)}
  520. isSelected={selectedDrawer === 0}
  521. >
  522. {carLoadingState ? (
  523. <View>
  524. <ActivityIndicator color="#34657b" />
  525. </View>
  526. ) : (
  527. <ScrollView
  528. horizontal={true}
  529. contentContainerStyle={{
  530. alignItems: 'center',
  531. flexDirection: 'row',
  532. marginVertical: 8
  533. }}
  534. className="space-x-2 "
  535. >
  536. {car
  537. .sort((a, b) => (b.isDefault ? 1 : 0) - (a.isDefault ? 1 : 0))
  538. .map((car, index) => (
  539. <ChooseCarForChargingRow
  540. onPress={() => {
  541. setSelectedCar(car.car_name);
  542. setSelectedCarID(car.car_id);
  543. setCarCapacitance(car.car_capacitance);
  544. setSelectedDrawer(1);
  545. setOpenDrawer(1);
  546. }}
  547. image={car.processedImageUrl}
  548. key={`${car.car_name}+${index}`}
  549. VehicleName={car.car_name}
  550. isDefault={car.isDefault}
  551. />
  552. ))}
  553. </ScrollView>
  554. )}
  555. </AccordionItem>
  556. )} */}
  557. {stopChargingUponBatteryFull === true || selectedWatt !== '' ? (
  558. <Pressable
  559. onPress={() => {
  560. setSelectedDuration('');
  561. setChargingBasedOnWatt(false);
  562. setStopChargingUponBatteryFull(false);
  563. setSelectedTime('');
  564. setSelectedDate('');
  565. setSelectedWatt('');
  566. setOpenDrawer(1);
  567. setSelectedDrawer(1);
  568. }}
  569. >
  570. <View className="mx-[5%] ">
  571. <View className="flex-row items-center pt-4">
  572. <Text className="text-lg pr-2 text-[#34667c]">選擇充電方案</Text>
  573. <CheckMarkLogoSvg />
  574. </View>
  575. <Text className="text-lg pb-4">
  576. {selectedWatt !== '' ? `按每道電 - ${selectedWatt.split('~')[0]}` : '充滿停機'}
  577. </Text>
  578. </View>
  579. </Pressable>
  580. ) : (
  581. <AccordionItem
  582. title="選擇充電方案"
  583. isOpen={openDrawer === 1}
  584. onToggle={() => {}}
  585. isSelected={selectedDrawer === 1}
  586. >
  587. <View className="flex-row justify-between mt-2 mb-3">
  588. <Pressable
  589. className={`border rounded-lg border-[#34667c] w-[47%] items-center bg-white ${
  590. chargingBasedOnWatt ? 'bg-[#34667c] ' : ''
  591. }`}
  592. onPress={() => {
  593. setChargingBasedOnWatt(!chargingBasedOnWatt);
  594. setStopChargingUponBatteryFull(false);
  595. }}
  596. >
  597. <Text
  598. className={`text-base p-2 text-[#34667c] ${
  599. chargingBasedOnWatt ? ' text-white' : 'text-[#34667c]'
  600. }`}
  601. >
  602. 按每度電
  603. </Text>
  604. </Pressable>
  605. {/* <Pressable
  606. onPress={() => {
  607. setStopChargingUponBatteryFull(!stopChargingUponBatteryFull);
  608. setChargingBasedOnWatt(false);
  609. setSelectedDrawer(2);
  610. setOpenDrawer(2);
  611. }}
  612. className={`border rounded-lg border-[#34667c] w-[47%] items-center bg-white ${
  613. stopChargingUponBatteryFull ? ' bg-[#34667c]' : ''
  614. }`}
  615. >
  616. <Text
  617. className={`text-base p-2 text-[#34667c] ${
  618. stopChargingUponBatteryFull ? ' text-white' : 'text-[#34667c]'
  619. }`}
  620. >
  621. 充滿停機
  622. </Text>
  623. </Pressable> */}
  624. </View>
  625. {chargingBasedOnWatt === true && (
  626. <View className="flex-row w-full justify-between mb-3">
  627. {['20 kWh~25mins', '25 kWh~30mins', '30 kWh~40mins', '40 kWh~45mins'].map(
  628. (watt) => (
  629. <Pressable
  630. key={watt}
  631. className={`${
  632. selectedWatt === watt ? 'bg-[#34667c] ' : 'bg-white'
  633. } border border-[#34667c] rounded-lg w-[22%] items-center`}
  634. onPress={() => {
  635. setSelectedWatt(watt);
  636. setOpenDrawer(2);
  637. setSelectedDrawer(2);
  638. }}
  639. >
  640. <Text
  641. className={`text-base pt-2 pl-2 pr-2 ${
  642. selectedWatt === watt ? 'text-white' : 'text-[#34667c]'
  643. } `}
  644. >
  645. {watt.split('~')[0]}
  646. </Text>
  647. <Text className="text-xs pt-0 pb-1 text-[#666666]">
  648. {watt.split('~')[1]}
  649. </Text>
  650. </Pressable>
  651. )
  652. )}
  653. </View>
  654. )}
  655. </AccordionItem>
  656. )}
  657. {selectedTime !== '' ? (
  658. <Pressable
  659. onPress={() => {
  660. setOpenDrawer(2);
  661. setSelectedDrawer(2);
  662. setSelectedDate('');
  663. setSelectedTime('');
  664. }}
  665. >
  666. <View className="mx-[5%] ">
  667. <View className="flex-row items-center pt-4">
  668. <Text className="text-lg pr-2 text-[#34667c]">選擇日期</Text>
  669. <CheckMarkLogoSvg />
  670. </View>
  671. <Text className="text-lg pb-4">
  672. {selectedDate} - {selectedTime}
  673. </Text>
  674. </View>
  675. </Pressable>
  676. ) : (
  677. <AccordionItem
  678. title="選擇日期 (月/日)"
  679. isOpen={openDrawer === 2}
  680. onToggle={() => {
  681. if (stopChargingUponBatteryFull !== false || selectedDuration !== '') {
  682. toggleDrawer(2);
  683. }
  684. }}
  685. isSelected={selectedDrawer === 2}
  686. >
  687. {isDateLoading ? (
  688. <View className="flex-1 items-center justify-center py-4">
  689. <ActivityIndicator size="large" color="#34667c" />
  690. </View>
  691. ) : (
  692. <View className="flex-row w-full flex-wrap mb-1 ">
  693. {availableDate.slice(0, 3).map((date) => (
  694. <Pressable
  695. key={date}
  696. className={`${
  697. selectedDate === date ? 'bg-[#34667c] ' : 'bg-white'
  698. } border border-[#34667c] rounded-lg w-[22%] items-center mt-1 mr-1 mb-1`}
  699. onPress={() => {
  700. setSelectedDate(date);
  701. }}
  702. >
  703. <Text
  704. className={`text-base p-2 ${
  705. selectedDate === date ? 'text-white' : 'text-[#34667c]'
  706. } `}
  707. >
  708. {date}
  709. </Text>
  710. </Pressable>
  711. ))}
  712. </View>
  713. )}
  714. {selectedDate !== '' && (
  715. <>
  716. <Text className="text-lg pr-2 ">選擇時間</Text>
  717. {isLoading ? (
  718. <View className="flex-1 mb-2">
  719. <ActivityIndicator />
  720. </View>
  721. ) : (
  722. <View className="flex-row w-full mb-3 flex-wrap my-2 ">
  723. {availableTimeSlots.map((time) => (
  724. <Pressable
  725. key={time}
  726. className={`${
  727. selectedTime === time ? 'bg-[#34667c] ' : 'bg-white'
  728. } border border-[#34667c] mr-2 rounded-lg w-[22%] items-center mb-2`}
  729. onPress={() => {
  730. setSelectedTime(time);
  731. setOpenDrawer(3);
  732. setSelectedDrawer(3);
  733. }}
  734. >
  735. <Text
  736. className={`text-base p-2 ${
  737. selectedTime === time ? 'text-white' : 'text-[#34667c]'
  738. } `}
  739. >
  740. {time}
  741. </Text>
  742. </Pressable>
  743. ))}
  744. </View>
  745. )}
  746. </>
  747. )}
  748. </AccordionItem>
  749. )}
  750. <View className="">
  751. <AccordionItem
  752. title="選擇充電座"
  753. isOpen={openDrawer === 3}
  754. onToggle={() => {
  755. if (selectedTime) {
  756. // toggleDrawer(3);
  757. }
  758. }}
  759. isSelected={selectedDrawer === 3}
  760. >
  761. <View className="">
  762. <DropdownSelect
  763. dropdownOptions={formattedConnectorDropdownOptions}
  764. placeholder={'選擇充電座號碼'}
  765. onSelect={(value) => {
  766. setSelectedChargingGun(value);
  767. handleConfirmation(value);
  768. }}
  769. extendedStyle={{
  770. borderColor: '#34667c',
  771. marginTop: 4,
  772. padding: 12
  773. }}
  774. />
  775. <Image
  776. style={{
  777. width: layoutWidth * 0.9,
  778. height: layoutHeight
  779. }}
  780. resizeMode="contain"
  781. source={require('../../assets/floorPlan1.png')}
  782. />
  783. <Modal
  784. isVisible={isModalVisible}
  785. // onBackdropPress={() => setModalVisible(false)}
  786. backdropOpacity={0.5}
  787. animationIn="fadeIn"
  788. animationOut="fadeOut"
  789. >
  790. <View style={styles.modalContent}>
  791. <Text style={styles.modalText}>
  792. 若客戶逾時超過15分鐘,系統將視作自動放棄預約,客戶需要重新預約一次。
  793. 本公司有權保留全數費用,恕不退還。按下確認代表您已閱讀並同意上述條款。
  794. </Text>
  795. <NormalButton
  796. title={<Text className="text-white">我確認</Text>}
  797. onPress={handleModalConfirm}
  798. extendedStyle={styles.confirmButton}
  799. />
  800. </View>
  801. </Modal>
  802. </View>
  803. </AccordionItem>
  804. </View>
  805. </View>
  806. {/* {routerParams ? (
  807. <View className="mx-[5%] my-4">
  808. <NormalButton
  809. title={
  810. <Text
  811. style={{
  812. fontWeight: '700',
  813. fontSize: 20,
  814. color: '#fff'
  815. }}
  816. >
  817. 新增
  818. </Text>
  819. }
  820. onPress={() => handleConfirmation(selectedChargingGun)}
  821. />
  822. </View>
  823. ) : (
  824. ''
  825. )} */}
  826. <View className="mx-[5%] flex-1">
  827. <Text className="text-xl pb-2 mt-6" style={styles.text}>
  828. 充電站資訊
  829. </Text>
  830. <View className="h-[250px]">
  831. <ChargingStationTabView titles={['預約充電事項', '其他']} />
  832. </View>
  833. </View>
  834. </ScrollView>
  835. </SafeAreaView>
  836. );
  837. };
  838. export default MakingBookingPageComponent;
  839. const styles = StyleSheet.create({
  840. grayColor: {
  841. color: '#888888'
  842. },
  843. topLeftTriangle: {
  844. width: 0,
  845. height: 0,
  846. borderLeftWidth: 50,
  847. borderBottomWidth: 50,
  848. borderLeftColor: '#02677D',
  849. borderBottomColor: 'transparent',
  850. position: 'absolute',
  851. top: 0,
  852. left: 0
  853. },
  854. modalContent: {
  855. backgroundColor: 'white',
  856. padding: 22,
  857. justifyContent: 'center',
  858. alignItems: 'center',
  859. borderRadius: 4,
  860. borderColor: 'rgba(0, 0, 0, 0.1)'
  861. },
  862. modalText: {
  863. fontSize: 18,
  864. marginBottom: 12,
  865. textAlign: 'center'
  866. },
  867. confirmButton: {
  868. backgroundColor: '#34667c',
  869. paddingHorizontal: 30,
  870. paddingVertical: 10,
  871. borderRadius: 5
  872. },
  873. text: {
  874. fontWeight: 300,
  875. color: '#000000'
  876. }
  877. });