/**
 * 新充电流程：充电主页
 * @邠心vbe on 2023/06/20
 */
import React, { Component } from 'react';
import { View } from 'react-native';
import apiCharge from '../../api/apiCharge';
import Dialog from '../../components/Dialog';
import { ErrorDialog } from '../chargeV2/InfoDialog';
import { PaymentDefault } 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,
      curerntPerUse: undefined,
      currentPayment: PaymentDefault.DEFAULT.payType,
      currentPaytype: PaymentDefault.DEFAULT.payName
    };
    this.waitStartCharging = false;
  }

  componentDidMount() {
    this.init();
    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.refreshChargeData(0);
      })
    }
  }

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

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

  getConnectorInfo() {
    //this.init();
    apiCharge.getConnectorDetail(this.state.stationInfo).then(res => {
      if (res.data.status) {
        const state = {
          isStoping: false,
          isCharging: false,
          isAuthentic: false,
          connectorInfo: {}
        }
        state.connectorInfo = res.data;
        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;
              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;
            this.refreshChargeData();
            break;
          case 'SuspendedEVSE':
            this.setState({
              errorCode: 'A5',
              showErrorDialog: true,
              errorMessage: $t('charging.errUnable2Charge')
            });
            break;
          case 'SuspendedEV': //已连接上但未充电
            state.isAuthentic = true;
            //this.refreshChargeData();
            break;
          case 'Reserved': //预定中
            this.setState({
              errorCode: 'A5',
              showErrorDialog: true,
              errorMessage: $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.setState({
              errorCode: 'A4',
              showErrorDialog: true,
              errorMessage: $t('charging.errNotChargeE0')
            });
            break;
        }
        this.setState(state);
      }
    }).catch(err => {
      Dialog.showResultDialog("An error occurred:\n" + err, "Retry", () => {
        this.getConnectorInfo();
      });
      //toastShort(err)
    })
  }

  refreshChargeData(time=2000) {
    //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;
    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.setState({
          errorCode: 'none',
          showErrorDialog: true,
          errorMessage: "(" + data.transactionPk + ') ' + err
        });
      } else {
        this.setState({
          errorCode: 'A4',
          showErrorDialog: true,
          errorMessage: ''+err
        });
      }
    });
  }

  onStopCharge() {
    Dialog.showDialog({
      title: $t('charging.titleStopCharging'),
      message: $t('charging.confirmStopCharging'),
      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.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
      });
      //模拟进入结算页
      /*startPage(PageList.summary, {
        chargingPk: 1,
        id: this.state.stationInfo.id,
        name: this.state.stationInfo.name,
        address: this.state.stationInfo.address
      });*/
    });
  }

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

  render() {
    return (
      <View style={ui.flex1}>
        { this.state.isStoping
        ? <StepStop
            currentPayment={this.state.currentPayment}
            curerntPerUse={this.state.curerntPerUse}
          />
        : ( this.state.isCharging 
          ? <StepCharging
              connectorInfo={this.state.connectorInfo}
              currentPayment={this.state.currentPayment}
              curerntPerUse={this.state.curerntPerUse}
              onStopCharge={() => this.onStopCharge()}
            />
          : ( this.state.isAuthentic
            ? <StepAuth
                status={this.state.connectorInfo?.status}
                currentPayment={this.state.currentPayment}
                curerntPerUse={this.state.curerntPerUse}
                onStartCharge={() => this.onStartCharge()}
              />
            : <StepStart
                connectorInfo={this.state.connectorInfo}
                currentPayment={this.state.currentPayment}
                curerntPerUse={this.state.curerntPerUse}
                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>
    );
  }
}
