/*
Name:rentchatapplesignin
Key ID:SVU2QA5HAW
Services:Sign in with Apple
*/
import React, {Component} from 'react';
import {
  View,
  Text,
  TouchableHighlight,
  StyleSheet,
  TouchableOpacity,
  Image,
  Keyboard,
  Alert,
  Platform,
} from 'react-native';
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view';
import {GoogleSignin, statusCodes} from '@react-native-community/google-signin';
import NaviBar from '../../components/navi-bar';
import Modal, {ModalContent} from 'react-native-modals';
import Toast, {DURATION} from 'react-native-easy-toast';
import * as WeChat from 'react-native-wechat';
import history from '../../common/history';
import LoadingView from '../../common/loading';
import {scale, verticalScale, moderateScale} from 'react-native-size-matters';
import Icon from 'react-native-vector-icons/FontAwesome5';
import {colors} from '../../assets/styles/colors-theme';
import {Fonts} from '../../assets/styles/fonts-theme';
import CommonTextInput from '../../components/commonTextInput';
import {inject, observer} from 'mobx-react';
import appleAuth, {
  AppleButton,
  AppleAuthRequestOperation,
  AppleAuthRequestScope,
} from '@invertase/react-native-apple-authentication';

import {observable} from 'mobx';
import {width, height} from '../../common/screen';
import Size from '../../common/size';
import {
  AccessToken,
  GraphRequest,
  GraphRequestManager,
  LoginManager,
} from 'react-native-fbsdk';

const size = new Size();

const wechatId = 'wx93de0986eec5fb79';
const wechatAppSecret = 'ce525babc37b62ea57077288ed3fa4fb';

@inject('appStore')
@observer
export default class Signin extends Component {
  static navigationOptions = {
    gesturesEnabled: false,
  };

  @observable
  isWXInstalled = false;

  @observable
  loginData = {
    id: '',
    pwd: '',
  };
  @observable
  changeCharVisable = false;
  constructor(props) {
    super(props);
    this.store = props.appStore;
  }

  async componentWillMount() {
    await this.store.loadLocalData();
    await WeChat.registerApp(wechatId);
    WeChat.isWXAppInstalled().then(isInstalled => {
      this.isWXInstalled = isInstalled;
      if (isInstalled) {
        this.isWXInstalled = true;
        console.log('微信已经安装');
      } else {
        console.log('微信未安装');
      }
    });
  }

  componentDidMount() {
    this._configureGoogleSignIn();
  }
  loginWithFacebook() {
    // Attempt a login using the Facebook login dialog asking for default permissions.
    this.store.loading = true;
    LoginManager.logInWithPermissions(['public_profile', 'email']).then(
      login => {
        this.store.loading = false;
        if (login.isCancelled) {
          console.log('Login cancelled');
        } else {
          AccessToken.getCurrentAccessToken().then(data => {
            const accessToken = data.accessToken.toString();
            data = {
              platform: 'facebook',
              token: accessToken,
              chara: this.store.user.memberType == 0 ? 'owner' : 'tenant',
            };
            this.store.thirdPartyLogin(
              data,
              this,
              !this.props.navigation.state.params.icon,
            );
            //  Alert.alert( JSON.stringify(accessToken))
            console.log(accessToken);
            //  this.getInfoFromToken(accessToken);
          });
        }
      },
      error => {
        this.store.loading = false;
        console.log('Login fail with error: ' + JSON.stringify(error));
        Alert.alert('fblogin', JSON.stringify(error));
      },
    );
  }

  loginWithWeChat() {
    if (!this.isWXInstalled) {
      this.refs.toast.show('微信未安装');
      return;
    }
    WeChat.sendAuthRequest('snsapi_userinfo', 'wechat_sdk_demo')
      .then(response => {
        this.getOpenId(response.code);
      })
      .catch(error => {
        console.log(error);
        let errorCode = Number(error.code);
        if (errorCode === -2) {
          // this.showAlert('已取消授权登录'); // errorCode = -2 表示用户主动取消的情况，下同
          this.refs.toast.show('已取消授權登錄');
        } else {
          this.refs.toast.show('微信授權登錄失敗');
        }
      });
  }

  async loginWithGoogle() {
    try {
      this.store.loading = true;
      await GoogleSignin.hasPlayServices();
      const userInfo = await GoogleSignin.signIn();
      console.log(userInfo.idToken);
      const isSignedIn = await GoogleSignin.getTokens();
      console.log(isSignedIn.accessToken);
      var data = {
        platform: 'google',
        token: isSignedIn.accessToken,
        chara: this.store.user.memberType == 0 ? 'owner' : 'tenant',
      };
      this.store.loading = false;
      this.store.thirdPartyLogin(
        data,
        this,
        !this.props.navigation.state.params.icon,
      );
    } catch (error) {
      this.store.loading = false;
      if (error.code === statusCodes.SIGN_IN_CANCELLED) {
        console.log(' user cancelled the login flow')
        // user cancelled the login flow
      } else if (error.code === statusCodes.IN_PROGRESS) {
        console.log('operation (e.g. sign in) is in progress already')
        // operation (e.g. sign in) is in progress already
      } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
        console.log('play services not available or outdated')
        // play services not available or outdated
      } else {
        console.log(error)
        // some other error happened
      }
    }
  }

  _configureGoogleSignIn() {
    GoogleSignin.configure({
      webClientId:
        '637211616323-d98smjtash81psfek6cm6ikk39s30j5d.apps.googleusercontent.com',
      offlineAccess: false,
    });
  }

  getInfoFromToken = token => {
    const PROFILE_REQUEST_PARAMS = {
      fields: {
        string: 'email,id,name',
      },
    };
    const profileRequest = new GraphRequest(
      '/me',
      {token, parameters: PROFILE_REQUEST_PARAMS},
      (error, user) => {
        if (error) {
          console.log('login info has error: ' + error);
        } else {
          this.setState({userInfo: user});
          console.log('result:', user);
          // Alert.alert(JSON.stringify(user))
        }
      },
    );
    new GraphRequestManager().addRequest(profileRequest).start();
  };

  loginAction() {
    if (this.loginData.id !== '') {
      if (this.loginData.pwd !== '') {
        console.log(!this.props.navigation.state.params.icon);
        this.store.loginPost(
          this.loginData,
          this,
          !this.props.navigation.state.params.icon,
        );
      } else {
        this.refs.toast.show('Please input your password');
      }
    } else {
      this.refs.toast.show('Please input your Email');
    }
  }

  async loginWithApple() {
    this.store.loading = true;
    try {
      // performs login request
      const appleAuthRequestResponse = await appleAuth.performRequest({
        requestedOperation: AppleAuthRequestOperation.LOGIN,
        requestedScopes: [
          AppleAuthRequestScope.EMAIL,
          AppleAuthRequestScope.FULL_NAME,
        ],
      });

      if (appleAuthRequestResponse['realUserStatus']) {
        var data = {
          identityToken: appleAuthRequestResponse.identityToken,
          chara: this.store.user.memberType == 0 ? 'owner' : 'tenant',
        };
        this.store.loading = false;
        this.store.signinWithApple(
          data,
          this,
          !this.props.navigation.state.params.icon,
        );
      }
    } catch (error) {
      this.store.loading = false;
      if (error.code === AppleAuthError.CANCELED) {
      }
      if (error.code === AppleAuthError.FAILED) {
        alert('Touch ID wrong');
      }
      if (error.code === AppleAuthError.INVALID_RESPONSE) {
        alert('Touch ID wrong');
      }
      if (error.code === AppleAuthError.NOT_HANDLED) {
      }
      if (error.code === AppleAuthError.UNKNOWN) {
        alert('Touch ID wrong');
      }
    }
  }

  getOpenId(code) {
    let requestUrl =
      'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' +
      wechatId +
      '&secret=' +
      wechatAppSecret +
      '&code=' +
      code +
      '&grant_type=authorization_code';
    fetch(requestUrl)
      .then(response => response.json())
      .then(json => {
        console.log('获取微信openid成功');
        console.log(json);
        this.getUnionId(json.access_token, json.openid);
      })
      .catch(error => {
        console.log(error);

        this.refs.toast.show('微信登錄失敗');
      });
  }

  getUnionId(accessToken, openId) {
    let requestUrl =
      'https://api.weixin.qq.com/sns/userinfo?access_token=' +
      accessToken +
      '&openid=' +
      openId;
    fetch(requestUrl)
      .then(response => response.json())
      .then(json => {
        console.log('获取微信unionid成功');
        console.log(json);
        // var data = {
        //   tpid: json.unionid,
        //   tppf: 'wechat',
        //   fullname: json.nickname,
        //   avatar: json.headimgurl,
        //   email: '',
        //   nonce: this.store.genNonce(),
        // };
        this.store.signinWithWeChat(
          json,
          this,
          !this.props.navigation.state.params.icon,
        );

        // TODO: 这里openId和unionId都已经成功获取了，调用用户自己的接口传递openId或unionId登录或注册
        // put your login method here...
      })
      .catch(error => {
        this.progressHUD.hide();
        this.refs.toast.show('微信登錄失敗');
      });
  }

  otherLogin(which) {
    switch (which) {
      case 'facebook':
        this.loginWithFacebook();
        break;
      case 'google':
        this.loginWithGoogle();
        break;
      case 'wechat':
        this.loginWithWeChat();
        break;
      case 'apple':
        this.loginWithApple();
        break;
    }
  }

  render() {
    var thirdPartyLoginButtons = [
      {
        text: this.store.text.googleLogin,
        icon: 'google',
        color: '#2D9AFF',
        which: 'google',
      },
      {
        text: this.store.text.facebookLogin,
        icon: 'facebook-square',
        color: '#295BA2',
        which: 'facebook',
      },
      {
        text: this.store.text.wechatLogin,
        icon: 'weixin',
        color: '#00E86E',
        which: 'wechat',
      },
    ];

    if (Platform.OS === 'ios') {
      thirdPartyLoginButtons.push({
        text: this.store.text.appleLogin,
        icon: 'apple',
        color: 'black',
        which: 'apple',
      });
    }
    return (
      <View style={{flex: 1, backgroundColor: 'white'}}>
        <LoadingView visible={this.store.loading} />
        <View
          style={{
            flex: 0.4,
            backgroundColor: colors.mainColor,
            justifyContent: 'center',
            alignItems: 'center',
          }}>
          <Image source={require('../../assets/images/logo.png')} />
          <View style={{position: 'absolute', top: 10, left: 5}}>
            {this.props.navigation.state.params.icon ? (
              <TouchableOpacity
                onPress={() => {
                  history.goBack(this);
                }}
                style={{
                  marginLeft: 10,
                  justifyContent: 'center',
                  alignItems: 'center',
                  height: 40,
                  width: 40,
                }}>
                <Icon name={'arrow-left'} size={22} color={'white'} />
              </TouchableOpacity>
            ) : (
              <View></View>
            )}
          </View>
        </View>
        <View style={{flex: 1, width: width}}>
          <KeyboardAwareScrollView>
            <CommonTextInput
              placeholder={this.store.text.email}
              value={this.loginData.email}
              onChangeText={id => (this.loginData.id = id)}
              returnKeyType={'next'}
              secureTextEntry={false}
              onSubmitEditing={event => {
                this.passwordinput.focus();
              }}
            />
            <CommonTextInput
              placeholder={this.store.text.password}
              secureTextEntry={true}
              value={this.loginData.pwd}
              onChangeText={pwd => (this.loginData.pwd = pwd)}
              returnKeyType={'done'}
              inputRef={input => {
                this.passwordinput = input;
              }}
              onSubmitEditing={event => {
                Keyboard.dismiss();
              }}
            />
            <View style={{width: width, alignItems: 'flex-end', marginTop: 10}}>
              <TouchableHighlight
                style={{marginRight: 30}}
                onPress={() => {
                  history.push(this, '/forgotPassword');
                }}>
                <Text style={styles.textView}>
                  {this.store.text.forgotPassword}
                </Text>
              </TouchableHighlight>
            </View>

            <TouchableHighlight
              disabled={this.store.loading}
              style={styles.buttonView}
              onPress={() => {
                this.loginAction();
              }}>
              <Text style={styles.buttonText}>{this.store.text.login}</Text>
            </TouchableHighlight>
            <View style={{marginTop: 20}}>
              {thirdPartyLoginButtons.map((buttons, index) => {
                if (index == 2) {
                  if (this.isWXInstalled) {
                    return (
                      <TouchableOpacity
                        style={{
                          backgroundColor: 'white',
                          flexDirection: 'row',
                          marginRight: 30,
                          marginLeft: 30,
                          marginTop: 10,
                        }}
                        onPress={() => {
                          this.otherLogin(buttons.which);
                        }}>
                        <View
                          style={{
                            flex: 0.2,
                            backgroundColor:
                              index == 3 ? 'black' : buttons.color,
                            height: 40,
                            borderColor: colors.mainColor,
                            borderBottomLeftRadius: 10,
                            borderTopLeftRadius: 10,
                            alignItems: 'center',
                            justifyContent: 'center',
                          }}>
                          <Icon
                            name={buttons.icon}
                            style={{color: 'white'}}
                            size={22}
                          />
                        </View>

                        <View
                          style={{
                            justifyContent: 'center',
                            alignItems: 'center',
                            flex: 1,
                            borderWidth: 0.5,
                            borderColor: index == 3 ? 'black' : buttons.color,
                            borderBottomRightRadius: 10,
                            borderTopRightRadius: 10,
                          }}>
                          <Text
                            style={{
                              fontSize: 15,
                              fontFamily: Fonts.ubuntu,
                              color: index == 3 ? 'black' : colors.mainColor,
                              alignItems: 'center',
                            }}>
                            {buttons.text}
                          </Text>
                        </View>
                      </TouchableOpacity>
                    );
                  } else {
                    return <View />;
                  }
                } else {
                  return (
                    <TouchableOpacity
                      style={{
                        backgroundColor: 'white',
                        flexDirection: 'row',
                        marginRight: 30,
                        marginLeft: 30,
                        marginTop: 10,
                      }}
                      onPress={() => {
                        this.otherLogin(buttons.which);
                      }}>
                      <View
                        style={{
                          flex: 0.2,
                          backgroundColor: index == 3 ? 'black' : buttons.color,
                          height: 40,
                          borderColor: colors.mainColor,
                          borderBottomLeftRadius: 10,
                          borderTopLeftRadius: 10,
                          alignItems: 'center',
                          justifyContent: 'center',
                        }}>
                        <Icon
                          name={buttons.icon}
                          style={{color: 'white'}}
                          size={22}
                        />
                      </View>

                      <View
                        style={{
                          justifyContent: 'center',
                          alignItems: 'center',
                          flex: 1,
                          backgroundColor: index == 3 ? 'black' : 'white',
                          borderWidth: 0.5,
                          borderColor: index == 3 ? 'black' : buttons.color,
                          borderBottomRightRadius: 10,
                          borderTopRightRadius: 10,
                        }}>
                        <Text
                          style={{
                            fontSize: 15,
                            fontFamily: Fonts.ubuntu,
                            color: index == 3 ? 'white' : colors.mainColor,
                            alignItems: 'center',
                          }}>
                          {buttons.text}
                        </Text>
                      </View>
                    </TouchableOpacity>
                  );
                }
              })}
            </View>
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'center',
                marginTop: 30,
              }}>
              <Text style={styles.textView}>{this.store.text.donthaveac}</Text>
              <TouchableOpacity
                onPress={() => {
                  history.push(this, '/signup', {
                    type: this.props.navigation.state.params.icon,
                  });
                }}>
                <Text
                  style={{
                    color: colors.textColor,
                    fontSize: 13,
                    fontFamily: Fonts.ubuntu,
                    marginLeft: 10,
                  }}>
                  {this.store.text.signup}
                </Text>
              </TouchableOpacity>
            </View>
            <TouchableOpacity
              onPress={() => {
                this.changeCharVisable = true;
              }}
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'center',
                marginTop: 10,
              }}>
              <Text style={styles.textView}>{this.store.text.changechar}</Text>
            </TouchableOpacity>
          </KeyboardAwareScrollView>
          <Modal
            visible={this.changeCharVisable}
            width={0.7}
            height={0.5}
            onTouchOutside={() => {
              this.changeCharVisable = false;
            }}
            swipeDirection={['up', 'down']} // can be string or an array
            swipeThreshold={200} // default 100
            onSwipeOut={event => {
              this.changeCharVisable = false;
            }}>
            <ModalContent style={{backgroundColor: colors.mainColor}}>
              <View
                style={{
                  backgroundColor: colors.mainColor,
                  alignItems: 'center',
                }}>
                <TouchableOpacity
                  style={{
                    justifyContent: 'center',
                    alignItems: 'center',
                    marginTop: 20,
                  }}
                  onPress={() => {
                    this.changeCharVisable = false;
                    this.store.changeChar(this, 0);
                  }}>
                  <Image
                    source={require('../../assets/images/owner.png')}
                    overlayColor={colors.mainColor}
                  />

                  <Text style={[styles.selectCharTextView, {marginTop: 10}]}>
                    {this.store.text.owner}
                  </Text>
                </TouchableOpacity>

                <TouchableOpacity
                  style={{
                    height: 200,
                    width: 200,
                    marginTop: 20,
                    justifyContent: 'center',
                    alignItems: 'center',
                  }}
                  onPress={() => {
                    this.changeCharVisable = false;
                    this.store.changeChar(this, 1);
                  }}>
                  <Image source={require('../../assets/images/tenant.png')} />

                  <Text style={[styles.selectCharTextView, {marginTop: 10}]}>
                    {this.store.text.tenant}
                  </Text>
                </TouchableOpacity>
              </View>
            </ModalContent>
          </Modal>
        </View>
        <Toast
          ref="toast"
          style={{backgroundColor: colors.mainColor}}
          position="bottom"
          positionValue={200}
          fadeInDuration={750}
          fadeOutDuration={2000}
          opacity={0.8}
          textStyle={{color: 'white'}}
        />
      </View>
    );
  }
}

const styles = StyleSheet.flatten({
  textView: {
    color: colors.textColor,
    fontFamily: Fonts.ubuntuL,
    fontSize: 13,
  },
  selectCharTextView: {
    color: colors.textColor,
    fontFamily: Fonts.ubuntu,
    fontSize: 17,
  },

  buttonText: {
    color: '#fff',
  },
  buttonView: {
    backgroundColor: colors.mainColor,
    marginRight: 30,
    marginLeft: 30,
    marginTop: 10,
    height: 50,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 10,
  },
  buttonText: {
    fontSize: 15,
    fontFamily: Fonts.ubuntu,
    color: 'white',
  },
});
