homePage.tsx 22 KB

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