homePage.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. import {
  2. View,
  3. Text,
  4. ScrollView,
  5. FlatList,
  6. Pressable,
  7. ActivityIndicator,
  8. Image,
  9. Modal,
  10. Alert,
  11. TextInput
  12. } from 'react-native';
  13. import NormalButton from '../global/normal_button';
  14. import { SafeAreaView } from 'react-native-safe-area-context';
  15. import { router, useFocusEffect } from 'expo-router';
  16. import { useColorScheme } from 'nativewind';
  17. import RecentlyBookedScrollView from '../global/recentlyBookedScrollView';
  18. import {
  19. BellIconSvg,
  20. HomeIconSvg,
  21. MyBookingIconSvg,
  22. WhatsAppSvg,
  23. WalletSvg,
  24. MyWalletSvg,
  25. QrCodeIconSvg,
  26. VipCodeIconSvg
  27. } from '../global/SVG';
  28. import { AuthContext } from '../../context/AuthProvider';
  29. import { useCallback, useContext, useEffect, useState } from 'react';
  30. import { authenticationService } from '../../service/authService';
  31. import { chargeStationService } from '../../service/chargeStationService';
  32. import useUserInfoStore from '../../providers/userinfo_store';
  33. import NormalInput from '../global/normal_input';
  34. import { notificationStorage } from '../notificationStorage';
  35. import { handleGoWhatsApp } from '../../util/index';
  36. import { useChargingStore } from '../../providers/scan_qr_payload_store';
  37. interface HomePageProps {}
  38. const HomePage: React.FC<HomePageProps> = () => {
  39. const {
  40. promotion_code,
  41. stationID,
  42. sum_of_coupon,
  43. scanned_qr_code,
  44. coupon_detail,
  45. total_power,
  46. processed_coupon_store,
  47. setPromotionCode,
  48. setCouponDetail,
  49. setTotalPower,
  50. setProcessedCouponStore,
  51. setSumOfCoupon,
  52. setCurrentPriceStore
  53. } = useChargingStore();
  54. const now = new Date();
  55. const { user } = useContext(AuthContext);
  56. const { userID, currentPrice, setUserID, setCurrentPrice, setNotifySessionID } = useUserInfoStore();
  57. const { colorScheme, toggleColorScheme } = useColorScheme();
  58. const [showLicencePlateMessage, setShowLicencePlateMessage] = useState<boolean>(false);
  59. const [licensePlate, setLicensePlate] = useState<string>('');
  60. const [showConfirmationModal, setShowConfirmationModal] = useState<boolean>(false);
  61. const [showOnboarding, setShowOnboarding] = useState(true);
  62. const [mainPromotion, setMainPromotion] = useState([]);
  63. const [mainPromotionImage, setMainPromotionImage] = useState('');
  64. const [reservationAfter2025, setReservationAfter2025] = useState([]);
  65. const [isLoadingReservations, setIsLoadingReservations] = useState(true);
  66. const [unreadCount, setUnreadCount] = useState(0);
  67. useEffect(() => {
  68. const fetchIDandCheckLicensePlate = async () => {
  69. try {
  70. const response = await authenticationService.getUserInfo();
  71. //if success, set user ID,
  72. if (response) {
  73. setNotifySessionID(response.data.notify_session_id);
  74. setUserID(response.data.id);
  75. //after setting id, also check if the user has a valid license plate, if not, show message
  76. if (!response.data.cars || !Array.isArray(response.data.cars)) {
  77. Alert.alert('無法檢測車輛資訊', '請稍後再試');
  78. setShowLicencePlateMessage(false);
  79. }
  80. if (response.data.cars.length === 1 && response.data.cars[0].license_plate === '0000') {
  81. setShowLicencePlateMessage(true);
  82. }
  83. } else {
  84. Alert.alert('fail to set user/notification session ID');
  85. }
  86. } catch (error) {
  87. console.log(error);
  88. }
  89. };
  90. const fetchCurrentPrice = async () => {
  91. try {
  92. const response = await chargeStationService.getCurrentPrice();
  93. if (response) {
  94. setCurrentPrice(response);
  95. }
  96. } catch (error) {
  97. console.log('main page fetch current price error', error);
  98. }
  99. };
  100. const fetchMainPromotion = async () => {
  101. try {
  102. const response = await chargeStationService.getAdvertise();
  103. if (response) {
  104. const mainPromo = response.filter((item: any) => item.is_main)[0];
  105. setMainPromotion(mainPromo);
  106. if (mainPromo) {
  107. const mainPromoImage = await chargeStationService.getProcessedImageUrl(mainPromo.image_url);
  108. if (mainPromoImage) {
  109. setMainPromotionImage(mainPromoImage);
  110. }
  111. }
  112. }
  113. } catch (error) {
  114. console.log('Error fetching promotion:', error);
  115. }
  116. };
  117. fetchMainPromotion();
  118. const fetchWithAllSettled = async () => {
  119. const results = await Promise.allSettled([
  120. fetchIDandCheckLicensePlate(),
  121. fetchCurrentPrice(),
  122. fetchMainPromotion()
  123. ]);
  124. };
  125. fetchWithAllSettled();
  126. }, []);
  127. const cleanupData = () => {
  128. setPromotionCode([]);
  129. setCouponDetail([]);
  130. setProcessedCouponStore([]);
  131. setSumOfCoupon(0);
  132. setTotalPower(null);
  133. };
  134. useFocusEffect(
  135. useCallback(() => {
  136. let isActive = true;
  137. const fetchData = async () => {
  138. setIsLoadingReservations(true); // Start loading
  139. try {
  140. const results = await Promise.allSettled([
  141. chargeStationService.fetchReservationHistories(),
  142. chargeStationService.getAdvertise()
  143. ]);
  144. if (!isActive) return;
  145. // Handle reservation data
  146. if (results[0].status === 'fulfilled') {
  147. const year2025 = new Date('2025-02-01T00:00:00.000Z');
  148. const reservationAfter2025 = results[0].value.filter((r: any) => {
  149. const date = new Date(r.createdAt);
  150. return date > year2025;
  151. });
  152. setReservationAfter2025(reservationAfter2025);
  153. } else if (results[0].status === 'rejected') {
  154. Alert.alert('Error fetching reservations:', results[0].reason);
  155. }
  156. // Get viewed notifications
  157. const viewedNotifications = await notificationStorage.getViewedNotifications();
  158. let totalUnread = 0;
  159. // Count unread reservations
  160. if (results[0].status === 'fulfilled') {
  161. const unreadReservations = reservationAfter2025.filter((r: any) => {
  162. return !viewedNotifications.some((vn: any) => vn.id === r.id);
  163. });
  164. totalUnread += unreadReservations.length;
  165. }
  166. // Count unread promotions
  167. if (results[1].status === 'fulfilled') {
  168. const unreadPromotions = results[1].value.filter((p: any) => {
  169. return !viewedNotifications.some((vn) => vn.id === p.id);
  170. });
  171. totalUnread += unreadPromotions.length;
  172. }
  173. setUnreadCount(totalUnread);
  174. if (results[0].status === 'fulfilled') {
  175. const reservationHistories = results[0].value;
  176. if (reservationHistories || Array.isArray(reservationHistories)) {
  177. const unpaidPenalties = reservationHistories.filter(
  178. (reservation: any) => reservation.penalty_fee > 0 && reservation.penalty_paid_status === false
  179. );
  180. const mostRecentUnpaidReservation = unpaidPenalties.reduce((mostRecent: any, current: any) => {
  181. return new Date(mostRecent.created_at) > new Date(current.created_at) ? mostRecent : current;
  182. }, unpaidPenalties[0]);
  183. if (unpaidPenalties.length > 0) {
  184. Alert.alert(
  185. '未付罰款',
  186. '您有未支付的罰款。請先支付罰款後再重新掃描充電。',
  187. [
  188. {
  189. text: '查看詳情',
  190. onPress: () => {
  191. // Navigate to a page showing penalty details
  192. cleanupData();
  193. router.push({
  194. pathname: '(auth)/(tabs)/(home)/penaltyPaymentPage',
  195. params: {
  196. book_time: mostRecentUnpaidReservation.book_time,
  197. end_time: mostRecentUnpaidReservation.end_time,
  198. actual_end_time: mostRecentUnpaidReservation.actual_end_time,
  199. penalty_fee: mostRecentUnpaidReservation.penalty_fee,
  200. format_order_id: mostRecentUnpaidReservation.format_order_id,
  201. id: mostRecentUnpaidReservation.id
  202. }
  203. });
  204. }
  205. },
  206. {
  207. text: '關閉',
  208. onPress: () => {
  209. cleanupData();
  210. }
  211. }
  212. ],
  213. { cancelable: false }
  214. );
  215. return;
  216. }
  217. }
  218. }
  219. } catch (error) {
  220. if (!isActive) return;
  221. console.log('Error fetching data');
  222. } finally {
  223. if (isActive) {
  224. setIsLoadingReservations(false);
  225. }
  226. }
  227. };
  228. fetchData();
  229. return () => {
  230. isActive = false;
  231. };
  232. }, [])
  233. );
  234. const saveLicensePlate = async (licensePlate: string) => {
  235. try {
  236. const response = await chargeStationService.addCar(
  237. licensePlate,
  238. '1834d087-bfc1-4f90-8f09-805e3d9422b5',
  239. 'f599470d-53a5-4026-99c0-2dab34c77f39',
  240. true
  241. );
  242. if (response === true) {
  243. console.log('License plate saved successfully');
  244. } else {
  245. Alert.alert('無法保存車牌號碼', '請稍後再試');
  246. }
  247. } catch (error) {
  248. Alert.alert('暫時無法保存車牌號碼', '請稍後再試');
  249. }
  250. };
  251. return (
  252. <SafeAreaView edges={['top', 'left', 'right']} className="flex-1 bg-white">
  253. {/* Add Modal component */}
  254. {mainPromotionImage && (
  255. <Modal
  256. animationType="fade"
  257. transparent={true}
  258. visible={showOnboarding}
  259. onRequestClose={() => { setShowOnboarding(false)}}
  260. >
  261. <Pressable
  262. className="flex-1 bg-black/50 items-center justify-center"
  263. onPress={() => setShowOnboarding(false)}
  264. >
  265. <View className="w-[98%] rounded-2xl ">
  266. <Image
  267. source={{ uri: mainPromotionImage }}
  268. className="w-full aspect-square "
  269. resizeMode="contain"
  270. />
  271. <Text className="text-center mt-4 mb-2 text-gray-200">點擊任意位置關閉</Text>
  272. </View>
  273. </Pressable>
  274. </Modal>
  275. )}
  276. {showLicencePlateMessage && (
  277. <Modal
  278. animationType="fade"
  279. transparent={true}
  280. visible={showLicencePlateMessage}
  281. onRequestClose={() => setShowLicencePlateMessage(false)}
  282. >
  283. <View className="flex-1 bg-black/50 items-center justify-center">
  284. {!showConfirmationModal ? (
  285. // License Plate Input Modal
  286. <View className="flex flex-col rounded-2xl bg-white overflow-hidden w-[80%]">
  287. <View className="bg-[#E3F2F8]">
  288. <Text className="text-base lg:text-lg font-[500] text-center p-4">
  289. 請添加您的車牌號碼
  290. </Text>
  291. </View>
  292. <View className="p-4 ">
  293. <Text className="text-sm lg:text-base font-[500] text-left mb-4">
  294. 為更好地為您提供服務,請在您的帳戶中添加車牌號碼。
  295. </Text>
  296. <NormalInput
  297. value={licensePlate}
  298. placeholder="車牌號碼"
  299. onChangeText={(s) => setLicensePlate(s)}
  300. extendedStyle={{ borderRadius: 12, marginBottom: 0 }}
  301. textContentType="none"
  302. autoComplete="off"
  303. keyboardType="default"
  304. />
  305. </View>
  306. <View className="pr-4 pl-4 pb-4 ">
  307. <NormalButton
  308. title={<Text className="text-white text-sm lg:text-lg">確定</Text>}
  309. onPress={() => {
  310. //here when users click confirm, i want to pop another modal that say you have entered "xxxxxx", click confirm to continue
  311. if (!licensePlate.trim()) {
  312. Alert.alert('請輸入車牌號碼');
  313. return;
  314. }
  315. if (licensePlate.trim().length < 4 || licensePlate.trim().length > 10) {
  316. Alert.alert('無效的車牌號碼', '請輸入有效的車牌號碼');
  317. return;
  318. }
  319. setShowConfirmationModal(true);
  320. }}
  321. />
  322. </View>
  323. </View>
  324. ) : (
  325. // Confirmation Modal
  326. <View className="flex flex-col rounded-2xl bg-white overflow-hidden w-[80%]">
  327. <View className="bg-[#E3F2F8]">
  328. <Text className="text-base lg:text-lg font-[500] text-center p-4">
  329. 確認車牌號碼
  330. </Text>
  331. </View>
  332. <View className="p-4">
  333. <Text className="text-sm lg:text-base font-[500] text-center mb-4">
  334. 您輸入的車牌號碼為:{licensePlate}
  335. </Text>
  336. </View>
  337. <View className="flex-row p-4 space-x-4">
  338. <View className="flex-1">
  339. <NormalButton
  340. title={<Text className="text-white text-sm lg:text-lg">取消</Text>}
  341. onPress={() => setShowConfirmationModal(false)}
  342. />
  343. </View>
  344. <View className="flex-1">
  345. <NormalButton
  346. title={<Text className="text-white text-sm lg:text-lg">確認</Text>}
  347. onPress={() => {
  348. saveLicensePlate(licensePlate);
  349. setShowConfirmationModal(false);
  350. setShowLicencePlateMessage(false);
  351. setLicensePlate('');
  352. }}
  353. />
  354. </View>
  355. </View>
  356. </View>
  357. )}
  358. </View>
  359. </Modal>
  360. )}
  361. <ScrollView showsVerticalScrollIndicator={false} className="flex-1 mx-[5%] ">
  362. <View className=" flex-1 pt-8 ">
  363. <View className="flex-row items-center pb-4">
  364. <HomeIconSvg />
  365. <View className="pl-2 flex-1 flex-column ">
  366. <View className="flex-row justify-between mr-[10%]">
  367. <Text className="text-lg text-left pb-1">您好!</Text>
  368. <View className="relative z-5">
  369. <Pressable
  370. onPress={() => router.push({ pathname: 'notificationPage' })}
  371. disabled={isLoadingReservations}
  372. className="z-10 w-10 items-center justify-center"
  373. hitSlop={{ top: 20, bottom: 20, left: 20, right: 20 }}
  374. >
  375. <View className="w-6 h-6">
  376. <BellIconSvg />
  377. </View>
  378. {unreadCount > 0 && (
  379. <View className="absolute -top-2 -right-[0.5] bg-red-500 rounded-full w-5 h-5 items-center justify-center">
  380. <Text className="text-white text-xs font-bold">{unreadCount}</Text>
  381. </View>
  382. )}
  383. </Pressable>
  384. <Pressable className="z-10 top-9 right-0" onPress={() => handleGoWhatsApp()}>
  385. <View className="w-8 h-8">
  386. <WhatsAppSvg />
  387. </View>
  388. </Pressable>
  389. </View>
  390. </View>
  391. <Text className="text-4xl font-light ">{user?.nickname}</Text>
  392. </View>
  393. </View>
  394. <View className=" flex-1 justify-center ">
  395. {/* <Pressable onPress={() => router.push('searchPage')}>
  396. <View
  397. style={{
  398. borderWidth: 1,
  399. padding: 24,
  400. borderRadius: 12,
  401. borderColor: '#bbbbbb',
  402. maxWidth: '100%'
  403. }}
  404. >
  405. <Text style={{ color: '#888888', fontSize: 16 }}>搜尋充電站或地區..</Text>
  406. </View>
  407. </Pressable> */}
  408. </View>
  409. </View>
  410. <View className="flex-1">
  411. <View className="my-4">
  412. <NormalButton
  413. onPress={() => router.push('scanQrPage')}
  414. // onPress={() => router.push('optionPage')}
  415. title={
  416. <View className="flex flex-row justify-start">
  417. <QrCodeIconSvg />
  418. <Text className="text-white font-bold text-lg ml-2">掃描及充電</Text>
  419. </View>
  420. }
  421. extendedStyle={{
  422. alignItems: 'flex-start',
  423. padding: 24
  424. }}
  425. />
  426. </View>
  427. <View className="flex-1 flex-row justify-between gap-6">
  428. {/* <View className="flex-1">
  429. <NormalButton
  430. // onPress={() => router.push('bookingMenuPage')}
  431. onPress={() => Alert.alert('即將推出', '此功能即將推出,敬請期待!')}
  432. //onPress={() => notificationStorage.clearStorage()}
  433. title={
  434. <View className="flex flex-row space-x-2 items-center ">
  435. <MyBookingIconSvg />
  436. <Text className="text-white font-bold text-lg ml-2">我的預約</Text>
  437. </View>
  438. }
  439. extendedStyle={{
  440. alignItems: 'flex-start',
  441. padding: 24
  442. }}
  443. />
  444. </View> */}
  445. <View className="flex-1">
  446. <NormalButton
  447. onPress={() => router.push('/(account)/(wallet)/walletPage')}
  448. title={
  449. <View className="flex flex-row space-x-2 items-center">
  450. <MyWalletSvg />
  451. <Text className="text-white font-bold text-lg ml-2">錢包</Text>
  452. </View>
  453. }
  454. extendedStyle={{
  455. alignItems: 'flex-start',
  456. padding: 24
  457. }}
  458. />
  459. </View>
  460. </View>
  461. <View className="mt-4">
  462. <NormalButton
  463. // onPress={() => console.log('掃瞄及充電')}
  464. onPress={() => router.push('vipQrPage')}
  465. title={
  466. <View className="flex flex-row items-center space-x-2">
  467. <VipCodeIconSvg />
  468. <Text className="text-white font-bold text-lg ml-2">專屬會員二維碼</Text>
  469. </View>
  470. }
  471. extendedStyle={{
  472. alignItems: 'flex-start',
  473. padding: 24
  474. }}
  475. />
  476. </View>
  477. </View>
  478. </ScrollView>
  479. </SafeAreaView>
  480. );
  481. };
  482. export default HomePage;