homePage.tsx 21 KB

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