/**
 * 新版钱包充值页面
 * @邠心vbe on 2023/02/02
 */
import React, { Component } from 'react';
import { View, Text, ScrollView, StyleSheet, Switch } from 'react-native';
import apiWallet from '../../api/apiWallet';
import BadgeSelectItem from '../../components/BadgeSelectItem';
import Button, { ElevationObject } from '../../components/Button';
import Dialog from '../../components/Dialog';
import { PaymentDefault } from '../payment/PaymentConfig';
import { PageList } from '../Router';
import { Balance } from './Payment';
import TopupPaythod from './TopupPaythod';

export default class TopupNew extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isAuto: false,
      topupList: [],
      selectIndex: 0,
      payType: {},
      balance: 0,
    };
  }

  componentDidMount() {
    this.props.navigation.addListener('focus', () => {
      getUserInfo(info => {
        this.setState({
          balance: info.credit
        })
      }, true);
    });
    this.getTopupList();
  }

  getTopupList() {
    Dialog.showProgressDialog();
    // apiWallet.getTopUpAmountList()
    apiWallet.getTopUpAmountListV2().then(res => {
      Dialog.dismissLoading();
      if (res.data.length > 0) {
        this.setState({
          topupList: res.data
        });
      }
    }).catch(err => {
      toastShort(err)
      const data = apiWallet.getTempAmountListV2();
      this.setState({
        topupList: data
      });
      Dialog.dismissLoading();
    })
  }

  /**
   * 2C2P充值
   */
  topup2() {
    const topup = this.state.topupList[this.state.selectIndex]
    const params = {
      currency: topup?.currency,
      payAmount: topup?.amount
    }
    apiWallet.doPaymentV2(params).then(res => {
      Dialog.dismissLoading();
      if (res.data.webPaymentUrl) {
        startPage(PageList.paymentWeb, { amount: params.payAmount, url: res.data.webPaymentUrl, type: 'Topup' });
      } else {
        toastShort('Error 0')
      }
    }).catch(err => {
      Dialog.dismissLoading();
      toastShort(err);
    });
  }

  /**
   * FOMO充值
   */
  topup() {
    const topup = this.state.topupList[this.state.selectIndex]
    const params = {
      currency: topup?.currency,
      payAmount: topup?.amount,
      fomoPayType: this.state.payType.fomoPayType
    }
    //console.log('params',params);
    if (params.payAmount) {
      if (params.fomoPayType == 'PAYNOW' || params.fomoPayType == 'GRABPAY') {
        //PAYNOW支付
        Dialog.showProgressDialog();
        apiWallet.doPayment(params).then(res => {
          Dialog.dismissLoading();
          if (res.data.fomoId && res.data.qrCodeInBase64) {
            startPage(PageList.paynow, { amount: params.payAmount, base64: res.data.qrCodeInBase64 });
          } else if (res.data.url) {
            startPage(PageList.paymentWeb, { amount: params.payAmount, url: res.data.url, type: 'Topup' });
          } else {
            toastShort('Error 0')
          }
        }).catch(err => {
          Dialog.dismissLoading();
          toastShort(err);
        });
      } else {
        //信用卡支付
        startPage(PageList.formCard, { amount: params.payAmount, payType: params.fomoPayType });
      }
    } else {
      toastShort('Error 1')
    }
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.headerView}>
          <Balance balanceText={this.state.balance}/>
        </View>
        <View style={styles.contentView}>
          <View style={styles.topupView}>
            <WalletTitle>{$t('wallet.titleChooseCreditValue')}</WalletTitle>
            <View style={styles.topupItems}>
              { this.state.topupList.map((item, index) => {
                  return (
                    <BadgeSelectItem
                      key={index}
                      style={[styles.topupItem, index > 0 && styles.right]}
                      checked={index == this.state.selectIndex}
                      onPress={() => {
                        this.setState({
                          selectIndex: index
                        })
                      }}>
                      <Text style={[styles.topupText, index == this.state.selectIndex && {color: colorAccent}]}>
                        {item.amount}
                        <Text style={{fontSize: 16}}> {item.currency}</Text>
                      </Text>
                    </BadgeSelectItem>

                  );
                })
              }
            </View>
          </View>
          { !PaymentDefault.is2c2p &&
            <View style={styles.topupView}>
              <WalletTitle>{$t('wallet.titleChoosePaymentType')}</WalletTitle>
              <TopupPaythod
                onChange={type => {
                  this.setState({
                    payType: type
                  });
                }}/>
            </View>
          }
        </View>
        <View style={ui.flex1}></View>
        <View style={styles.buttonView}>
          <Button
            text={$t('wallet.btnPurchase')}
            elevation={1.5}
            onClick={() => {
              PaymentDefault.is2c2p 
              ? this.topup2()
              : this.topup()
            }}/>
        </View>
      </View>
    );
  }
}

export const WalletTitle = ({children}) => {
  return (
    <View style={styles.topupTitle}>
      {/* <Text style={styles.titleLeft}></Text> */}
      <Text style={styles.titleText}>{children}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: pageBackground
  },
  headerView: {
    paddingBottom: 76,
    //backgroundColor: colorAccent
  },
  contentView: {
    padding: 16,
    marginTop: -88
  },
  topupView: {
    marginBottom: 16
  },
  topupViewOld: {
    padding: 16,
    borderRadius: 10,
    marginBottom: 16,
    backgroundColor: colorLight
  },
  topupTitle: {
    marginBottom: 16,
    alignItems: 'center',
    flexDirection: 'row'
  },
  titleLeft: {
    width: 4,
    height: 15,
    borderRadius: 16,
    backgroundColor: colorPrimary
  },
  titleText: {
    color: textPrimary,
    fontSize: 16,
    paddingLeft: 0,
    fontWeight: 'bold',
    textShadowOffset: {
      width: 0,
      height: 1
    },
    textShadowRadius: 4,
    textShadowColor: "rgba(0, 0, 0, 0.25)",
  },
  subTitle: {
    color: textPrimary,
    fontSize: 14,
    marginTop: 16,
    marginBottom: 16
  },
  topupItems: {
    paddingBottom: 16,
    alignItems: 'center',
    flexDirection: 'row'
  },
  topupItem: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: colorLight,
    ...ElevationObject(5)
  },
  topupText: {
    fontSize: 18,
    color: textPrimary,
    ...$padding(20, 0)
  },
  right: {
    marginLeft: 16
  },
  selected: {
    color: textLight,
    borderColor: colorDark,
    backgroundColor: colorPrimary
  },
  autoView: {
    flex: 1,
    color: textPrimary,
    fontSize: 14,
    paddingRight: 32
  },
  buttonView: {
    padding: 16,
    marginTop: 0,
    marginBottom: 16
  }
})