index.js 10.8 KB
Newer Older
ItbGcthate's avatar
ItbGcthate 已提交
1
import React, {Component} from 'react';
ItbGcthate's avatar
ItbGcthate 已提交
2 3 4 5 6 7 8
import {
  View,
  Text,
  StyleSheet,
  Dimensions,
  Alert,
  PanResponder,
ItbGcthate's avatar
ItbGcthate 已提交
9 10 11
  Platform,
  BackHandler,
  ToastAndroid,
ItbGcthate's avatar
ItbGcthate 已提交
12
} from 'react-native';
ItbGcthate's avatar
ItbGcthate 已提交
13 14 15 16 17
import MyStatistics from '../MyStatistics';
import MyTitle from '../MyTitle';
import SettingButton from '../SettingButton';
import MyBanner from '../MyBanner';
import RangePKState from '../RangePKState';
ItbGcthate's avatar
ItbGcthate 已提交
18 19 20 21 22 23
import {
  parseMinute,
  parseRangeID,
  parseTime,
  acID,
  rangeID,
ItbGcthate's avatar
ItbGcthate 已提交
24 25 26
  websocket,
  sno,
  parseHour,
ItbGcthate's avatar
ItbGcthate 已提交
27
} from '../MyUtilities';
ItbGcthate's avatar
ItbGcthate 已提交
28

ItbGcthate's avatar
ItbGcthate 已提交
29
const {height} = Dimensions.get('window');
ItbGcthate's avatar
ItbGcthate 已提交
30 31 32 33 34 35 36
/**
 * 标语风格切换共使用了组件:
 * 1. GlobalSetting(引入global变量global.bannerStyle,来控制标语风格)
 * 2. SettingButton
 * 3. BannerStyle(在你的Navigator中引入)
 * 4. MyButton(在BannerStyle组件中引入)
 * 5. MyBanner
ItbGcthate's avatar
ItbGcthate 已提交
37
 * 6. {bannerStyle} from MyUtilities
ItbGcthate's avatar
ItbGcthate 已提交
38 39 40 41 42 43 44 45 46 47 48
 *
 * 此外,还使用了:
 * 1. componentDidMount()
 * 2. componentWillUnmount()
 */
class RangePKStudy extends Component {
  constructor() {
    super();
  }

  state = {
ItbGcthate's avatar
ItbGcthate 已提交
49
    user: {
ItbGcthate's avatar
ItbGcthate 已提交
50
      id: undefined,
ItbGcthate's avatar
ItbGcthate 已提交
51 52 53 54
      name: 'username',
      rank: 'error',
      duration: -1,
    },
ItbGcthate's avatar
ItbGcthate 已提交
55
    isGoBack: false,
ItbGcthate's avatar
ItbGcthate 已提交
56
    ranking: 1,
ItbGcthate's avatar
ItbGcthate 已提交
57 58
    timeInTheMatch: 0,
    rankingFirst: {
ItbGcthate's avatar
ItbGcthate 已提交
59
      name: 'null',
ItbGcthate's avatar
ItbGcthate 已提交
60 61 62
      time: -1,
    },
    rankingSecond: {
ItbGcthate's avatar
ItbGcthate 已提交
63
      name: 'null',
ItbGcthate's avatar
ItbGcthate 已提交
64 65 66
      time: -1,
    },
    rankingThird: {
ItbGcthate's avatar
ItbGcthate 已提交
67
      name: 'null',
ItbGcthate's avatar
ItbGcthate 已提交
68 69
      time: -1,
    },
ItbGcthate's avatar
ItbGcthate 已提交
70 71 72
  };

  componentDidMount() {
ItbGcthate's avatar
ItbGcthate 已提交
73 74 75 76
    const {
      navigation,
      route: {params},
    } = this.props;
ItbGcthate's avatar
ItbGcthate 已提交
77 78 79 80
    navigation.setOptions({
      // 引入SettingButton组件至header的右边
      // 并把this.props传给SettingButton组件以实现Navigation的跳转
      headerRight: () => <SettingButton {...this.props} />,
ItbGcthate's avatar
ItbGcthate 已提交
81
      headerBackVisible: false,
ItbGcthate's avatar
ItbGcthate 已提交
82
    });
ItbGcthate's avatar
ItbGcthate 已提交
83
    this.unsubscribeFocus = navigation.addListener('focus', () => {
ItbGcthate's avatar
ItbGcthate 已提交
84
      // Screen was focused
ItbGcthate's avatar
ItbGcthate 已提交
85
      this.setState({isGoBack: false});
ItbGcthate's avatar
ItbGcthate 已提交
86
      // 强制刷新组件,读取最新的bannerStyle
ItbGcthate's avatar
ItbGcthate 已提交
87 88
      this.forceUpdate();
    });
ItbGcthate's avatar
ItbGcthate 已提交
89 90 91 92
    this.unsubscribeBlur = navigation.addListener('blur', () => {
      // Screen was blur
      this.setState({isGoBack: true});
    });
ItbGcthate's avatar
ItbGcthate 已提交
93
    // 以下不是标语风格切换相关
ItbGcthate's avatar
ItbGcthate 已提交
94 95 96 97 98
    this.parseParams(params);
    websocket.onmessage(this.resolveMessage);
    if (Platform.OS === 'android') {
      BackHandler.addEventListener('hardwareBackPress', this.backEvent);
    }
ItbGcthate's avatar
ItbGcthate 已提交
99 100 101 102
    this.startTimer();
  }

  componentWillUnmount() {
ItbGcthate's avatar
ItbGcthate 已提交
103 104
    this.unsubscribeFocus();
    this.unsubscribeBlur();
ItbGcthate's avatar
ItbGcthate 已提交
105
    // 以下不是标语风格切换相关
ItbGcthate's avatar
ItbGcthate 已提交
106 107 108
    if (Platform.OS === 'android') {
      BackHandler.removeEventListener('hardwareBackPress', this.backEvent);
    }
ItbGcthate's avatar
ItbGcthate 已提交
109 110 111
    clearInterval(this.timer);
  }

ItbGcthate's avatar
ItbGcthate 已提交
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
  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');
        }
      }
    }
  };

ItbGcthate's avatar
ItbGcthate 已提交
207
  calculateTime = () => {
ItbGcthate's avatar
ItbGcthate 已提交
208
    const {timeInTheMatch} = this.state;
ItbGcthate's avatar
ItbGcthate 已提交
209
    this.setState({
ItbGcthate's avatar
ItbGcthate 已提交
210
      timeInTheMatch: timeInTheMatch + 500,
ItbGcthate's avatar
ItbGcthate 已提交
211
    });
ItbGcthate's avatar
ItbGcthate 已提交
212 213 214 215 216 217
    if (timeInTheMatch % 10000 === 0) {
      acID
        .getRankingList()
        .then(this.resolveRankingList)
        .catch(this.resolveError);
    }
ItbGcthate's avatar
ItbGcthate 已提交
218 219 220 221 222
  };

  startTimer = () => {
    this.timer = setInterval(() => {
      this.calculateTime();
ItbGcthate's avatar
ItbGcthate 已提交
223
    }, 500);
ItbGcthate's avatar
ItbGcthate 已提交
224 225 226 227 228 229
  };

  openRankingList = () => {
    this.props.navigation.navigate('区域排行榜');
  };

ItbGcthate's avatar
ItbGcthate 已提交
230 231 232
  panResponder = PanResponder.create({
    onStartShouldSetPanResponder: () => true,

ItbGcthate's avatar
ItbGcthate 已提交
233
    onMoveShouldSetPanResponder: () => true,
ItbGcthate's avatar
ItbGcthate 已提交
234 235 236 237 238 239 240 241 242

    onPanResponderMove: (event, gestureState) => {
      // console.log('onPanResponderMove');
      // console.log(
      //   '滑动参数:dx=' + gestureState.dx + ',dy=' + gestureState.dy,
      // );
      // console.log(
      //   '滑动参数:vx=' + gestureState.vx + ',vy=' + gestureState.vy,
      // );
ItbGcthate's avatar
ItbGcthate 已提交
243
      if (gestureState.vx < -0.45 && Math.abs(gestureState.dy) < 10) {
ItbGcthate's avatar
ItbGcthate 已提交
244 245 246 247 248
        this.openRankingList();
      }
    },
  });

ItbGcthate's avatar
ItbGcthate 已提交
249 250 251 252 253 254
  resolveRecord = record => {
    const params = record;
    if (Object.keys(params).length > 0) {
      let top = 'ERROR';
      let bottom = 'ERROR';
      console.log('[QUIT_SUCCESS]', params);
YYYTDMS's avatar
YYYTDMS 已提交
255 256 257
      if(params.hasOwnProperty('duration')){
        top=params.duration
      }
ItbGcthate's avatar
ItbGcthate 已提交
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
      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');
    }
  };

ItbGcthate's avatar
ItbGcthate 已提交
298 299 300 301 302 303 304 305 306 307 308
  finish = () => {
    Alert.alert('结算确认', '您确定要结束PK并结算成绩吗?', [
      {
        text: '取消',
        onPress: () => console.log('Cancel Pressed'),
        style: 'cancel',
      },
      {
        text: '是的',
        onPress: () => {
          //console.log('OK Pressed');
ItbGcthate's avatar
ItbGcthate 已提交
309 310
          acID.quitMatch().then(this.resolveRecord).catch(this.resolveError);
          ToastAndroid.show('正在取得对战结果中', ToastAndroid.SHORT);
ItbGcthate's avatar
ItbGcthate 已提交
311 312 313 314 315 316
        },
      },
    ]);
  };

  render() {
ItbGcthate's avatar
ItbGcthate 已提交
317 318 319 320 321 322 323 324
    const {
      user,
      ranking,
      timeInTheMatch,
      rankingFirst,
      rankingSecond,
      rankingThird,
    } = this.state;
ItbGcthate's avatar
ItbGcthate 已提交
325 326

    return (
YYYTDMS's avatar
YYYTDMS 已提交
327
      <View style={styles.container}>
ItbGcthate's avatar
ItbGcthate 已提交
328 329 330 331
        <MyTitle
          title={'当前的排名为 第' + ranking + ''}
          containerStyle={styles.containerTitle}
        />
YYYTDMS's avatar
YYYTDMS 已提交
332
        <View style={styles.containerMain} {...this.panResponder.panHandlers}>
ItbGcthate's avatar
ItbGcthate 已提交
333 334 335 336
          <MyStatistics
            text={{
              first: {
                top: '用户',
ItbGcthate's avatar
ItbGcthate 已提交
337
                bottom: user.name,
ItbGcthate's avatar
ItbGcthate 已提交
338 339 340
              },
              second: {
                top: '段位',
ItbGcthate's avatar
ItbGcthate 已提交
341
                bottom: user.rank,
ItbGcthate's avatar
ItbGcthate 已提交
342 343 344
              },
              third: {
                top: '本次时长',
ItbGcthate's avatar
ItbGcthate 已提交
345
                bottom: parseMinute(timeInTheMatch) + ' min',
ItbGcthate's avatar
ItbGcthate 已提交
346 347 348
              },
              forth: {
                top: '生涯时长',
ItbGcthate's avatar
ItbGcthate 已提交
349
                bottom: parseHour(timeInTheMatch) + user.duration + ' min',
ItbGcthate's avatar
ItbGcthate 已提交
350 351 352
              },
            }}
          />
ItbGcthate's avatar
ItbGcthate 已提交
353
          <RangePKState range={parseRangeID()} />
ItbGcthate's avatar
ItbGcthate 已提交
354 355 356 357 358 359 360
          <MyStatistics
            containerStyle={styles.containerOnRight}
            insideStyle={styles.containerInRightColumn}
            textStyle={styles.textOnRight}
            onPress={this.openRankingList}
            text={{
              first: {
ItbGcthate's avatar
ItbGcthate 已提交
361
                top: parseRangeID() + '区域',
ItbGcthate's avatar
ItbGcthate 已提交
362
                bottom: 'Top 3',
ItbGcthate's avatar
ItbGcthate 已提交
363 364
              },
              second: {
ItbGcthate's avatar
ItbGcthate 已提交
365 366
                top: rankingFirst.name,
                bottom: rankingFirst.time + ' min',
ItbGcthate's avatar
ItbGcthate 已提交
367 368
              },
              third: {
ItbGcthate's avatar
ItbGcthate 已提交
369 370
                top: rankingSecond.name,
                bottom: rankingSecond.time + ' min',
ItbGcthate's avatar
ItbGcthate 已提交
371 372
              },
              forth: {
ItbGcthate's avatar
ItbGcthate 已提交
373 374
                top: rankingThird.name,
                bottom: rankingThird.time + ' min',
ItbGcthate's avatar
ItbGcthate 已提交
375 376 377 378
              },
            }}
          />
        </View>
YYYTDMS's avatar
YYYTDMS 已提交
379
        <View style={styles.containerTimer} {...this.panResponder.panHandlers}>
ItbGcthate's avatar
ItbGcthate 已提交
380
          <Text style={styles.text}>{'<--'}左滑打开排行榜</Text>
ItbGcthate's avatar
ItbGcthate 已提交
381
          <Text style={styles.textTimer}>{parseTime(timeInTheMatch)}</Text>
ItbGcthate's avatar
ItbGcthate 已提交
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
        </View>
        <MyBanner
          containerStyle={styles.myBanner.container}
          title={'结算'}
          onPress={this.finish}
        />
      </View>
    );
  }
}

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',
  },
ItbGcthate's avatar
ItbGcthate 已提交
421 422 423 424 425 426 427
  text: {
    textAlignVertical: 'center',
    color: '#592202',
    fontSize: parseInt(height, 10) / 50,
    fontWeight: '300',
    textAlign: 'center',
  },
ItbGcthate's avatar
ItbGcthate 已提交
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
  textTimer: {
    textAlignVertical: 'center',
    flex: 1,
    color: '#592202',
    fontSize: parseInt(height, 10) / 12,
    fontWeight: 'bold',
    textAlign: 'center',
  },
  myBanner: {
    container: {
      flex: 2,
    },
  },
});

export default RangePKStudy;