import React, {Component} from 'react';
import {View, Text, Image} from 'react-native';
import {connect} from 'react-redux';
import Touch from '../components/Touch';
import Speech from '../utils/Speech';
import Smilepay from '../utils/Smilepay';
import Toast from '../components/Toast';
import delay from '../utils/delay';

@connect()
class SmokePage extends Component {
  state = {
    tipText: '触摸屏幕，人脸识别，打开货柜',
  };

  async componentDidMount() {
    this.listen();
  }

  listen = async () => {
    try {
      while (!window.socket) {
        await delay(1000);
      }
      if (!window.socket.hasListeners('doorLogin')) {
        // 扫码验证成功
        window.socket.on('doorLogin', this.handleDoorLogin);
      }
    } catch (e) {
      console.log(e);
    }
  };

  alipayinfo = async () => {
    const {data} = await this.props.dispatch({type: 'goods/alipayinfo'});
    this.alipayInfo = await Smilepay.init(data);
    if (this.alipayInfo.code === '1000')
      this.alipayInfo.metaInfo = JSON.parse(this.alipayInfo.metaInfo);
    return this.alipayInfo;
  };

  handleDoorLogin = async ret => {
    if (ret && ret.msg) {
      Speech.speak(ret.msg);
    }
  };

  smileFace = async () => {
    await this.alipayinfo();
    if (!this.alipayInfo || !this.alipayInfo.metaInfo) {
      this.props.speak('刷脸支付启动失败，请重新刷脸或扫码支付', true);
      return;
    }
    const {data} = await this.props.dispatch({
      type: 'goods/smilepay',
      service_id: 'auth',
      zimmetainfo: this.alipayInfo.metaInfo,
    });
    if (data.code === 1) {
      const res = await Smilepay.verify(JSON.parse(data.data));
      if (res.code !== '1000') {
        Toast.show(res.msg);
        return;
      }
      const ret = await this.props.dispatch({
        type: 'store/wxdoor',
        alipayUid: res.uid,
        fToken: res.fToken,
      });
      this.handleDoorLogin(ret);
    }
  };

  render() {
    const {tipText} = this.state;
    return (
      <View style={styles.container}>
        <Touch onPress={this.smileFace}>
          <Image source={require('../assets/ai/face.gif')} />
        </Touch>
        <Touch style={styles.tip} onPress={this.smileFace}>
          <View style={styles.tip}>
            <Image
              resizeMode="contain"
              style={styles.tipImage}
              source={require('../assets/Jike/alipay.png')}
            />
            <Text style={styles.tipText}>{tipText}</Text>
          </View>
        </Touch>
      </View>
    );
  }
}

const styles = {
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'black',
  },
  tip: {
    position: 'absolute',
    flexDirection: 'row',
    bottom: 0,
    width: '100%',
    height: 80,
    backgroundColor: '#FC4000',
    justifyContent: 'center',
    alignItems: 'center',
  },
  tipImage: {
    width: 60,
  },
  tipText: {
    color: 'white',
    fontSize: 20,
  },
};

export default SmokePage;
