/
FoodListView.js
executable file
·766 lines (732 loc) · 21.2 KB
/
FoodListView.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
import React, { Component } from "react";
import {
View,
TouchableOpacity,
StyleSheet,
Image,
Platform,
ActivityIndicator,
BackHandler,
ToastAndroid,
Animated,
Easing,
Alert
} from "react-native";
import { Header } from "native-base";
import { connect } from "react-redux";
import LinearGradient from "react-native-linear-gradient";
import FastImage from "react-native-fast-image";
import Antd from "react-native-vector-icons/AntDesign";
import {PopoverPicker} from 'teaset';
import {isNil} from "lodash";
//actions
import { SHOW_AD, HIDE_AD } from "../actions";
//utils
import GLOBAL_PARAMS, { em, isEmpty, currentPlatform } from "../utils/global_params";
import JSONUtils from "../utils/JSONUtils";
import { getDeviceId, getVersion } from "../utils/DeviceInfo";
//api
import { getFoodList, adSpace, inviteActivityInfo } from "../api/request";
import {abortRequestInPatchWhenRouteChange} from "../api/CancelToken";
//components
import Text from "../components/UnScalingText";
import WarningTips from "../components/WarningTips";
import CommonFlatList from "../components/CommonFlatList";
import AdvertiseView from "../components/AdvertiseView";
import PlacePickerModel from "../components/PlacePickerModel";
import CustomizeContainer from "../components/CustomizeContainer";
import Tips from "../components/Tips";
import Swiper from "../components/Swiper";
import Guider from "../components/Guider";
//styles
import FoodDetailsStyles from "../styles/fooddetails.style";
//storage
import { advertisementStorage } from "../cache/appStorage";
import Divider from "../components/Divider";
//store
import store from "../store/index";
import { SAVE_ACTIVITY } from "../actions/index";
const {
isIphoneX,
bottomDistance,
iPhoneXBottom,
_winHeight,
_winWidth
} = GLOBAL_PARAMS;
const HAS_FOODS = 1;
const NO_MORE_FOODS = 2;
const IS_INTERCEPT = 3;
let lastBackPressed = Date.now();
class FoodListView extends Component {
_interval = null;
_isFirstReload = null;
flatlist = null;
constructor(props) {
super(props);
this._interval = null;
this._isFirstReload = true; //判断是否为首次加载
// Platform.OS == 'android' && BackHandler.addEventListener('hardareBackPress', this.onBackButtonPressAndroid.bind(this));
this.state = {
placeSelected: null, // 当前地址选择
advertiseImg: "", // 广告图
advertiseData: null, //首页广告数据
advertiseCountdown: 5, //广告倒计时
swiperListData: [], //首页轮播图数据
star: null, // 当日评分
isAdvertiseShow: false, //是否展示广告
isActivityBtnShow: false, // 是否展示活动详情的入口按钮
isSwiperShow: false, //是否展示首页的轮播图
searchBarOpacity: new Animated.Value(1), //搜索框滚动列表时逐渐消失动画
searchBtnShow: false, //是否展示搜索框
};
}
componentWillReceiveProps(nextProps) {
if(nextProps.userInfo.username != this.props.userInfo.username) {
this._getActivityInfo();
}
}
shouldComponentUpdate(nextProps, nextState) {
return JSON.stringify(nextState) != JSON.stringify(this.state) || nextProps.userInfo.username != this.props.userInfo.username;
}
componentDidMount() {
let { isAdShow, hideAd } = this.props;
if (isAdShow) {
hideAd();
}
// 获取广告页数据
advertisementStorage.getData((error, data) => {
if (error == null) {
if (data != null) {
isAdShow &&
this.setState({
advertiseImg: data.image,
advertiseData: data,
isAdvertiseShow: true
});
this._advertiseInterval();
}
this._getAdvertise(data);
}
});
let _timer = setTimeout(() => {
this._getActivityInfo();
this._getSwiperAdList();
clearTimeout(_timer);
},300);
}
componentWillUnmount() {
abortRequestInPatchWhenRouteChange();
}
//logic functions
/**
* 安卓返回键
*
* @returns
* @memberof FoodListView
*/
onBackButtonPressAndroid() {
if(lastBackPressed && lastBackPressed + 2000 >= Date.now()) {
BackHandler.exitApp()
}
lastBackPressed = Date.now();
ToastAndroid.show("再按一次退出app", ToastAndroid.SHORT);
return true;
}
/**
* 获取启动页广告
*
* @param {*} old_data
* @memberof FoodListView
*/
_getAdvertise(old_data) {
adSpace()
.then(data => {
if (data.ro.respCode == "0000") {
if (data.data.length == 0) {
// 如果data为空,则不设置缓存为空
advertisementStorage.setData(null);
return;
}
if (old_data != null) {
// 如果缓存不为空
if (JSONUtils.jsonDeepCompare(old_data, data.data[0])) {
return; // 判断缓存是否与服务器数据相等,如果相等则不做操作
} else {
// 如果缓存不等则覆盖本地缓存为服务器数据
advertisementStorage.setData(data.data[0]);
Image.prefetch(data.data[0].image);
}
} else {
// 如果缓存为空,则缓存到本地
advertisementStorage.setData(data.data[0]);
Image.prefetch(data.data[0].image);
}
}
})
.catch(err => {
if (axios.isCancel(thrown)) {
// console.log('Request canceled', thrown.message);
}
});
}
/**
* 获取swiper活动详情列表
* @params type=2 获取swiper
* @memberof FoodListView
*/
_getSwiperAdList() {
adSpace(2).then(data => {
this.setState({
swiperListData: data
})
}).catch(err => {
console.log('err', err)
})
}
/**
* 获取活动详情
*
* @memberof FoodListView
*/
_getActivityInfo(){
inviteActivityInfo().then(data => {
console.log('data :', data);
this.setState({
isActivityBtnShow: data.showStatus == 1
});
store.dispatch({type: SAVE_ACTIVITY, data});
}).catch(err => {
console.log('err',err)
this.setState({
isActivityBtnShow: false
});
});
}
/**
* 广告页倒计时
*
* @memberof FoodListView
*/
_advertiseInterval() {
this._interval = setInterval(() => {
if (this.state.advertiseCountdown > 1) {
this.setState({
advertiseCountdown: this.state.advertiseCountdown - 1
});
} else {
this.setState({
isAdvertiseShow: false
});
clearInterval(this._interval);
}
}, 1000);
}
/**
* 获取当前选择地区回调
*
* @param {*} val
* @returns
* @memberof FoodListView
*/
_getSeletedValue(val) {
if (val == null) {
// this._picker.getPlace();
this.setState({ isError: true, loading: false });
return;
}
if(!!this.state.placeSelected && val.name == this.state.placeSelected.name) {
return;
}
this.setState(
{
placeSelected: val
},
() => {
if (!this._isFirstReload) {
if (!!this.flatlist) {
this.flatlist.getWrappedInstance().outSideRefresh();
};
this._isFirstReload = false;
} else {
this._isFirstReload = false;
}
}
);
}
/**
* 获取列表滚动高度
*
* @param {*} scrollTop
* @memberof FoodListView
*/
_getScrollTop(scrollTop) {
this.setState({
searchBtnShow: scrollTop > em(100)
});
}
//render functions
/**
* 广告页
*
* @returns
* @memberof FoodListView
*/
_renderAdvertisementView() {
return (
<AdvertiseView
modalVisible={this.state.isAdvertiseShow}
seconds={this.state.advertiseCountdown}
image={this.state.advertiseImg}
data={this.state.advertiseData}
countDown={this.state.advertiseCountdown}
closeFunc={() =>
this.setState({
isAdvertiseShow: false
})
}
/>
);
}
/**
* 顶部导航栏
*
* @returns
* @memberof FoodListView
*/
_renderHeaderView() {
let { placeSelected } = this.state;
let { navigate } = this.props.navigation;
let scheme = "";
if (placeSelected != null) {
let {
placeSelected: { lon, lat, name }
} = this.state;
scheme = Platform.select({
android: `geo:${lon},${lat}?q=${name}`,
ios: `http://maps.apple.com/?q=${name}&ll=${lon},${lat}`
});
}
const menuElement = title => (<Text style={{padding: em(5)}}>{title}</Text>)
return (
<Header
style={FoodDetailsStyles.Header}
iosBarStyle="light-content"
androidStatusBarColor="transparent"
>
<LinearGradient
colors={["#FF881D", "#FF312F"]}
start={{ x: 0.0, y: 0.0 }}
end={{ x: 1.0, y: 0.0 }}
style={FoodDetailsStyles.linearGradient}
>
<TouchableOpacity
onPress={() => navigate("DrawerOpen", { callback: this._add })}
style={FoodDetailsStyles.MenuBtn}
>
<Antd name="menu-fold" style={FoodDetailsStyles.MenuImage} />
{/* <Image
source={require("../asset/menu.png")}
style={FoodDetailsStyles.MenuImage}
resizeMode="contain"
/> */}
</TouchableOpacity>
{this.state.searchBtnShow ? <View style={[FoodDetailsStyles.HeaderContent, ]}><Text style={{color: '#fff', fontSize: em(18),fontWeight: 'bold',marginRight: em(-52)}}>精選菜品</Text></View> :
<Animated.View style={[FoodDetailsStyles.HeaderContent,{opacity: this.state.searchBarOpacity}]}>
{placeSelected != null ? this._renderPlacePickerBtn() : (
<ActivityIndicator color="#fff" size="small" />
)}
</Animated.View>}
<View style={{flexDirection: 'row', alignItems:'center'}}>
{this.state.searchBtnShow && <TouchableOpacity style={[FoodDetailsStyles.MenuBtn,{marginRight: -8}]} onPress={() => this.setState({ showPlacePicker: true })}>
<Antd name="enviromento" style={FoodDetailsStyles.moreIcon}/>
</TouchableOpacity>}
<TouchableOpacity
onPress={() =>{
PopoverPicker.show(
{x: _winWidth - 135, y: -50, width:100, height:100},
[menuElement("查看配送點"),menuElement("兌換優惠碼"), menuElement('反饋')],
this.state.modalSelectedIndex,
(item, index) => {
switch(index) {
case 0: {
this.props.navigation.navigate('PickPlace', {
navigate: true
});break;
}
case 1: {
this.props.navigation.navigate('Coupon', {
navigate: true
});break;
}
case 2: {
this.props.navigation.navigate('Feedback', {
navigate: true
});break;
}
}
},
{modal: false}
);
}}
style={FoodDetailsStyles.MenuBtn}
>
{/* <Image
source={require("../asset/location_white.png")}
style={FoodDetailsStyles.locationImage}
resizeMode="contain"
/> */}
<Antd name="appstore-o" style={FoodDetailsStyles.moreIcon}/>
</TouchableOpacity>
</View>
</LinearGradient>
</Header>
);
}
/**
* 导航栏选择地区bar
*
* @returns
* @memberof FoodListView
*/
_renderPlacePickerBtn() {
return (
<TouchableOpacity
activeOpacity={0.8}
style={FoodDetailsStyles.PlacePickerBtn}
onPress={() => this.setState({ showPlacePicker: true })}
>
<View style={FoodDetailsStyles.PlacePickerBtnBgAbsolute} />
<Text style={FoodDetailsStyles.PlacePickerBtnText} numberOfLines={1}>
{this.state.placeSelected.name}
</Text>
{/* <Image
source={require("../asset/arrow_down.png")}
style={FoodDetailsStyles.PlacePickerBtnImage}
resizeMode="contain"
/> */}
<Antd name="search1" style={FoodDetailsStyles.PlacePickerBtnImage}/>
</TouchableOpacity>
);
}
/**
* 弹出地址选择器
*
* @returns
* @memberof FoodListView
*/
_renderPlacePicker() {
let { showPlacePicker } = this.state;
return (
<PlacePickerModel
ref={c => (this._picker = c)}
modalVisible={showPlacePicker}
closeFunc={() => this.setState({ showPlacePicker: false })}
getSeletedValue={val => this._getSeletedValue(val)}
/>
);
}
/**
* 列表item渲染
*
* @param {*} item
* @param {*} index
* @returns
* @memberof FoodListView
*/
_renderFoodListItemView(item, index) {
if (typeof item === "undefined") return;
let _device = getDeviceId().split(",")[0];
return (
<TouchableOpacity style={styles.itemContainer}
onPress={() => {
const {placeSelected} = this.state;
if(placeSelected && typeof placeSelected.hasTips == "undefined") {
this.props.navigation.navigate("Food", {
dateFoodId: item.dateFoodId
});
}else {
Alert.alert(
this.props.i18n.tips,
placeSelected.name,
[
{ text: this.props.i18n.confirm, onPress: () => {
this.setState({
showPlacePicker: true
})
} }
],
{ cancelable: false }
)
}
}} activeOpacity={1}>
<Text style={styles.dateText}>{item.date}</Text>
<View
style={[
styles.articleItemContainer,
{
borderTopRightRadius: 8,
borderTopLeftRadius: 8,
overflow: 'hidden',
}
]}
>
<FastImage
source={{ uri: item.thumbnail }}
borderRadius={8}
style={{
width: '100%',
height: em(200),
alignSelf: "center",
borderRadius: 8,
marginBottom: em(5),
overflow: 'hidden'
}}
resizeMode={FastImage.resizeMode.cover}
/>
<View style={styles.itemLike}>
<Image style={styles.itemLikeImg} source={require('../asset/1.3.7/icon_2.png')} resizeMode="contain"/>
<Text style={styles.itemLikeText}>{item.likeCount || 0}贊</Text>
</View>
<View style={styles.articleItemDetails}>
<View style={[styles.itemName, styles.marginBottom9]}>
<Text style={styles.foodName} numberOfLines={1}>
{item.name}
</Text>
</View>
{
!isNil(item.prePrice) && !isNil(item.dayPrice) ? (
<View style={styles.foodCommonContainer}>
<Text style={[styles.foodCommon]}>是日價: </Text>
<Text style={[styles.foodCommon,{textDecorationLine:'line-through'}]}>
{` HKD${parseInt(item.dayPrice).toFixed(2)}`}
</Text>
</View>
) : null
}
<View style={[styles.foodCommonContainer]}>
<Text style={styles.foodCommon}>{item.prePrice ? `預購價: ` : `是日價: `} </Text>
<Text style={styles.foodCommon}>
HKD{parseInt(item.prePrice ? `${item.prePrice}` : `${item.dayPrice || item.prePrice}`).toFixed(2)}
</Text>
</View>
<View>
<Text numberOfLines={4} style={styles.foodBrief}>成分: {item.component || ""}</Text>
</View>
</View>
</View>
<View style={styles.confirmBtn}>
<Text
style={{
color: "#fff",
alignSelf: 'flex-end',
fontSize: em(20),
marginTop: Platform.OS == "android" ? -3 : 0
}}
>
{
item.status && (item.status == HAS_FOODS ? '立即預訂' : item.status == NO_MORE_FOODS ? '已售罄' : '已截單') || '立即預訂'
}
</Text>
</View>
</TouchableOpacity>
);
}
/**
* 列表控件渲染
*
* @returns
* @memberof FoodListView
*/
_renderFlatListView() {
_bottomDistance = isIphoneX()
? bottomDistance + iPhoneXBottom
: bottomDistance;
const { placeSelected } = this.state;
if (isEmpty(placeSelected)) {
return null;
}
return (
<CommonFlatList
ref={c => (this.flatlist = c)}
requestFunc={getFoodList}
renderItem={(item, index) => this._renderFoodListItemView(item, index)}
renderHeader={() => {return this.state.swiperListData.length > 0 ? <Swiper adDetail={this.state.swiperListData} /> : null}}
extraParams={{ placeId: this.state.placeSelected.id }}
refreshControlTitleColor="#999999"
isIndicatorShow={false}
blankBtnMessage="所選配送點暫未有餐食供應,請選擇其他離你最近的配送點"
errorCallback={() => {
this._getSwiperAdList();
this._getActivityInfo();
}}
getRawData={data => {
this.setState({ star: data.star});
}}
getScrollTop={
scrollTop => this._getScrollTop(scrollTop)
}
/>
);
}
/**
* 主render函数
*
* @returns
* @memberof FoodListView
*/
render() {
const {
activityInfo
} = this.props;
return (
<CustomizeContainer.SafeView mode="linear" style={{ position: "relative", backgroundColor: "#fff" }}>
<Guider pageName="foodList"/>
{this._renderAdvertisementView()}
{this._renderPlacePicker()}
{this._renderHeaderView()}
{
(this.state.isActivityBtnShow) && (<Tips message="邀請好友,領取優惠券" clickFunc={() =>
this.props.navigation.navigate('Content', {
data: {
url: `${activityInfo.activity.myInviteUrl}?sid=${store.getState().auth.sid}&language=${store.getState().language.language}&sellClient=${currentPlatform}&appVersion=${getVersion()}`,
title: '邀請好友落Order獎你HKD10優惠券',
message: 'goforeat'
},
kind: 'activity'
})
}/>)
}
{this._renderFlatListView()}
</CustomizeContainer.SafeView>
);
}
}
const foodListStateToProps = state => {
return {
isAdShow: state.toggleAd.isAdvertisementShow,
sid: state.auth.sid,
userInfo: state.auth,
activityInfo: state.activityInfo
};
};
const foodListDispatchToProps = dispatch => ({
showAd: () => dispatch({ type: SHOW_AD }),
hideAd: () => dispatch({ type: HIDE_AD })
});
export default connect(
foodListStateToProps,
foodListDispatchToProps,
null,
{withRef: true}
)(FoodListView);
const styles = StyleSheet.create({
itemContainer: {
backgroundColor: '#fff',
padding: em(8),
// height: em(190),
borderBottomWidth: em(15),
borderBottomColor: '#f0f0f0',
justifyContent: 'center',
position: 'relative'
},
dateText: {
fontSize: em(20),
color: "#333",
marginBottom: em(10),
fontWeight: "800"
},
articleItemContainer: {
// flex: 1,
// paddingBottom: 15,
// flexDirection: "row",
shadowColor: "#333",
shadowOffset: { width: 3, height: 5 },
shadowOpacity: 0,
shadowRadius: 10,
backgroundColor: "#fff",
// overflow: "hidden",
// alignItems: 'center',
},
itemLike: {
backgroundColor: "rgba(0, 0, 0, .5)",
width: em(92),
height: em(32),
borderRadius: em(20),
position: 'absolute',
top: em(155),
left: em(12),
zIndex: 5,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center'
},
itemLikeImg: {
width: em(22),
marginRight: em(10)
},
itemLikeText: {
color: '#fff',
fontSize: em(16),
},
articleItemDetails: {
// height: em(100),
// paddingLeft: em(10),
// paddingRight: 0,
marginTop: em(5),
flex: 1,
backgroundColor: "#fff",
// borderWidth: 1,
// borderColor: '#ededeb',
borderTopRightRadius: 5,
borderBottomRightRadius: 5,
// overflow: "hidden",
// justifyContent: "space-between"
},
itemName: {
flexDirection: "row",
justifyContent: "space-between"
},
foodCommonContainer: {
flexDirection: "row",
justifyContent: "flex-start",
marginBottom: em(5)
},
foodName: {
fontSize: em(20),
color: "#111",
fontWeight: "800",
maxWidth: em(220)
},
foodCommon: {
fontSize: em(18),
color: "#666"
},
foodBrief: {
fontSize: em(14),
color: "#959595",
textAlign: "justify",
lineHeight: 20,
},
foodUnit: {
fontSize: em(15),
color: "#666",
marginRight: em(3),
marginTop: Platform.OS === "android" ? em(-3.5) : 0
},
foodPrice: {
fontSize: _winWidth < 375 ? em(20) : em(20),
color: "#2a2a2a",
lineHeight: em(20)
},
marginBottom9: {
marginBottom: em(10)
},
confirmBtn: {
position: "absolute",
right: 15,
top: em(260),
backgroundColor: '#ff5050',
padding: em(5),
borderRadius: em(2.5)
}
});