· 6 years ago · Oct 03, 2019, 07:16 AM
1import React, { Component } from "react";
2import { Text, View, TextInput } from "react-native";
3import { createStackNavigator, createMaterialTopTabNavigator } from "react-navigation";
4import { WinnerBigFormTab } from "../../screens";
5import { SVGWinner, TopTab, Col, TextButton, KeyboardShift } from "../../components";
6import EStyleSheet from "react-native-extended-stylesheet";
7import imgSrc from "../../utils/Images";
8import { handleBase64Image } from "../../utils/Tools";
9import { DynamicStore, AppStore, NavigationStore } from '../../stores'
10import i18n from "../../i18n";
11import GStyles from "../../utils/GlobalStyles";
12import Color from "color";
13import debounce from 'lodash/debounce';
14import { BigErrorType, MODALS, SCREENS, PopupType } from '../../utils/Enums';
15import { inject, observer } from 'mobx-react/native'
16import Api from "../../utils/Api";
17
18const ALERT_TIME = 2000
19const DEBOUNCE_TIME = 1200
20
21@inject("UserStore")
22@observer
23export default class WinnerBigForm extends Component {
24 constructor(props) {
25 super(props);
26 this.state = {
27 sum: 0,
28 stake: 5,
29 maxEventCombinations: 25,
30 bigGameMaximumBetSum: 955,
31 gameData: null,
32 formGame1: {
33 teamA: [],
34 teamB: []
35 },
36 formGame2: {
37 teamA: [],
38 teamB: []
39 },
40 formGame3: {
41 teamA: [],
42 teamB: []
43 },
44 fullForm: [],
45 currentRoute: 'WinnerBigFormTab1',
46 errorAlert: null,
47 creditCardData: {},
48 }
49 this.onChangeSum = debounce(this.onChangeSum, DEBOUNCE_TIME);
50
51 };
52
53 componentDidMount = () => {
54 const navParams = this.props.navigation.state.params
55 const gameData = navParams ? navParams.gameData : null
56 console.log("TCL: WinnerBigForm -> componentDidMount -> gameData", gameData)
57 const systemParameters = DynamicStore.getSystemParameters;
58 const stake = systemParameters.bigGameStake;
59 const maximumBetSum = systemParameters.bigGameMaximumBetSum;
60 const maxEventCombinations = systemParameters.bigGameMaxEventComb;
61
62 this.setState({ gameData, stake, sum: stake, maxEventCombinations, maximumBetSum })
63 };
64
65 TabNavigator = createMaterialTopTabNavigator({
66 WinnerBigFormTab1: {
67 screen: createStackNavigator({
68 WinnerBigFormTab,
69 }, {
70 headerMode: 'none'
71 }),
72 navigationOptions: ({ screenProps }) => ({
73 title: screenProps.fullForm.includes(1) ? '1 ✓' : '1',
74 })
75 },
76 WinnerBigFormTab2: {
77 screen: createStackNavigator({
78 WinnerBigFormTab,
79 }, {
80 headerMode: 'none'
81 })
82 ,
83 navigationOptions: ({ screenProps }) => ({
84 title: screenProps.fullForm.includes(2) ? '2 ✓' : '2',
85 })
86 },
87 WinnerBigFormTab3: {
88 screen: createStackNavigator({
89 WinnerBigFormTab,
90 }, {
91 headerMode: 'none'
92 })
93 ,
94 navigationOptions: ({ screenProps }) => ({
95 title: screenProps.fullForm.includes(3) ? '3 ✓' : '3',
96 })
97 },
98 WinnerBigFormErase: {
99 screen: WinnerBigFormTab,
100 navigationOptions: {
101 title: 'x',
102 // @Stas / @Idan - the icon doesnt work ¯\_(ツ)_/¯
103 tabBarIcon: ({ focused, tintColor }) => {
104 return <SVGWinner
105 style={{ backgroundColor: 'pink', width: 16, height: 16, color: 'red' }}
106 fill={tintColor}
107 width="16"
108 height="16"
109 source={handleBase64Image(imgSrc.a_icons_success_enabled)}
110 />
111 },
112 }
113 },
114 },
115 {
116 initialRouteName: 'WinnerBigFormTab1',
117 lazy: true,
118 tabBarOptions: {
119 scrollEnabled: true,
120 showIcon: true,
121 activeTintColor: EStyleSheet.value('$white_60')
122 },
123 tabBarComponent: TopTab,
124 navigationOptions: ({ navigation }) => ({
125 tabBarOnPress: ({ navigation, defaultHandler }) => {
126 console.log('tabBarOnPress', navigation)
127 const { key } = navigation.state;
128 console.log('key', key)
129 if (key == 'WinnerBigFormErase') {
130 this.setState({ fullForm: [], formGame1: { teamA: [], teamB: [] }, formGame2: { teamA: [], teamB: [] }, formGame3: { teamA: [], teamB: [] } })
131 } else {
132 defaultHandler()
133 }
134 },
135 })
136 }
137 );
138
139 updateAlert = (type) => {
140 const { errorAlert } = this.state
141 setTimeout(() => {
142 this.setState({ errorAlert: errorAlert == type ? null : errorAlert })
143 }, ALERT_TIME);
144 }
145
146 onUpdateGame = (tabIndex, betData) => {
147 const newBets = this.calculateBetOptions(tabIndex, betData)
148 const { maxEventCombinations, gameData } = this.state
149 if (newBets.length > gameData.maximumNumberOfScoresSelectedPerTeam) {
150 return this.setState({ errorAlert: BigErrorType.MAXIMUM_SELECTED_PER_TEAM }, () => this.updateAlert(BigErrorType.MAXIMUM_SELECTED_PER_TEAM))
151 }
152 if ((betData.team == 'teamA' && (newBets.length * this.state['formGame' + tabIndex].teamB.length) > maxEventCombinations) || (betData.team == 'teamB' && (newBets.length * this.state['formGame' + tabIndex].teamA.length) > maxEventCombinations)) {
153 return this.setState({ errorAlert: BigErrorType.MAXIMUM_EVENT_COMBINATIONS }, () => this.updateAlert(BigErrorType.MAXIMUM_EVENT_COMBINATIONS))
154 }
155 let fullForm = this.checkValidateForm(tabIndex, betData.team, newBets)
156 const currentRoute = 'WinnerBigFormTab' + tabIndex
157 this.setState({ fullForm, currentRoute, ['formGame' + tabIndex]: { ...this.state['formGame' + tabIndex], [betData.team]: newBets } })
158 }
159
160 checkValidateForm = (tabIndex, team, newBets) => {
161 const { fullForm } = this.state
162 if ((team == 'teamA' && newBets.length > 0 && this.state['formGame' + tabIndex].teamB.length > 0) || (team == 'teamB' && newBets.length > 0 && this.state['formGame' + tabIndex].teamA.length > 0)) {
163 return !fullForm.includes(tabIndex) ? [...fullForm, tabIndex] : fullForm
164 } else {
165 const index = fullForm.indexOf(tabIndex)
166 if (index !== -1) {
167 const newFullForm = fullForm
168 newFullForm.splice(index, 1)
169 return newFullForm
170 }
171 return fullForm
172 }
173 }
174
175 calculateBetOptions = (tabIndex, betData) => {
176 let bets = this.state['formGame' + tabIndex][betData.team].slice();
177 const betIndex = bets.indexOf(betData.bet)
178 if (betIndex === -1) {
179 bets.push(betData.bet)
180 } else {
181 bets.splice(betIndex, 1)
182 }
183 console.log("TCL: calculateBetOptions -> END bets", bets)
184 return bets
185 }
186
187 onChangeSum = (sum) => {
188 const { stake, maximumBetSum } = this.state
189 if (+sum > +maximumBetSum) {
190 return this.setState({ sum: maximumBetSum.toString(), errorAlert: BigErrorType.MAXIMUM_SUM }, () => this.updateAlert(BigErrorType.MAXIMUM_SUM))
191 } else if (+sum < +stake) {
192 return this.setState({ sum: stake.toString(), errorAlert: BigErrorType.MINIMUM_SUM }, () => this.updateAlert(BigErrorType.MINIMUM_SUM))
193 } else if (+sum % +stake != 0) {
194 return this.setState({ sum: (Math.floor(sum / stake) * stake).toString() || stake.toString(), errorAlert: BigErrorType.MULTIPLE_OF_STAKE }, () => this.updateAlert(BigErrorType.MULTIPLE_OF_STAKE))
195 }
196 }
197
198 getNumberColumns = () => {
199 if (this.isFullForm()) {
200 let columns = 1
201 for (i = 1; i <= 3; i++) {
202 columns = columns * this.state['formGame' + i].teamA.length * this.state['formGame' + i].teamB.length
203 }
204 return columns
205 } else {
206 return 0
207 }
208 }
209
210 getTotalSum = () => this.getNumberColumns() * +this.state.sum
211
212 onSendForm = async () => {
213 if (this.isFullForm()) {
214 if (!this.props.UserStore.isConnected) {
215 AppStore.toggleModal(MODALS.LAYOVER, SCREENS.LOGIN)
216 } else {
217 setTimeout(() => {
218 this.checkUserBalance()
219 }, DEBOUNCE_TIME);
220 }
221 } else {
222 this.setState({ errorAlert: BigErrorType.FORM_NOT_FULL }, () => this.updateAlert(BigErrorType.FORM_NOT_FULL))
223 }
224 }
225
226 isFullForm = () => {
227 let isFullForm = true
228 for (i = 1; i <= 3; i++) {
229 if (this.state['formGame' + i].teamA.length == 0 || this.state['formGame' + i].teamB.length == 0) {
230 isFullForm = false
231 }
232 }
233 return isFullForm
234 }
235
236 checkUserBalance = async () => {
237 try {
238 AppStore.showLoader();
239 const response = await Api.GetWithdrawalData();
240 const { lastDigits, deposit, winnings, promo, token } = response
241 const totalBalance = deposit + winnings + promo
242 if (this.getTotalSum() <= totalBalance) {
243 alert('sum is ok - send request')
244 this.postTotoBets()
245 } else {
246 this.setState({ errorAlert: BigErrorType.BALANCE_LESS, creditCardData: { totalBalance, token, lastDigits } })
247 }
248 AppStore.hideLoader();
249 } catch (e) {
250 console.log('checkUserBalance ERROR', e)
251 AppStore.hideLoader();
252 AppStore.showPopup({ type: PopupType.REGULAR, title: i18n.t('c_popup_general_title'), content: e.error_message });
253 }
254 }
255
256 postTotoBets= async () => {
257 try {
258 AppStore.showLoader();
259 const { sum } = this.state
260 const params = {
261 unitarySelectionStake: +sum,
262 addOnUnitarySelectionStake: 0,
263 }
264 const response = await Api.SendTotoPoolGames();
265 const { lastDigits, deposit, winnings, promo, token } = response
266 const totalBalance = deposit + winnings + promo
267 if (this.getTotalSum() <= totalBalance) {
268 alert('sum is ok - send request')
269 this.postTotoBets()
270 } else {
271 this.setState({ errorAlert: BigErrorType.BALANCE_LESS, creditCardData: { totalBalance, token, lastDigits } })
272 }
273 AppStore.hideLoader();
274 } catch (e) {
275 console.log('checkUserBalance ERROR', e)
276 AppStore.hideLoader();
277 AppStore.showPopup({ type: PopupType.REGULAR, title: i18n.t('c_popup_general_title'), content: e.error_message });
278 }
279 }
280
281
282 addMoney = async () => {
283 const { UserStore } = this.props;
284 const { creditCardData } = this.state
285 if (!creditCardData.lastDigits) {
286 return this.setState({ errorAlert: BigErrorType.ADD_CREDIT_CARD })
287 }
288 try {
289 AppStore.showLoader();
290 await Api.DepositCreditCard({ isbbInternalToken: creditCardData.token, amount: this.getTotalSum() - +creditCardData.totalBalance });
291 const balanceResponse = await Api.GetUserBalances()
292 UserStore.setBalance(balanceResponse.balance)
293 UserStore.setPromo(balanceResponse.comBalances.promo)
294 AppStore.hideLoader();
295 }
296 catch (e) {
297 AppStore.hideLoader();
298 e.code && AppStore.showPopup({ type: PopupType.REGULAR, title: i18n.t('c_popup_general_title'), content: e.error_message });
299 }
300 }
301
302 render() {
303 const { gameData, formGame1, formGame2, formGame3, fullForm, currentRoute, errorAlert, stake, maxEventCombinations, sum, maximumBetSum } = this.state
304 let TabNavigator = this.TabNavigator
305 console.log('%c [THIS.STATE]:', 'background: #222; color: #bada55', this.state);
306 return gameData ?
307 <>
308 <KeyboardShift>
309 <TabNavigator screenProps={{ gameData, onUpdateGame: this.onUpdateGame, formGame1, formGame2, formGame3, fullForm }} />
310
311 {/*ALERT MESSAGES*/}
312 {errorAlert &&
313 <View style={s.alertMessageAbsoluteContainer}>
314 <View style={[s.alertMessageContainer]}>
315 <View style={[GStyles.alignCenter, GStyles.flexRow,]}>
316 {errorAlert == BigErrorType.BALANCE_LESS &&
317 <>
318 <Col size={2}>
319 <Text style={[s.alertMessageText, { textAlign: 'left' }]}>{i18n.t('c_game_wBig_results_warning_balance_less')}</Text>
320 </Col>
321 <Col size={1.2}>
322 <TextButton
323 buttonType={'greenLight'}
324 containerStyle={s.alertMessageContainerStyle}
325 style={s.alertMessageStyle}
326 textStyle={s.alertMessageTextStyle}
327 onPress={this.addMoney}
328 text={i18n.t('c_game_wBig_results_warning_btn_to_deposit')}
329 />
330 </Col>
331 </>}
332 {errorAlert == BigErrorType.ADD_CREDIT_CARD &&
333 <>
334 <Col size={2}>
335 <Text style={[s.alertMessageText, { textAlign: 'left' }]}>{i18n.t('c_game_wBig_warning_credit_card_undefined')}</Text>
336 </Col>
337 <Col size={1.2}>
338 <TextButton
339 buttonType={'greenLight'}
340 containerStyle={s.alertMessageContainerStyle}
341 style={s.alertMessageStyle}
342 textStyle={s.alertMessageTextStyle}
343 onPress={() => NavigationStore.navigate('Deposit')}
344 text={i18n.t('c_game_wBig_warning_add_credit_card_btn')}
345 />
346 </Col>
347 </>}
348 {errorAlert == BigErrorType.MINIMUM_SUM &&
349 <Col size={2}>
350 <Text style={[s.alertMessageText]}>{`${i18n.t('c_game_wBig_results_warning_min_sum_is')} ${stake} ₪`}</Text>
351 </Col>
352 }
353 {errorAlert == BigErrorType.MAXIMUM_SUM &&
354 <Col size={2}>
355 <Text style={[s.alertMessageText]}>{`${i18n.t('c_game_wBig_warning_max_bet_sum')} ${maximumBetSum}`}</Text>
356 </Col>
357 }
358 {errorAlert == BigErrorType.MAXIMUM_SELECTED_PER_TEAM &&
359 <Col size={2}>
360 <Text style={[s.alertMessageText]}>{i18n.t('c_game_wBig_warning_max_of_scores_selected_per_team')}</Text>
361 </Col>
362 }
363 {errorAlert == BigErrorType.MAXIMUM_EVENT_COMBINATIONS &&
364 <Col size={2}>
365 <Text style={[s.alertMessageText]}>{`${i18n.t('c_game_wBig_warning_max_event_combinations1')} ${maxEventCombinations} ${i18n.t('c_game_wBig_warning_max_event_combinations1')}`}</Text>
366 </Col>
367 }
368 {errorAlert == BigErrorType.FORM_NOT_FULL &&
369 <Col size={2}>
370 <Text style={[s.alertMessageText]}>{i18n.t('c_game_wBig_warning_form_not_full')}</Text>
371 </Col>
372 }
373 {errorAlert == BigErrorType.MULTIPLE_OF_STAKE &&
374 <Col size={2}>
375 <Text style={[s.alertMessageText]}>{`${i18n.t('c_game_wBig_warning_sum_not_multiple_of_stake')} ${stake}`}</Text>
376 </Col>
377 }
378
379
380 </View>
381 </View>
382 </View>
383 }
384
385 {/*FOOTER*/}
386 <View style={s.footerContainerTop}>
387 <View style={[GStyles.alignCenter, GStyles.flexRow,]}>
388 <Col>
389 <Text style={[s.footerSubTitle, { paddingTop: 4 }]}>{i18n.t('c_game_wBig_results_amount_to_attach')}:</Text>
390 </Col>
391
392 <Col />
393
394 <Col size={1}>
395 <View style={[GStyles.flexRow]}>
396 <TextInput
397 value={sum}
398 style={[s.sumInput, ([BigErrorType.BALANCE_LESS, BigErrorType.MINIMUM_SUM, BigErrorType.MAXIMUM_SUM, BigErrorType.MULTIPLE_OF_STAKE].includes(errorAlert)) && s.alertRedBorderInput,]}
399 underlineColorAndroid="transparent"
400 keyboardType={'numeric'}
401 onChangeText={(sum) => { this.setState({ sum }); this.onChangeSum(sum) }}
402 />
403 <SVGWinner
404 width="24"
405 height="24"
406 style={s.currencyIcon}
407 fill={EStyleSheet.value('$black')}
408 source={imgSrc.a_icons_currency}
409 />
410 </View>
411 </Col>
412 </View>
413 </View>
414
415 <View style={s.footerContainer}>
416 <View style={[GStyles.alignCenter, GStyles.flexRow]}>
417 <Col size={1.3}>
418 <Text style={s.footerSubTitle}>{i18n.t('c_game_w16_game_footer_filled_columns')}:</Text>
419 <Text style={s.footerTitle}>{i18n.t('c_game_wBig_results_form_price')}:</Text>
420 </Col>
421
422 <Col style={{ paddingRight: 16 }}>
423 <Text style={s.footerSubTitle}>{this.getNumberColumns()}</Text>
424 <Text style={[s.footerTitle]}>{`${this.getTotalSum()} \u20AA`}</Text>
425 </Col>
426
427 <Col size={1.2}>
428 <TextButton
429 containerStyle={{ marginBottom: 0 }}
430 onPress={this.onSendForm}
431 text={i18n.t('text_betslip_send')}
432 />
433 </Col>
434 </View>
435 </View>
436 </KeyboardShift>
437 </>
438 : <View />
439 }
440}
441
442
443const s = EStyleSheet.create({
444 footerContainer: {
445 paddingHorizontal: 8,
446 paddingVertical: 8,
447 backgroundColor: EStyleSheet.value('$very_light_pink'),
448 },
449 footerContainerTop: {
450 paddingHorizontal: 8,
451 paddingVertical: 8,
452 backgroundColor: EStyleSheet.value('$very_light_pink'),
453 borderBottomWidth: 1,
454 borderBottomColor: () => Color(EStyleSheet.value('$gray_blue_secondary')).alpha(.3)
455 },
456 footerTitle: {
457 color: '$black',
458 fontSize: 16,
459 lineHeight: 24,
460 writingDirection: 'rtl',
461 fontFamily: GStyles.HeeboBold,
462 textAlign: 'left',
463 },
464 footerSubTitle: {
465 color: '$black',
466 fontSize: 14,
467 lineHeight: 16,
468 writingDirection: 'rtl',
469 fontFamily: GStyles.HeeboMedium,
470 textAlign: 'left',
471 },
472 footerText: {
473 color: '$black',
474 fontSize: 10,
475 lineHeight: 12,
476 writingDirection: 'rtl',
477 fontFamily: GStyles.HeeboBold,
478 textAlign: 'left',
479 },
480 sumInput: {
481 flex: 1,
482 height: 28,
483 paddingRight: 20,
484 paddingLeft: 8,
485 backgroundColor: '$white',
486 borderRadius: 2,
487 borderWidth: 1,
488 borderColor: '$black_20',
489 fontSize: 16,
490 lineHeight: 24,
491 fontFamily: GStyles.HeeboMedium,
492 color: '$black',
493 writingDirection: 'rtl',
494 textAlign: 'right',
495 shadowColor: '$black_10',
496 shadowOffset: {
497 width: 0,
498 height: 4,
499 },
500 shadowOpacity: 1,
501 shadowRadius: 8,
502 elevation: 2,
503 },
504 currencyIcon: {
505 color: '$gray_blue',
506 position: 'absolute',
507 right: 5,
508 top: 4
509 },
510 // -----------
511 alertMessageAbsoluteContainer: {
512 position: 'absolute',
513 bottom: 100,
514 width: '100%',
515 marginHorizontal: 8,
516 marginBottom: 8,
517 },
518 alertMessageContainer: {
519 flex: 1,
520 backgroundColor: '$white',
521 borderRadius: 4,
522 borderWidth: 2,
523 borderColor: '$red_toto',
524 alignItems: 'center',
525 marginTop: 10,
526 paddingHorizontal: 8,
527 paddingVertical: 8,
528 shadowColor: '$black_10',
529 shadowOffset: {
530 width: 0,
531 height: 4,
532 },
533 shadowOpacity: 1,
534 shadowRadius: 8,
535 elevation: 1,
536 },
537 alertMessageText: {
538 color: '$red_secondary',
539 fontSize: 12,
540 lineHeight: 16,
541 writingDirection: 'rtl',
542 fontFamily: GStyles.HeeboMedium,
543 textAlign: 'center',
544 },
545 alertMessageContainerStyle: {
546 borderWidth: 0,
547 marginBottom: 0,
548 },
549 alertMessageStyle: {
550 backgroundColor: '$green_secondary',
551 height: 24,
552 },
553 alertMessageTextStyle: {
554 color: EStyleSheet.value('$white'),
555 fontSize: 13,
556 lineHeight: 16,
557 paddingTop: 3,
558 },
559 alertRedBorderInput: {
560 borderWidth: 2,
561 borderColor: '$red_toto',
562 },
563});