import React, {Component} from 'react';
import {View, Text, Image} from 'react-native';
import QRCode from 'react-native-qrcode-svg';
import io from 'socket.io-client';
import axios from 'axios';
import {counterLogin} from '../utils/authLogin';
import config from '../utils/config';

class AuthPage extends Component {
  state = {};

  async componentDidMount() {
    this.socket = io(axios.defaults.baseURL);
    this.socket.on('storeAuth', this.handleLogin);
    this.socket.on('connect', () => {
      this.setState({socket: this.socket.id});
    });
    this.socket.on('disconnect', () => {
      this.socket.connect();
    });
  }

  handleLogin = async values => {
    this.setState({loading: true});
    if (!values.host) {
      values.host = config.host;
    }
    values.login = values.device;
    await counterLogin(values);
  };

  render() {
    const {socket} = this.state;
    return (
      <View style={styles.container}>
        <View style={styles.title}>
          <Image
            style={styles.titleImg}
            source={require('../assets/logo2.png')}
            resizeMode="contain"
          />
          <Image
            style={{marginLeft: 20}}
            source={require('../assets/Vertical/24h.png')}
          />
          <Text style={styles.titleText}>仲马购人工智能</Text>
        </View>
        <View style={styles.qrcode}>
          <QRCode
            size={350}
            logo={require('../assets/logo.png')}
            logoBackgroundColor="#FC4000"
            backgroundColor="white"
            value={`${config.qrHost}/#/store-auth-${socket}`}
          />
        </View>
      </View>
    );
  }
}

const styles = {
  title: {
    top: 0,
    paddingLeft: 30,
    flexDirection: 'row',
    height: 100,
    width: '100%',
    position: 'absolute',
    backgroundColor: 'white',
    alignItems: 'center',
    elevation: 10,
  },
  titleImg: {
    width: 80,
    height: 80,
  },
  titleText: {
    color: '#333',
    fontSize: 40,
    marginLeft: 30,
  },
  container: {
    flex: 1,
    backgroundColor: '#F5F5F5',
    justifyContent: 'center',
    alignItems: 'center',
  },
  qrcode: {
    padding: 10,
    backgroundColor: 'white',
    elevation: 5,
  },
};

export default AuthPage;
