import React, { Component, Fragment } from 'react'
import {
View, ScrollView, Dimensions, TouchableOpacity, StyleSheet, FlatList, RefreshControl, Animated, ActivityIndicator, Platform, Alert, Modal
} from 'react-native'
import Image from 'react-native-fast-image'
import ImageBackground from 'react-native-fast-image'
import Icon from '../../components/Icon'
import { Card, Body, Badge, ListItem, Left, Right, } from 'native-base'
import { BackgroundImage_RegisterForm } from '../../components/BackgroundImage_RegisterForm'
import LinearGradient from 'react-native-linear-gradient'
import { BackgroundImage } from '../../components/BackgroundImage'
import Text from '../../components/Text'
import { NavigationEvents } from 'react-navigation'
import {
getNews,
getNewsPage,
getUserProfile,
getNewsByProject,
login,
registerDevice,
setPaymentLater,
setFillInMeterLater,
checkPaymentMeter } from '../../api/UserApi';
import { clearToken } from '../../api/api'
import { bindActionCreators } from 'redux'
import {
appSetDevice,
appSetPushToken,
appSetToken,
appSetUser,
appCleanToken,
appCleanUser,
appSetNotification,
appSetProjectID,
appCleanProjectID
} from '../../redux/app/action'
import { connect } from 'react-redux'
import moment from 'moment'
import IndicatorLoading from '../../components/IndicatorLoading'
import { loginWithFacebook } from '../../components/FacebookUtils'
import { signinApple } from '../../components/AppleAuth'
import parseDateLocale from '../../utils/parseDateLocale'
import { from } from 'rxjs'
//import Slideshow from 'react-native-image-slider-show';
import appleAuth, {
AppleButton,
} from '@invertase/react-native-apple-authentication';
import { t, locale } from '../../utils/i18n'
import messaging from "@react-native-firebase/messaging";
import {store} from '../../redux/store';
const { height, width } = Dimensions.get('window')
console.disableYellowBox = true
function PopupNotiElectric({isVisible, onPress, onCancel, onPressLater, pending_payment, due_at_payment}) {
return
{t('have_outstanding_balance')}
{pending_payment}
{t('baht')}
{t('please_pay_within')} {moment(due_at_payment).add('543', 'y').format('DD/MM/YYYY')}
{t('pay_now')}
{t('later')}
}
function PopupOverDue({isVisible, onPress, onCancel, onPressLater, pending_payment}) {
return
{t('close')}
{t('payment_overdue')}
{pending_payment}
{t('baht')}
{t('outstanding_balance_past_due')}
{/*กรุณาดำเนินการชำระหนี้ตอนนี้*/}
{t('contact_front')}
{t('ok')}
{/*
ภายหลัง
*/}
}
function PopupNotiFillInMeter({isVisible, onPress, onCancel, onPressLater, notified_meter_at}) {
return
{/**/}
{t('attach_meter')}
{t('by_due_date')} {notified_meter_at}
{t('sorry_send_data')}
{t('enter_info')}
{t('later')}
}
class NewsScreen extends Component {
constructor (props) {
super(props)
this.state = {
isLoading: false,
refreshing: false,
auth: null,
position: 0,
user: {
point: 0
},
interval: null,
news_head: [{
title: t('loading_news'),
content: t('loading_news'),
date: t('loading_news'),
is_new: false
}],
new_all: [{
title: t('loading_news'),
content: t('loading_news'),
date: t('loading_news'),
is_new: false
}],
due_at: '',
pending_payment: 0,
noti_count: 0,
isFirstTime: true,
user_point: 0,
user_project_id: 0,
isBilling: false,
isMeter: false,
isShipping: false,
scrollY: new Animated.Value(0),
loadMore: false,
loadPage: 1,
last_page: 1,
isLoadmore: false,
fb_is_link: false,
email: '',
visibleNotiElectric: false,
visibleNotiOverDue: false,
visibleNotiMeter: false,
payment_id: null,
is_notified_electric: false,
is_notified_before_due:false,
is_notified_overdue: false,
is_notified_meter: false,
notified_meter_at: moment().format('DD MMM YYYY'),
due_at_payment: moment().format('DD/MM/YYYY')
}
this._onCarouselScroll = this._onCarouselScroll.bind(this)
this.initData = this.initData.bind(this)
}
checkNotifiedPopup = () => {
if (this.props.user) {
checkPaymentMeter()
.then(res => {
if (res.data && res.data.success) {
this.setState({
is_notified_electric: res.data.is_notified_electric,
is_notified_meter: res.data.is_notified_meter,
is_notified_overdue: res.data.is_notified_overdue,
notified_meter_at: res.data.notified_meter_at,
payment_id: res.data.payment_id,
pending_payment: res.data.pending_payment != null ? res.data.pending_payment : 0,
due_at_payment: res.data.payment && res.data.payment.due_at ? res.data.payment.due_at : null,
}, () => {
setTimeout(() => {
console.log('pending payment >>> ', parseInt(this.state.pending_payment))
this.setState({
visibleNotiElectric: this.state.is_notified_overdue ? false : this.state.is_notified_electric && parseInt(this.state.pending_payment) > 0,
visibleNotiMeter: ((this.state.is_notified_electric && parseInt(this.state.pending_payment) > 0) || this.state.is_notified_overdue) === true ? false : this.state.is_notified_meter,
visibleNotiOverDue: this.state.is_notified_overdue,
})
}, 1000)
})
}
})
}
}
async getUser () {
if (this.props.token != null) {
return await getUserProfile()
.then(async res => {
if (res.ok) {
console.log("News:: res.data:")
console.log(res.data)
console.log('project id >>>> ', res.data.project_id)
this.checkNotifiedPopup()
if(res.data.project_id){
this.setState({
loadPage: 1,
last_page: 1,
news_head: [{
title: t('loading_news'),
content: t('loading_news'),
date: t('loading_news'),
is_new: false
}],
new_all: [{
title: t('loading_news'),
content: t('loading_news'),
date: t('loading_news'),
is_new: false
}],
},async () => {
await this.getAllNewsByProject(res.data.project_id)
})
}else {
await this.getAllNewsList()
}
this.setState({
noti_count: res.data.count_noti,
user_point: res.data.point_balance,
user_project_id: res.data.project_id,
isBilling: res.data.user.enable_billing == null ? false : res.data.user.enable_billing,
isMeter: res.data.user.enable_meter == null ? false : res.data.user.enable_meter,
isShipping: res.data.user.enable_shipping == null ? false : res.data.user.enable_shipping,
fb_is_link: res.data.user.fb_is_link,
email: res.data.user.email,
}, () => {
if (res.data.message != null) {
Alert.alert('แจ้งเตือนจากระบบ', res.data.message)
}
})
} else {
// this.setState({
// isLoading: false
// }, () => {
clearToken();
setTimeout(() => {
this.props.appCleanUser();
this.props.appCleanToken();
this.props.appCleanProjectID();
this.initData()
}, 500)
// })
}
})
}else {
await this.getAllNewsList()
}
return true
}
async getAllNewsByProject(project_id) {
return getNewsByProject(project_id)
.then(res => {
console.log('res >>>>>>> ', res)
this.setNewsData(res)
})
}
async getAllNewsList () {
// return getNews()
return getNewsPage(this.state.loadPage)
.then(res => {
this.setNewsData(res)
})
}
setNewsData(res) {
if (res.data.data && (res.data.data).length > 5) {
console.log('data >>>>> ', res)
var cut = []
for (let index = 0; index < 5; index++) {
cut.push(res.data.data[index])
}
this.setState({
user: this.props.user,
news_head: cut,
new_all: res.data.data,
refreshing: false,
isLoading: false,
last_page: res.data.last_page
})
} else {
this.setState({
news_head: res.data.data,
new_all: res.data.data,
refreshing: false,
isLoading: false,
last_page: res.data.last_page
})
}
}
initData () {
console.log('initData >>> ')
this.setState({
isLoading: true,
}, () => {
Promise.all([
this.getUser(),
// this.getAllNewsList()
])
.then(() => {
let user_id = 0
let user_noti_id = 0
if (this.props.token != null) {
if (this.state.isFirstTime) {
this.props.appSetNotification(this.state.noti_count)
this.props.appSetProjectID(this.state.user_project_id)
this.setState({ isFirstTime: false })
}
}
if (this.props.user && this.props.user.id) {
user_id = this.props.user.id
user_noti_id = this.props.user.id
} else if (this.props.device && this.props.device.customer_id) {
user_noti_id = this.props.device.customer_id
}
if (this.props.token != null && this.props.user != null) {
this.setState({
auth: true,
})
} else {
this.setState({
auth: false
})
}
this.setState({ isLoading: false })
})
.catch(() => {
// console.log('catch ------------------>');
// this.setState({isLoading:false})
// this.props.appCleanUser()
// this.props.appCleanToken()
setTimeout(() => {
this.setState({
isLoading: false
}, () => {
//this.props.appCleanUser()
//this.props.appCleanToken()
})
}, 600)
// this.initData()
})
})
}
setPermission = async () => {
try {
const enabled = await messaging().hasPermission()
if (!enabled) {
await messaging().requestPermission()
}
} catch (error) {
console.log('error', error)
}
}
initNotification = async () => {
await this.setPermission()
const fcmToken = await messaging().getAPNSToken()
if (fcmToken) {
store.dispatch(appSetPushToken(fcmToken))
const resultSendDevice = await registerDevice(fcmToken)
console.log(' re sult register_device =>', resultSendDevice)
if (resultSendDevice.ok && resultSendDevice.data.success) {
store.dispatch(appSetDevice(resultSendDevice.data.device))
}
}
}
_onRefresh = () => {
this.setState({
refreshing: true, loadPage: 1, loadMore: false
}, () => {
this.initData()
this.initNotification()
// this.checkNotifiedPopup()
})
}
setPaymentLater = () => {
// setPaymentLater()
// .then(res => {
// if(res && res.data && res.data.success){
this.setState({
visibleNotiElectric: false,
visibleNotiOverDue: false
})
if(this.state.is_notified_meter === true){
this.setState({
visibleNotiMeter: true
}, () => {
setTimeout(() => {
this.forceUpdate()
}, 100)
})
}
// }
// })
}
setFillInMeterLater = () => {
// setFillInMeterLater()
// .then(res => {
// if(res && res.data && res.data.success){
this.setState({
visibleNotiMeter: false
})
// }
// })
}
renderNativeItem = ({ item }) => (
{this.props.navigation.navigate('NewsDetail', { news_id: item.id })}}>
{item.title}
{parseDateLocale(item.date)}
{
item.is_new == true &&
{item.type == "promotion" ? t('latest_promotion') : t('latest_news')}
}
)
renderNativeItemImages = (item) => {
return {
this.props.navigation.navigate('NewsDetail', { news_id: item.id })
}}>
{ this.props.source = require('../../../assets/images/default_big.png') }} style={styles.imgBg}>
{item.is_new == true ?
{item.type == "promotion" ? t('latest_promotion') : t('latest_news')}
: null }
{item.title}
{parseDateLocale(item.date)}
}
_onCarouselScroll (e) {
const scrollX = e.nativeEvent.contentOffset.x
this.setState({
position: Math.ceil(scrollX / width)
})
// console.log(this.state.position)
}
isCloseToBottom = ({ layoutMeasurement, contentOffset, contentSize }) => {
const paddingToBottom = 20
return layoutMeasurement.height + contentOffset.y >=
contentSize.height - paddingToBottom
}
loadMoreData = async () => {
if(parseInt(this.state.loadPage) < parseInt(this.state.last_page)){
this.setState({
loadMore: true,
isLoadmore: true,
loadPage: this.state.loadPage + 1
}, () => {
getNewsPage(this.state.loadPage)
.then(res => {
if (res.ok) {
let resData = res.data.data
let news_all = this.state.new_all
let news_arr = news_all.concat(resData)
this.setState({
new_all: news_arr,
refreshing: false,
loadMore: false,
isLoadmore: false,
last_page: res.data.last_page
})
}
})
})
}
/*loading - set loadMore = false when done*/
}
_keyExtractorNewHead = (item, index) => 'new_head_' + index
_keyExtractorNewAll = (item, index) => 'new_all_' + index
render () {
return (
{
this.setState({
isLoading: true
}, () => {
this.initData()
})
}}
/>
}
showsVerticalScrollIndicator={false}
scrollEventThrottle={16}
onScroll={Animated.event(
[{ nativeEvent: { contentOffset: { y: this.state.scrollY } } }],
{useNativeDriver: false}
)}
onMomentumScrollEnd={({ nativeEvent }) => {
if (this.isCloseToBottom(nativeEvent)) {
this.loadMoreData()
}
}}
>
this.renderNativeItemImages(item)}
horizontal={true}
showsHorizontalScrollIndicator={false}
pagingEnabled={true}
keyExtractor={this._keyExtractorNewHead}
onScroll={this._onCarouselScroll}
/>
{
this.state.news_head ?
(this.state.news_head).map((item, i) => )
:
}
{
this.state.auth !== null &&
(
!this.state.auth ? (
{t('for_csa_customer')}
{t('login')} {t('to_view_outstanding_balance')}
{/* {
// this.props.navigation.navigate('Register')
this.props.navigation.navigate('Terms')
}}>
{t('create_account')}
*/}
{/* {t('or')} */}
{ this.props.navigation.navigate('Login') }}>
{t('login')}
{Platform.OS == 'ios' ? {t('or')} : null}
{Platform.OS == 'ios' ?
{signinApple(() => {
this.initData()
})
}}
/>
: null}
{t('or')}
{
loginWithFacebook(() => {
this.initData()
})}}>
{t('login_facebook')}
) : (
{/*คุณมียอดค้างชำระ*/}
{t('have_outstanding_balance')}
{this.state.isBilling ? this.state.pending_payment : 'N/A'}
{/*{parseFloat(this.state.pending_payment) > 0 ?'โปรดชำระก่อนวันที่':'ยังไม่มียอดค้างชำระ'}*/}
{parseFloat(this.state.pending_payment) > 0 ? t('to_view_outstanding_balance') : t('no_outstanding_balance_yet')}
{this.state.due_at !== '' && {parseFloat(this.state.pending_payment) > 0 && this.state.due_at !== '' ? this.state.due_at : ''} }
{this.props.navigation.navigate('Bill')}}>
{/*ดูเพิ่มเติม*/}
{t('view_more')}
{t('view_points')}
{parseFloat(this.state.user_point).toLocaleString()}
{/*พอยต์*/}
{t('point')}
{this.props.navigation.navigate('Redeem')}}>
{t('redeem')}
{
this.props.navigation.navigate('Meter')
}} style={{ flex: 1 }}>
{t('smart_meter')}
{
this.props.navigation.navigate('Object',{
user:this.props.user
})
}} style={{ flex: 1 }}>
{t('mail_and_parcel')}
{ this.props.navigation.navigate('RepairService',{
user:this.props.user
}) }}*/
onPress={() => { this.props.navigation.navigate('Repair')}}
style={{ flex: 1 }}>
{t('request_repair')}
{this.props.navigation.navigate('Question')}} style={{ flex: 1 }}>
{t('inquire')}
))
}
{
return
}}
ListFooterComponent={() => {
if (!this.state.isLoadmore) return null
return ()
}}
/>
this.setState({visibleNotiElectric: false})}
onPressLater={() => this.setPaymentLater()}
pending_payment={this.state.pending_payment}
due_at_payment={this.state.due_at_payment}
onPress={() => this.setState({
visibleNotiElectric: false
}, () => {
this.props.navigation.navigate('Bill')
this.setPaymentLater()
})}/>
this.setState({visibleNotiOverDue: false})}
onPressLater={() => this.setPaymentLater()}
pending_payment={this.state.pending_payment}
onPress={() => this.setState({
visibleNotiOverDue: false
}, () => {
// this.props.navigation.navigate('Payment', {payment_id: this.state.payment_id})
this.props.navigation.navigate('Bill')
this.setPaymentLater()
})}/>
this.setState({visibleNotiMeter: false})}
onPressLater={() => this.setFillInMeterLater()}
notified_meter_at={this.state.notified_meter_at}
onPress={() => this.setState({
visibleNotiMeter: false
}, () => {
this.props.navigation.navigate('Meter')
this.setFillInMeterLater()
})}
/>
)
}
}
//export default NewsScreen
const styles = StyleSheet.create({
container: {
flex: 1, flexDirection: 'column',
padding: 7
},
row: {
flex: 1, flexDirection: 'row',
},
textNews: {
backgroundColor: '#0D8890',
width: 60,
color: '#FFFFFF',
borderRadius: 5,
textAlign: 'center',
fontSize: 12
},
imgBg: {
flex: 1,
height: 200,
width: width,
justifyContent: 'flex-end'
},
textNewsName: {
color: '#FFFFFF',
fontSize: 18
},
textDate: {
color: 'white',
fontSize: 12,
marginLeft: 5,
marginTop: 10
},
contentContainer: {
paddingVertical: 0,
},
image_style: {
height: 64,
width: 64,
borderRadius: 5,
},
custom_card: {
width: '50%', paddingHorizontal: 5,
// width: '100%'
},
popupNoti: {
backgroundColor: 'white',
justifyContent: 'center',
alignItems: 'center',
borderRadius: 5,
marginHorizontal: 50,
paddingVertical: 20,
paddingHorizontal: 30,
maxWidth: 300,
width: '100%'
},
popupNotiContainer: {
backgroundColor: 'rgba(0,0,0,0.6)',
justifyContent: 'center',
alignItems: 'center',
position: 'absolute',
width: '100%',
height: '100%',
flex: 1
},
costText: {
backgroundColor: '#EFEFF4',
alignItems: 'center',
paddingHorizontal: 20,
paddingVertical: 5,
borderRadius: 5,
width: '100%',
marginBottom: 10
},
badgeCancel: {
backgroundColor: 'white',
alignItems: 'center',
width: '100%'
},
badgeSubmit: {
backgroundColor: '#145EB3',
borderRadius: 5,
marginBottom: 10,
alignItems: 'center',
width: '100%',
height: 'auto'
},
TextFont: {
fontFamily: 'Prompt-Regular',
}
})
const mapDisPatchToProps = state => {
return state.app
}
const setUser = dispatch => bindActionCreators({
appSetToken,
appSetPushToken,
appSetDevice,
appSetUser,
appCleanToken,
appCleanUser,
appSetNotification,
appSetProjectID,
setPaymentLater,
appCleanProjectID
}, dispatch)
export default connect(mapDisPatchToProps, setUser)(NewsScreen)