import React, {Component} from 'react';
import {
View,
Text,
StyleSheet,
Dimensions,
Alert,
PanResponder,
Platform,
BackHandler,
ToastAndroid,
} from 'react-native';
import MyStatistics from '../MyStatistics';
import MyTitle from '../MyTitle';
import SettingButton from '../SettingButton';
import MyBanner from '../MyBanner';
import RangePKState from '../RangePKState';
import {
parseMinute,
parseRangeID,
parseTime,
acID,
rangeID,
websocket,
sno,
parseHour,
} from '../MyUtilities';
const {height} = Dimensions.get('window');
/**
* 标语风格切换共使用了组件:
* 1. GlobalSetting(引入global变量global.bannerStyle,来控制标语风格)
* 2. SettingButton
* 3. BannerStyle(在你的Navigator中引入)
* 4. MyButton(在BannerStyle组件中引入)
* 5. MyBanner
* 6. {bannerStyle} from MyUtilities
*
* 此外,还使用了:
* 1. componentDidMount()
* 2. componentWillUnmount()
*/
class RangePKStudy extends Component {
constructor() {
super();
}
state = {
user: {
id: undefined,
name: 'username',
rank: 'error',
duration: -1,
},
isGoBack: false,
ranking: 1,
timeInTheMatch: 0,
rankingFirst: {
name: 'null',
time: -1,
},
rankingSecond: {
name: 'null',
time: -1,
},
rankingThird: {
name: 'null',
time: -1,
},
};
componentDidMount() {
const {
navigation,
route: {params},
} = this.props;
navigation.setOptions({
// 引入SettingButton组件至header的右边
// 并把this.props传给SettingButton组件以实现Navigation的跳转
headerRight: () => ,
headerBackVisible: false,
});
this.unsubscribeFocus = navigation.addListener('focus', () => {
// Screen was focused
this.setState({isGoBack: false});
// 强制刷新组件,读取最新的bannerStyle
this.forceUpdate();
});
this.unsubscribeBlur = navigation.addListener('blur', () => {
// Screen was blur
this.setState({isGoBack: true});
});
// 以下不是标语风格切换相关
this.parseParams(params);
websocket.onmessage(this.resolveMessage);
if (Platform.OS === 'android') {
BackHandler.addEventListener('hardwareBackPress', this.backEvent);
}
this.startTimer();
}
componentWillUnmount() {
this.unsubscribeFocus();
this.unsubscribeBlur();
// 以下不是标语风格切换相关
if (Platform.OS === 'android') {
BackHandler.removeEventListener('hardwareBackPress', this.backEvent);
}
clearInterval(this.timer);
}
backEvent = () => {
if (this.state.isGoBack) {
this.props.navigation.goBack();
} else {
this.finish();
}
return true;
};
parseParams = params => {
if (
params.hasOwnProperty('nickname') &&
params.hasOwnProperty('dan_name_CH') &&
params.hasOwnProperty('sno') &&
params.hasOwnProperty('study_duration')
) {
if (params.sno === sno.get()) {
const stateName = 'user';
this.setState({
[stateName]: {
name: params.nickname,
id: params.sno,
rank: params.dan_name_CH,
duration: params.study_duration,
},
});
} else {
console.log('wrong userID');
}
} else {
console.log('wrong param');
}
this.setState({timeInTheMatch: 0});
};
resolveError = () => {
this.setState({isGoBack: true});
Alert.alert('错误', '可能与服务器断开连接', [
{
text: '退出对战',
onPress: () => {
acID.quitMatch().then(this.resolveRecord).catch();
this.props.navigation.goBack();
},
style: 'cancel',
},
{
text: '继续对战',
},
]);
};
resolveRankingList = data => {
const array = ['rankingFirst', 'rankingSecond', 'rankingThird'];
let ranking = 0;
for (let i in array) {
this.setState({
[array[i]]: {
name: 'null',
time: -1,
},
});
}
for (let key in data) {
const row = data[key];
if (row.hasOwnProperty('sno')) {
if (row.sno === sno.get()) {
this.setState({ranking: data.length - ranking});
}
}
ranking++;
}
for (let i = 0; i < 3; i++) {
const key = data.length - 1 - i;
if (key < 0) {
break;
} else {
const row = data[key];
if (
row.hasOwnProperty('nickname') &&
row.hasOwnProperty('continued_time')
) {
this.setState({
[array[i]]: {
name: row.nickname,
time: row.continued_time,
},
});
} else {
console.log('wrong row in ranking list');
}
}
}
};
calculateTime = () => {
const {timeInTheMatch} = this.state;
this.setState({
timeInTheMatch: timeInTheMatch + 500,
});
if (timeInTheMatch % 10000 === 0) {
acID
.getRankingList()
.then(this.resolveRankingList)
.catch(this.resolveError);
}
};
startTimer = () => {
this.timer = setInterval(() => {
this.calculateTime();
}, 500);
};
openRankingList = () => {
this.props.navigation.navigate('区域排行榜');
};
panResponder = PanResponder.create({
onStartShouldSetPanResponder: () => true,
onMoveShouldSetPanResponder: () => true,
onPanResponderMove: (event, gestureState) => {
// console.log('onPanResponderMove');
// console.log(
// '滑动参数:dx=' + gestureState.dx + ',dy=' + gestureState.dy,
// );
// console.log(
// '滑动参数:vx=' + gestureState.vx + ',vy=' + gestureState.vy,
// );
if (gestureState.vx < -0.45 && Math.abs(gestureState.dy) < 10) {
this.openRankingList();
}
},
});
resolveRecord = record => {
const params = record;
if (Object.keys(params).length > 0) {
let top = 'ERROR';
let bottom = 'ERROR';
console.log('[QUIT_SUCCESS]', params);
if(params.hasOwnProperty('duration')){
top=params.duration
}
if (
params.hasOwnProperty('start_time') &&
params.hasOwnProperty('end_time')
) {
if (
!isNaN(Date.parse(params.start_time)) &&
!isNaN(Date.parse(params.end_time))
) {
top = parseMinute(
Date.parse(params.end_time) - Date.parse(params.start_time),
);
} else {
console.log(
'[Date.parse](params.start_time)',
Date.parse(params.start_time),
);
console.log(
'[Date.parse](params.end_time)',
Date.parse(params.end_time),
);
}
}
if (params.hasOwnProperty('exp')) {
bottom = params.exp;
}
this.props.navigation.navigate('区域PK结算', {
numberTop: top,
numberCentre: this.state.ranking,
numberBottom: bottom,
range: parseRangeID(),
});
clearInterval(this.timer);
rangeID.set();
acID.set();
} else {
ToastAndroid.show('无法取得对战结果', ToastAndroid.SHORT);
console.log('no params');
}
};
finish = () => {
Alert.alert('结算确认', '您确定要结束PK并结算成绩吗?', [
{
text: '取消',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel',
},
{
text: '是的',
onPress: () => {
//console.log('OK Pressed');
acID.quitMatch().then(this.resolveRecord).catch(this.resolveError);
ToastAndroid.show('正在取得对战结果中', ToastAndroid.SHORT);
},
},
]);
};
render() {
const {
user,
ranking,
timeInTheMatch,
rankingFirst,
rankingSecond,
rankingThird,
} = this.state;
return (
{'<--'}左滑打开排行榜
{parseTime(timeInTheMatch)}
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: '#F2E2CE',
//opacity: 0.5,
flex: 1,
},
containerTitle: {
flex: 1,
},
containerMain: {
flex: 3,
flexDirection: 'row',
},
containerTimer: {
justifyContent: 'center',
flex: 1,
},
containerOnRight: {
borderColor: '#f4cb8c',
backgroundColor: '#BF7636',
},
containerInRightColumn: {
borderColor: '#f4cb8c',
backgroundColor: '#BF7636',
},
textOnRight: {
color: '#f2e2ce',
},
text: {
textAlignVertical: 'center',
color: '#592202',
fontSize: parseInt(height, 10) / 50,
fontWeight: '300',
textAlign: 'center',
},
textTimer: {
textAlignVertical: 'center',
flex: 1,
color: '#592202',
fontSize: parseInt(height, 10) / 12,
fontWeight: 'bold',
textAlign: 'center',
},
myBanner: {
container: {
flex: 2,
},
},
});
export default RangePKStudy;