/**
 * 网页支付页面
 * @邠心vbe on 2022/01/10
 */
import React, { Component } from 'react';
import { View, AppState, Linking, StyleSheet, Image } from 'react-native';
import * as Progress from 'react-native-progress';
import WebView from 'react-native-webview';
import TextView from '../../components/TextView';
import { PaymentDefault } from './PaymentConfig';

export default class PaymentWeb extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isCallback: false,
      progress: 0,
      paymentInfo: {
        url: '',
        amount: 0,
        type: ''
      }
    };
    this.canBack = false;
    this.stateListener = undefined;
  }

  componentDidMount() {
    const param = this.props.route.params
    console.log('PaymentWeb', param);
    if (param.url) {
      this.setState({
        isCallback: true,
        paymentInfo: param
      }, () => this.init());
    }
    if (!PaymentDefault.enableInnerWebView) {
      this.stateListener = AppState.addEventListener("change", state => {
        if (state == 'active' && this.state.isCallback) {
          //console.log("AppState", state);
          this.completePayment();
        }
      });
    }
    /*this.props.navigation.addListener('beforeRemove', e => {
      if (!this.canBack) {
        if (this.state.isRepay) {
          this.onReset();
          e.preventDefault();
        } else if (this.state.isReturn) {
          this.canBack = true;
          goBack();
          setTimeout(() => {
            goBack();
          }, 100);
        } else {
          this.onClose();
          e.preventDefault();
        }
      }
    })*/
  }

  componentWillUnmount() {
    if (this.stateListener) {
      this.stateListener.remove();
    }
  }

  init() {
    if (!PaymentDefault.enableInnerWebView) {
      setTimeout(() => {
        Linking.openURL(this.state.paymentInfo.url)
      }, 500);
    }
  }

  completePayment() {
    this.setState({
      isCallback: false
    }, () => {
      setTimeout(() => {
        goBack();
      }, 500);
    });
  }

  onPostMessage(data) {
    console.log('WebviewMessage', data)
    this.completePayment();
  }

  render() {
    if (PaymentDefault.enableInnerWebView) {
      return (
        <View style={styles.container}>
          <Progress.Bar
            style={styles.progress}
            width={$vw(100)}
            height={2}
            color={colorPrimaryDark}
            borderWidth={0}
            borderRadius={0}
            progress={this.state.progress}/>
          <WebView
            style={ui.flex1}
            source={{ uri: this.state.paymentInfo.url}}
            mixedContentMode={'always'}
            applicationNameForUserAgent={'vbe_lumi/1.0'}
            onLoadProgress={({nativeEvent}) => this.setState({ progress: nativeEvent.progress }) }
            onLoadEnd={(e) => {
              //console.log('webview-end', e)
              this.setState({ progress: 0 }) 
            }}
            onMessage={e => this.onPostMessage(e.nativeEvent.data)}/>
        </View>
      );
    } else {
      return (
        <View style={styles.container}>
          { this.state.isCallback &&
            <View style={styles.center}>
              <View style={styles.loadingIcon}>
                { isIOS
                ? <Image
                    style={styles.loadingIconImage}
                    source={require('../../images/icon/loading.gif')}/>
                : <Progress.CircleSnail
                    size={56}
                    duration={667}
                    thickness={4}
                    color={[colorAccent]}
                    direction={'clockwise'}
                    spinDuration={2000}/>
                }
              </View>
              <EndView/>
              <TextView style={styles.loadingText}>{$t("nav.loading")}</TextView>
            </View>
          }
        </View>
      )
    }
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: pageBackground
  },
  progress: {
    top: 0,
    left: 0,
    zIndex: 10,
    position: 'absolute'
  },
  center: {
    flex: 1,
    paddingBottom: 56,
    alignItems: 'center',
    justifyContent: 'center'
  },
  loadingText: {
    fontSize: 12,
    color: textSecondary
  },
  loadingIcon: {
    width: 56,
    height: 56,
    overflow: 'hidden',
    borderRadius: 56
  },
  loadingIconImage: {
    width: 56,
    height: 56,
    transform: [{scale: 1.5}]
  }
})