homePage.tsx 23 KB

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