/**
 * 新版充电页面
 * @邠心vbe on 2023/02/06
 */
import React, { Component } from 'react';
import { View, StyleSheet } from 'react-native';
import apiCharge from '../../api/apiCharge';
import Dialog from '../../components/Dialog';
import { PageList } from '../Router';
import { EnterStationDialog } from './Charging';
import { QRResult } from '../charge/QRScan';
import { ErrorDialog } from './InfoDialog';
import PagerUtil from './PagerUtil';
import StepStartView from '../charging/StepStartView';
import StepChargeView from '../charging/StepChargeView';
import utils from '../../utils/utils';
import { PaymentDefault } from '../payment/PaymentConfig';

export default class TabCharge extends Component {
  constructor(props) {
    super(props);
    this.state = {
      available: false,
      isPrivate: false,
      refreshId: 0,
      isStart: false,
      isPending: false,
      isCharging: false,
      isAuthentic: false,
      selectRate: '',
      connectorInfo: {},
      stationInfo: {},
      lastUpdated: '',
      errorCode: 'A9',
      errorMessage: '',
      showErrorDialog: false,
      showStationDialog: false,
      curerntPerUser: undefined,
      canIntoCharging: false,
      //currentPayment: PAYTYPE.CREDIT_WALLET,
      //currentPaytype: "Credit Wallet",
      currentPayment: PaymentDefault.DEFAULT.payType,
      currentPaytype: PaymentDefault.DEFAULT.payName
    };
    this.changeMethod = false;
    this.canAutoRefresh = false;
    this.inputStationId = '';
    this.autoIntoCharging = true;
    this.intoChargingStatus = ["Preparing", "Charging", "Initiating", "SuspendedEVSE", "SuspendedEV"]
  }

  componentDidMount() {
    this.canAutoRefresh = true;
    PagerUtil.addOnRefresh(this);
    //this.onRefresh();
  }

  onRefresh() {
    console.log("Charge刷新", this.props.route.name);
    const info = PagerUtil.getStationInfo();
    this.setState({
      stationInfo: info
    }, () => {
      this.init();
      console.log("站点信息", this.state.stationInfo);
      //this.checkIsCharge();
    });
  }

  init() {
    console.log("Charge刷新", "init");
    this.onMethodChanged();
    this.refreshAvailable();
    if (QRResult.haveResult()) {
      console.log("Charge刷新", "haveResult");
      const info = QRResult.getResult()
      console.log('QRResult', info);
      if (PagerUtil.ENABLE_NEW_UI) {
        //新充电流程
        this.setState({
          connectorInfo: info
        }, () => {
          this.checkChargeStatus(true);
        })
      } else {
        this.setState({
          isAuthentic: true,
          connectorInfo: info
          //soc: info.chargeType == 'AC' ? 0 : 'In Charging'
        }, () => {
          PagerUtil.onCharge(this.props);
          this.checkChargeStatus(true);
        });
      }
      //QRResult.clearResult();
    } else if (this.state.isStart) {
      console.log("Charge刷新", "isStart");
      this.checkIsCharge();
    } else {
      console.log("Charge刷新", "noStart");
      this.getConnectorInfo();
      //this.checkChargeStatus();
    }
  }

  componentWillUnmount() {
    this.canAutoRefresh = false;
  }

  //刷新可用充电接口
  refreshAvailable() {
    const info = this.state.stationInfo
    const all = info?.allConnector;
    if (info.siteType == 'Private') {
      this.setState({
        isPrivate: true
      })
    }
    if (all) {
      this.setState({
        available: !all.available > 0
      });
    }
  }

  toChargingPage() {
    this.autoIntoCharging = false;
    startPage(PageList.chargingPage, {
      id: this.state.stationInfo.id,
      name: this.state.stationInfo.name,
      address: this.state.stationInfo.address,
      chargeBoxId: this.state.connectorInfo.chargeBoxId,
      connectorId: this.state.connectorInfo.connectorId
    });
  }

  enterStatioinId() {
    if (QRResult.haveResult()) {
      const info = QRResult.getResult()
      console.log('EnterResult', info);
      this.setState({
        isAuthentic: true,
        connectorInfo: info
        //soc: info.chargeType == 'AC' ? 0 : 'In Charging'
      });
      this.checkChargeStatus();
    }
  }

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

  onMethodChange() {
    this.changeMethod = true;
    startPage(PageList.paymentMethod, {info: this.state.connectorInfo, type: this.state.currentPayment});
  }

  onMethodChanged() {
    if (this.changeMethod) {
      this.changeMethod = false;
      if (global.paymentOption?.title) {
        this.setState({
          curerntPerUser: global.paymentOption.amount,
          currentPayment: global.paymentOption.value,
          currentPaytype: global.paymentOption.title
        }, () => {
          global.paymentOption= {}
        })
      }
    }
  }

  //打开输入弹窗
  onEnterStation() {
    this.setState({
      showStationDialog: true
    })
  }

  //自动刷新
  autoCheckIsCharge() {
    if (this.canAutoRefresh) {
      this.checkIsCharge();
    }
  }

  //自动刷新状态
  autoCheckChargeStatus() {
    setTimeout(() => {
      if (this.canAutoRefresh) {
        this.checkChargeStatus();
      }
    }, 10000);
  }

  //扫码后获取连接器数据
  getConnectorInfo() {
    console.log("[TabCharge] getConnectorInfo", this.state.stationInfo.id);
    apiCharge.checkIsCharging({sitePk: this.state.stationInfo.id}).then(res => {
      this.setState({
        connectorInfo: res.data
      }, () => {
        this.checkChargeStatus();
      });
    }).catch((err) => {
      
    });
  }

  //获取充电进度数据（百分比）
  checkIsCharge(showError) {
    const params = {
      sitePk: this.state.stationInfo.id
    }
    apiCharge.checkIsCharging(params).then(res => {
      this.setState({
        isStart: true,
        isCharging: true,
        isAuthentic: true,
        connectorInfo: res.data,
        lastUpdated: utils.getNowHHmm()
      });
      if (this.canAutoRefresh) {
        setTimeout(() => {
          this.autoCheckIsCharge();
        }, 30000);
      }
      PagerUtil.onCharge(this.props);
    }).catch(({err, code}) => {
      //TODO 模拟测试
      //TODO 模拟测试-End
      this.setState({
        isStart: false,
        isCharging: false
      });
      setTimeout(() => {
        this.autoCheckIsCharge();
        this.canAutoRefresh = false;
      }, 30000);
      if (showError) {
        this.setState({
          errorCode: 'A4',
          showErrorDialog: true,
          errorMessage: 'Your vehicle doesn’t seem to be charging. Please check your vehicle.'
        });
      }
    });
  }
  //获取充电进度数据-end

  //获取充电桩对应接口的状态
  checkChargeStatus(haveResult=false) {
    //TODO 模拟测试
    /*this.setState({
      isStart: true,
      isCharging: true,
      isAuthentic: true
    });
    return;*/
    //TODO 模拟测试-End
    const params = {
      connectorId: this.state.connectorInfo.connectorId,
      chargeBoxId: this.state.connectorInfo.chargeBoxId,
    }
    if (!PagerUtil.ENABLE_NEW_UI) {
      if (!params.chargeBoxId || !params.connectorId) {
        this.checkIsCharge();
        return;
      }
    }
    apiCharge.getCurrentStatus(params).then(res => {
      if (res.data.status) {
        if (PagerUtil.ENABLE_NEW_UI && (this.intoChargingStatus.indexOf(res.data.status) >= 0 || haveResult)) {
          //进入新流程
          this.setState({
            canIntoCharging: true
          }, () => {
            if (this.autoIntoCharging) {
              this.toChargingPage();
            } else {
              PagerUtil.onCharge(this.props);
            }
          })
        } else {
          if (haveResult) {
            PagerUtil.onCharge(this.props);
          }
          switch (res.data.status) {
            case 'Available': //可用的
              this.state.connectorInfo.isCheckThrough = false;
              this.setState({
                isStart: false,
                isPending: false,
                isCharging: false,
                connectorInfo: this.state.connectorInfo
              });
              break;
            case 'Preparing': //已插入
              this.state.connectorInfo.isCheckThrough = true;
              this.setState({
                isStart: false,
                isPending: false,
                isCharging: false,
                available: true,
                connectorInfo: this.state.connectorInfo
              });
              //this.checkIsCharge();
              break;
            case 'Charging': //正在充电
              this.canAutoRefresh = true;
              this.state.connectorInfo.isCheckThrough = true;
              this.setState({
                isPending: false,
                connectorInfo: this.state.connectorInfo
              });
              this.checkIsCharge();
              break;
            case 'Initiating': //充电确认中
              this.canAutoRefresh = true;
              this.state.connectorInfo.isCheckThrough = true;
              this.setState({
                isStart: true,
                isPending: true,
                isCharging: true,
                isAuthentic: true,
                connectorInfo: this.state.connectorInfo
              });
              this.autoCheckChargeStatus();
              break;
            case 'SuspendedEVSE':
              this.setState({
                errorCode: 'A5',
                showErrorDialog: true,
                errorMessage: $t('charging.errUnable2Charge')
              });
              break;
            case 'SuspendedEV': //已连接上但未充电
              this.checkIsCharge(true);
              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 {
                this.setState({
                  isStart: true,
                  isPending: false,
                  isCharging: false
                });
              }
              break;
            default:
              this.setState({
                isStart: false,
                isPending: false,
                isCharging: false
              });
              this.setState({
                errorCode: 'A4',
                showErrorDialog: true,
                errorMessage: $t('charging.errNotChargeE0')
              });
              break;
          }
        }
      } else {
        this.setState({
          errorCode: 'A4',
          showErrorDialog: true,
          errorMessage: $t('charging.errNotChargeE0')
        });
      }
    }).catch((err) => {
      toastShort(err)
      this.setState({
        errorCode: 'A9',
        showErrorDialog: true,
        errorMessage: $t('charging.errAuthenticationError')
      });
    })
  }
  //获取充电桩对应接口的状态-end

  //开始充电-start
  startCharge() {
    if (this.state.connectorInfo.isCheckThrough) {
      Dialog.showProgressDialog();
      const params = {
        chargeBoxId: this.state.connectorInfo.chargeBoxId,
        connectorId: this.state.connectorInfo.connectorId
      }
      apiCharge.startCharge(params).then(res => {
        console.log(res);
        setTimeout(() => {
          this.setState({
            isStart: true,
            isPending: true,
            isCharging: true
          });
          this.canAutoRefresh = true;
          this.autoCheckChargeStatus();
          Dialog.dismissLoading();
          if (res.msg) {
            Dialog.showResultDialog(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
          });
        }
      });
    } else {
      this.setState({
        errorCode: 'A1',
        showErrorDialog: true,
        errorMessage: $t('charging.errNotConnected')
      });
    }
  }
  //开始充电-end

  //停止充电-start
  onStopCharge() {
    if (this.state.isCharging) {
      Dialog.showDialog({
        title: $t('charging.titleStopCharging'),
        message: $t('charging.confirmStopCharging'),
        callback: ok => {
          if (ok == Dialog.BUTTON_OK) {
            this.stopCharge();
          }
        }
      });
    } else {
      this.stopCharge();
    }
  }

  stopCharge() {
    this.canAutoRefresh = false;
    Dialog.showProgressDialog();
    apiCharge.stopCharge().then(res => {
      if (res.msg) {
        toastShort(res.msg)
      }
      if (res.data.chargingPk) {
        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
          });
        }, 3000);
      } else {
        Dialog.dismissLoading();
        toastShort($t('charging.errDetected'));
      }
    }).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
      });*/
    });
  }
  //停止充电-end

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

  render() {
    return (
      <View style={styles.container}>
        { this.state.isAuthentic //是否扫码认证
        ? <StepChargeView
            isStart={this.state.isStart} //是否开始充电
            isPending={this.state.isPending}
            isCharging={this.state.isCharging}
            lastUpdated={this.state.lastUpdated}
            connectorInfo={this.state.connectorInfo}
            currentPayment={this.state.currentPayment}
            curerntPerUser={this.state.curerntPerUser}
            onStartCharge={() => this.startCharge()}
            onStopCharge={() => this.onStopCharge()}
            onPaymentMethodChanged={(type) => this.onPaymentMethodChanged(type)}/>
        : <StepStartView
            isPrivate={this.state.isPrivate}
            canIntoCharging={this.state.canIntoCharging}
            stationInfo={this.state.stationInfo}
            onEnterStation={() => this.onEnterStation()}
            onIntoCharging={() => this.toChargingPage()}
          />
        }
        <ErrorDialog
          visible={this.state.showErrorDialog}
          code={this.state.errorCode}
          message={this.state.errorMessage}
          onClose={() => {
            this.closeError();
          }}
        />
        <EnterStationDialog
          visible={this.state.showStationDialog}
          stationId={this.state.stationInfo.id}
          onConfirm={() => this.enterStatioinId()}
          onClose={() => this.closeError()}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingLeft: 16,
    paddingRight: 16
  },
  title: {
    color: '#000',
    fontSize: 14,
    fontWeight: 'bold',
    paddingTop: 16,
    paddingBottom: 16
  }
})
