/**
 * 新充电流程：充电主页
 * @邠心vbe on 2023/06/20
 */
import React, { Component } from 'react';
import { View } from 'react-native';
import app from '../../../app.json';
import apiCharge from '../../api/apiCharge';
import apiWallet from '../../api/apiWallet';
import Dialog from '../../components/Dialog';
import { ErrorDialog } from '../chargeV2/InfoDialog';
import { PaymentDefault, PAYTYPE } from '../payment/PaymentConfig';
import { PageList } from '../Router';
import StepAuth from './StepAuth';
import StepCharging from './StepCharging';
import StepStart from './StepStart';
import StepStop from './StepStop';

export default class ChargingPage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isStoping: false,
      isCharging: false,
      isAuthentic: false,
      stationInfo: {},
      connectorInfo: {},
      errorCode: 'A9',
      errorMessage: '',
      lastUpdated: '',
      showErrorDialog: false,
      showStationDialog: false,
      currentPerUse: "",
      currentPayment: PaymentDefault.DEFAULT.payType,
      currentPaytype: PaymentDefault.DEFAULT.payName
    };
    this.isPageShow = true;
    this.waitStartCharging = false;
  }

  componentDidMount() {
    this.init();
    this.isPageShow = true;
    console.log("参数", this.props.route.params);
    if (this.props.route.params.connectorId && this.props.route.params.chargeBoxId) {
      this.setState({
        stationInfo: this.props.route.params
      }, () => {
        //测试进入
        //this.testInit();
        //正常进入
        this.getConnectorInfo();
      })
    }
    this.props.navigation.addListener('focus', () => {
      //console.log("充电流程页面获取焦点" + this.isPageShow, this.state.currentPerUse);
      if (!this.isPageShow && this.state.currentPerUse == "Pending") {
        this.isPageShow = true;
        //console.log("继续充电流程");
        this.setState({
          currentPerUse: "Paid"
        })
        this.refreshChargeData();
      } else {
        this.isPageShow = true;
        //this.canShowLoginDialog();
      }
    });
    this.props.navigation.addListener('blur', () => {
      this.isPageShow = false;
      //console.log("充电流程页面失去焦点");
    });
  }

  componentWillUnmount() {
    this.isPageShow = false;
  }

  testInit() {
    this.setState({
      isCharging: true,
      connectorInfo: {
        status: "Initiating"
      }
    }, () => {
      setTimeout(() => {
        this.getConnectorInfo();
      }, 2000);
    })
  }

  init() {
    this.setState({
      isStoping: false,
      isCharging: false,
      isAuthentic: false
    });
    this.waitAuthentic = false;
    this.waitStartCharging = false;
  }

  getConnectorInfo() {
    if (!this.isPageShow) return;
    //this.init();
    const params = {
      sitePk: this.state.stationInfo.id,
      chargeBoxId: this.state.stationInfo.chargeBoxId,
      connectorId: this.state.stationInfo.connectorId,
      paymentOption: this.state.currentPayment,
    }
    if (app.v3.paymentMethod && this.state.currentPayment?.code) {
      params.paymentMethod = this.state.currentPayment?.code
    }
    console.log("参数", params);
    apiCharge.getConnectorDetail(params).then(res => {
      if (res.data.status && !this.state.isStoping) {
        const state = {
          isStoping: false,
          isCharging: false,
          isAuthentic: false,
          connectorInfo: {}
        }
        state.connectorInfo = res.data;
        if (app.v3.paymentMethod && res.data.currentPaymentMethod) {
          //V3版获取当前支付方式
          state.currentPayment = {
            code: res.data.currentPaymentMethod
          }
        } else if (res.data.currentPaymentType && res.data.currentPaymentType == PAYTYPE.PAY_PER_USE) {
          //V2版获取当前支付方式
          state.currentPayment = PAYTYPE.PAY_PER_USE
        }
        console.log("状态", res.data.status);
        switch (res.data.status) {
          case 'Available': //可用的
            if (this.waitAuthentic) {
              state.isAuthentic = true;
              this.refreshChargeData(3000);
            } else {
              state.isAuthentic = false;
            }
            break;
          case 'Preparing': //已插入
            this.waitAuthentic = false;
            if (this.waitStartCharging) {
              state.isCharging = true;
              if (res.data.payPerUsePaymentStatus) {
                //等待PayPerUse支付-初始化充电
                if (res.data.payPerUsePaymentStatus == "PENDING" || res.data.payPerUsePaymentStatus == "PAID") {
                  this.refreshChargeData(3000);
                } else {
                  this.showErrorDialog('A4', $t('charging.errPayperusePayment') + res.data.payPerUsePaymentStatus);
                  state.isCharging = false;
                  state.isAuthentic = true;
                }
              } else {
                //普通充电-初始化充电
                this.refreshChargeData(3000);
              }
            } else {
              state.isAuthentic = true;
              //this.checkIsCharge();
            }
            break;
          case 'Charging': //正在充电
            state.isCharging = true;
            this.waitStartCharging = false;
            this.refreshChargeData(10000);
            break;
          case 'Initiating': //充电确认中
            state.isCharging = true;
            if (res.data.payPerUsePaymentStatus) {
              //等待PayPerUse支付-初始化充电
              if (res.data.payPerUsePaymentStatus == "PENDING" || res.data.payPerUsePaymentStatus == "PAID") {
                this.refreshChargeData();
              } else {
                this.showErrorDialog('A4', $t('charging.errPayperusePayment') + res.data.payPerUsePaymentStatus);
                state.isCharging = false;
                state.isAuthentic = false;
              }
            } else {
              //普通充电-初始化充电
              this.refreshChargeData();
            }
            break;
          case 'SuspendedEVSE':
            this.showErrorDialog('A5', $t('charging.errUnable2Charge'));
            break;
          case 'SuspendedEV': //已连接上但未充电
            state.isAuthentic = true;
            //this.refreshChargeData();
            break;
          case 'Reserved': //预定中
            this.showErrorDialog('A5', $t('charging.errUnable2Reserved'));
            break;
          case 'Finishing': //已完成
            if (res.data.chargingPk) {
              Dialog.showProgressDialog();
              setTimeout(() => {
                Dialog.dismissLoading();
                this.setState({
                  isStart: false,
                  isPending: false,
                  isCharging: false
                });
                startPage(PageList.summary, { 
                  chargingPk: res.data.chargingPk,
                  id: this.state.stationInfo.id,
                  name: this.state.stationInfo.name,
                  address: this.state.stationInfo.address
                });
              }, 2000);
            } else {
              goBack();
            }
            break;
          default:
            this.showErrorDialog('A4', $t('charging.errNotChargeE0'));
            break;
        }
        this.setState(state)
      }
    }).catch(err => {
      Dialog.showResultDialog("An error occurred:\n" + err, "Retry", () => {
        this.getConnectorInfo();
      })
      //toastShort(err)
    })
  }

  refreshChargeData(time=2000) {
    if (this.isPageShow) {
      //console.log("[刷新获取充电信息]", time);
      setTimeout(() => {
        this.getConnectorInfo();
      }, time);
    }
  }

  onPaymentMethodChanged(payment) {
    this.setState({
      currentPayment: payment
    })
  }

  onAuthenticate() {
    this.waitAuthentic = true;
    this.setState({
      isAuthentic: true
    }, () => {
      this.refreshChargeData()
    })
  }

  onStartCharge() {
    this.setState({
      isCharging: true
    });
    this.waitStartCharging = true;
    if (app.v3.paymentMethod) { //V3版本开始充电
      this.onStartChargeV3();
      return;
    }
    if (this.state.currentPayment == PAYTYPE.PAY_PER_USE) { //V2版本PayPerUse
      this.onStartChargePerUse();
      return;
    }
    apiCharge.startCharge(this.state.stationInfo).then(res => {
      console.log("[开始充电-onStartCharge]", res);
      setTimeout(() => {
        this.canAutoRefresh = true;
        this.refreshChargeData(500);
        //Dialog.dismissLoading();
        if (res.msg) {
          //Dialog.showResultDialog(res.msg)
          toastShort(res.msg)
        }
        //this.autoCheckIsCharge();
      }, 3000);
    }).catch(({err, code, data}) => {
      //toastShort(err);
      console.log("[开始充电错误]", err, code);
      //Dialog.dismissLoading();
      if (code == 5200) {
        this.showErrorDialog('none', "(" + data.transactionPk + ') ' + err);
      } else {
        this.showErrorDialog('A4', err);
      }
      this.setState({
        isCharging: false
      });
    });
  }

  onStartChargePerUse() {
    const params = {
      paymentOption: this.state.currentPayment,
      ...this.state.stationInfo
    }
    apiWallet.doPaymentV2(params).then(res => {
      if (res.data.webPaymentUrl) {
        this.setState({
          currentPerUse: "Pending"
        })
        startPage(PageList.paymentWeb, { amount: params.payAmount, url: res.data.webPaymentUrl, type: 'PayPerUse' });
      } else {
        toastShort('Error 0')
      }
    }).catch(({err}) => {
      this.showErrorDialog('A9', err);
      this.setState({
        isCharging: false
      });
    });
  }

  onStartChargeV3() {
    const params = {
      sitePk: this.state.stationInfo.id,
      chargeBoxId: this.state.stationInfo.chargeBoxId,
      connectorId: this.state.stationInfo.connectorId
    }
    if (this.state.currentPayment?.code) {
      params.paymentMethod = this.state.currentPayment?.code
    }
    console.log("[开始充电V3-params]", params);
    apiCharge.startChargeV3(params).then(res => {
      console.log("[开始充电V3-response]", res);
      if (res.data.webPaymentUrl) {
        this.setState({
          currentPerUse: "Pending"
        })
        startPage(PageList.paymentWeb, { amount: params.sitePk, url: res.data.webPaymentUrl, type: 'PayPerUse' });
      } else {
        setTimeout(() => {
          this.canAutoRefresh = true;
          this.refreshChargeData(500);
          if (res.msg) {
            toastShort(res.msg)
          }
        }, 3000);
      }
    }).catch(({err, code, data}) => {
      //toastShort(err);
      console.log("[开始充电V3-错误]", err, code);
      //Dialog.dismissLoading();
      if (code == 5200) {
        this.showErrorDialog('none', "(" + data.transactionPk + ') ' + err);
      } else {
        this.showErrorDialog('A4', err);
      }
      this.setState({
        isCharging: false
      });
    });
  }

  onStopCharge() {
    Dialog.showDialog({
      title: $t('charging.titleStopCharging'),
      message: $t('charging.confirmStopCharging'),
      ok: $t('nav.confirm'),
      callback: ok => {
        if (ok == Dialog.BUTTON_OK) {
          this.stopCharge();
        }
      }
    });
  }

  stopCharge() {
    this.setState({
      isStoping: true
    })
    //Dialog.showProgressDialog();
    apiCharge.stopCharge().then(res => {
      if (res.data.chargingPk) {
        setTimeout(() => {
          //Dialog.dismissLoading();
          if (res.msg) {
            toastShort(res.msg)
          }
          this.setState({
            isCharging: false,
            isAuthentic: false
          });
          //this.init();
          startPage(PageList.summary, { 
            chargingPk: res.data.chargingPk,
            id: this.state.stationInfo.id,
            name: this.state.stationInfo.name,
            address: this.state.stationInfo.address
          });
        }, 3000);
      } else {
        if (res.msg) {
          toastShort(res.msg)
        } else {
          toastShort($t('charging.errDetected'));
        }
        this.refreshChargeData(500);
      }
    }).catch((err) => {
      //Dialog.dismissLoading();
      toastShort(err);
      this.setState({
        isStart: false,
        isPending: false,
        isCharging: false,
        isStoping: false
      });
      //模拟进入结算页
      /*startPage(PageList.summary, {
        chargingPk: 1,
        id: this.state.stationInfo.id,
        name: this.state.stationInfo.name,
        address: this.state.stationInfo.address
      });*/
    });
  }

  showErrorDialog(code, msg) {
    this.setState({
      errorCode: code,
      showErrorDialog: true,
      errorMessage: ''+msg
    });
  }

  closeError() {
    this.setState({
      showErrorDialog: false,
      showStationDialog: false
    });
  }

  render() {
    return (
      <View style={ui.flex1}>
        { this.state.isStoping
        ? <StepStop
            currentPayment={this.state.currentPayment}
          />
        : ( this.state.isCharging 
          ? <StepCharging
              connectorInfo={this.state.connectorInfo}
              currentPayment={this.state.currentPayment}
              onStopCharge={() => this.onStopCharge()}
            />
          : ( this.state.isAuthentic
            ? <StepAuth
                status={this.state.connectorInfo?.status}
                chargeBoxId={this.state.stationInfo.chargeBoxId}
                currentPayment={this.state.currentPayment}
                onStartCharge={() => this.onStartCharge()}
                onPaymentMethodChanged={(type) => this.onPaymentMethodChanged(type)}
              />
            : <StepStart
                connectorInfo={this.state.connectorInfo}
                currentPayment={this.state.currentPayment}
                onAuthenticate={() => this.onAuthenticate()}
                onPaymentMethodChanged={(type) => this.onPaymentMethodChanged(type)}
              />
            )
          )
        }
        <ErrorDialog
          visible={this.state.showErrorDialog}
          code={this.state.errorCode}
          message={this.state.errorMessage}
          onClose={() => {
            this.closeError();
          }}/>
      </View>
    );
  }
}
