/**
 * 选择支付方式页面
 * @邠心vbe on 2022/01/10
 */
import React, { Component } from 'react';
import { View, Text, StyleSheet, Pressable, Image } from 'react-native';
import apiWallet from '../../api/apiWallet';
import Button from '../../components/Button';
import Dialog from '../../components/Dialog';
import ChargeItemSelect from '../../icons/ChargeItemSelect';
import { PageList } from '../Router';
import { PaymentDefault, PAYTYPE } from '../wallet/Payment';
import { WalletTitle } from '../wallet/Topup';

export default class PaymentMethod extends Component {
  constructor(props) {
    super(props);
    this.state = {
      cIndex: 0,
      selectIndex: 0,
      paymentOptions: [{
        title: "Credits",
        desc: '',
        value: PAYTYPE.CREDIT_WALLET,
        icon: require('../../images/icon/draw-wallet.png')
      }],
      paymentOptionsWallet: [{
        title: "Credits",
        desc: '',
        value: PAYTYPE.CREDIT_WALLET,
        icon: require('../../images/icon/draw-wallet.png')
      }, {
        title: "Pay Per Use",
        desc: '(SGQR)',
        value: PAYTYPE.PAY_PER_USE,
        icon: require('../../images/wallet/ic_payperuse.png')
      }],
      paymentOptionsUse: [{
        title: "Pay Per Use",
        desc: '(SGQR)',
        value: PAYTYPE.PAY_PER_USE,
        icon: require('../../images/wallet/ic_payperuse.png')
      }, {
        title: "Credits",
        desc: '',
        value: PAYTYPE.CREDIT_WALLET,
        icon: require('../../images/icon/draw-wallet.png')
      }],
      amountList: [{
        amount: 10,
        power: 0
      }, {
        amount: 20,
        power: 0
      }, {
        amount: 40,
        power: 0
      }],
      connectorInfo: {}
    };
    this.rate = 0
    this.ENABLE_2C2P = PaymentDefault.is2c2p;
    this.FirstPayPerUse = PaymentDefault.DEFAULT.payType == PAYTYPE.PAY_PER_USE;
  }

  componentDidMount() {
    /*this.setState({
      paymentOptions: this.FirstPayPerUse ? this.state.paymentOptionsUse : this.state.paymentOptionsWallet
    });*/
    const params = this.props.route.params;
    const info = params.info ?? {};
    console.log('----params----', params);
    if (info.rate && params.type) {
      this.rate = info.rate;
      this.setState({
        connectorInfo: info,
        cIndex: (params.type == PAYTYPE.CREDIT_WALLET) ? 0 : 1
      });
      this.calculatePower();
    }
  }

  calculatePower() {
    if (this.rate > 0) {
      this.state.amountList.forEach(item => {
        item.power = (item.amount / this.rate).toFixed(0)
      });
    }
  }

  changePayType(index) {
    this.setState({
      cIndex: index
    })
  }

  onConfirm() {
    const info = this.state.paymentOptions[this.state.cIndex];
    global.paymentOption = {
      title: info.title,
      value: info.value
    };
    if (info.value == PAYTYPE.CREDIT_WALLET) {
      goBack();
    } else {
      const amount = this.state.amountList[this.state.selectIndex].amount;
      global.paymentOption.amount = amount;
      const params = {
        payAmount: amount,
        fomoPayType: "PAYNOW",
        paymentOption: info.value,
        chargeBoxId: this.state.connectorInfo.chargeBoxId,
        connectorId: this.state.connectorInfo.connectorId
      }
      //console.log('params',params);
      if (params.payAmount) {
        //PAYNOW支付
        Dialog.showProgressDialog();
        apiWallet.doPayment(params).then(res => {
          Dialog.dismissLoading();
          if (res.data.fomoId && res.data.qrCodeInBase64) {
            startPage(PageList.payPeruse, { amount: params.payAmount, base64: res.data.qrCodeInBase64 });
          } else {
            toastShort('Error 0')
          }
        }).catch(err => {
          Dialog.dismissLoading();
          toastShort(err);
        });
      } else {
        toastShort('Error 1')
      }
    }
  }

  onConfirmV2() {
    const info = this.state.paymentOptions[this.state.cIndex];
    global.paymentOption = {
      title: info.title,
      value: info.value
    };
    if (info.value == PAYTYPE.CREDIT_WALLET) {
      goBack();
    } else {
      const amount = this.state.amountList[this.state.selectIndex].amount;
      global.paymentOption.amount = amount;
      const params = {
        payAmount: amount,
        fomoPayType: "PAYNOW",
        paymentOption: info.value,
        paymentChannel: "SGQR",
        chargeBoxId: this.state.connectorInfo.chargeBoxId,
        connectorId: this.state.connectorInfo.connectorId
      }
      //console.log('params',params);
      if (params.payAmount) {
        //PAYNOW支付
        Dialog.showProgressDialog();
        apiWallet.doPaymentV2(params).then(res => {
          Dialog.dismissLoading();
          if (res.data.webPaymentUrl) {
            startPage(PageList.paymentWeb, { amount: params.payAmount, url: res.data.webPaymentUrl, type: 'PayPerUse' });
          } else {
            toastShort('Error 0')
          }
        }).catch(err => {
          Dialog.dismissLoading();
          toastShort(err);
        });
        /*apiWallet.doPayment(params).then(res => {
          Dialog.dismissLoading();
          if (res.data.fomoId && res.data.qrCodeInBase64) {
            startPage(PageList.payPeruse, { amount: params.payAmount, base64: res.data.qrCodeInBase64 });
          } else {
            toastShort('Error 0')
          }
        }).catch(err => {
          Dialog.dismissLoading();
          toastShort(err);
        });*/
      } else {
        toastShort('Error 2')
      }
    }
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.headerView}>
          <Text></Text>
        </View>
        <View style={styles.contentView}>
          <View style={styles.optionView}>
            <WalletTitle>Payment Option</WalletTitle>
            <Text style={styles.subTitle}>Pay with: </Text>
            { this.state.paymentOptions.map((item, index) => {
              return (
                <Pressable
                  key={index}
                  style={[
                    styles.paytypeView,
                    index > 0 && styles.next,
                    index == this.state.cIndex && styles.selected
                  ]}
                  onPress={() => {
                    this.changePayType(index);
                  }}>
                  <Image
                    style={styles.accountLogo}
                    source={item.icon}/>
                  <Text style={styles.paytypeText}>
                    {item.title} {' '}
                    {item.desc ? item.desc : '(Balance '+currency+userInfo.credit+')'}
                  </Text>
                  <View style={styles.selectIcon}>
                    <ChargeItemSelect size={18} selected={index == this.state.cIndex} tint={colorPrimary}/>
                  </View>
                </Pressable>
              );
            })
          }
          </View>
          { (this.state.cIndex == (this.FirstPayPerUse ? 0 : 1)) &&
            <View style={[styles.optionView, ui.flex1]}>
              <WalletTitle>Pay Per Use</WalletTitle>
              <Text style={styles.subTitle}>Choose Amount:</Text>
              <View style={styles.amountItems}>
                { this.state.amountList.map((item, index) => {
                    return (
                      <Pressable
                        key={index}
                        style={[
                          styles.amountItem,
                          index > 0 && styles.right,
                          index == this.state.selectIndex && styles.amountSelect]}
                        onPress={() => {
                          this.setState({
                            selectIndex: index
                          })
                        }}>
                        <Text
                          style={index == this.state.selectIndex ? styles.amountActive : styles.amountText}>
                          {currency}{item.amount}
                        </Text>
                        <Text style={index == this.state.selectIndex ? styles.powerTextActive : styles.powerText}>~{item.power}kWh</Text>
                      </Pressable>
                    );
                  })
                }
              </View>
              <Text style={ui.flex1}></Text>
              <Text style={styles.warningText}>Un-utilized amount will be refunded.</Text>
            </View>
          }
        </View>
        <Button
          text="Confirm"
          style={$margin(16)}
          onClick={() => this.ENABLE_2C2P ? this.onConfirmV2() : this.onConfirm()}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5F5F5'
  },
  headerView: {
    paddingBottom: 76,
    //backgroundColor: colorAccent
  },
  contentView: {
    flex: 1,
    padding: 16,
    marginTop: -80,
    marginBottom: -20
  },
  optionView: {
    padding: 16,
    borderRadius: 10,
    marginBottom: 16,
    backgroundColor: 'white'
  },
  subTitle: {
    color: '#333',
    fontSize: 14,
    marginTop: 16,
    marginBottom: 16
  },
  paytypeView: {
    padding: 16,
    borderWidth: 1,
    borderColor: '#eee',
    borderRadius: 10,
    alignItems: 'center',
    flexDirection: 'row',
    backgroundColor: '#F5F5F5'
  },
  selected: {
    borderColor: colorPrimary
  },
  next: {
    marginTop: 16,
  },
  paytypeText: {
    flex: 1,
    color: '#333',
    fontSize: 14,
  },
  selectIcon: {
    width: 18,
    height: 18,
  },
  amountItems: {
    paddingBottom: 16,
    alignItems: 'center',
    flexDirection: 'row'
  },
  amountItem: {
    flex: 1,
    borderWidth: 1,
    borderRadius: 4,
    borderColor: '#999',
  },
  right: {
    marginLeft: 20
  },
  amountSelect: {
    borderColor: colorPrimary,
    backgroundColor: colorPrimary
  },
  amountText: {
    color: '#666',
    fontSize: 24,
    height: 50,
    lineHeight: 60,
    textAlign: 'center'
  },
  amountActive: {
    color: '#fff',
    fontSize: 24,
    height: 50,
    lineHeight: 60,
    textAlign: 'center'
  },
  powerText: {
    color: '#333',
    padding: 6,
    fontSize: 12,
    textAlign: 'right',
  },
  powerTextActive: {
    color: '#f0f0f0',
    padding: 6,
    fontSize: 12,
    textAlign: 'right',
  },
  warningText: {
    color: '#ED4A4A',
    fontSize: 14,
    textAlign: 'center',
    paddingBottom: 16
  },
  accountLogo: {
    width: 26,
    height: 26,
    marginRight: 12
  },
});