<template>
  <view class="container fixed">
    <view class="toolbar" v-if="chargeInfo">
      <view class="tool-title">Charge</view>
      <view class="tool-desc" v-if="chargeInfo.chargeBoxId">{{chargeInfo.chargeBoxId + "-" + chargeInfo.connectorId}}</view>
      <view class="tool-desc" v-else>-</view>
    </view>
    <header-view
      title="Insert Charging Cable"
      :status="connectorInfo.status"
      :isLoading="isLoading"/>
    <info-view
      :info="connectorInfo"
      :isLoading="isLoading"/>
    <payment-view
      v-if="connectorInfo.status == 'Preparing'"
      :status="connectorInfo.paymentStatus"/>
    <divide size="36"/>
    <view class="bottom-button">
      <button
        v-if="connectorInfo.status == 'Initiating'"
        class="ui-button margin0"
        type="primary"
        @click="onStart"
        :disabled="!connectorInfo.shouldClickStart">START CHARGING</button>
      <button
        v-else-if="connectorInfo.status == 'Charging'"
        class="ui-button margin0"
        type="primary"
        @click="stopCharge">INPUT PIN TO STOP CHARGING</button>
      <button
        v-else-if="connectorInfo.status == 'Finishing'"
        class="ui-button margin0"
        type="primary"
        disabled>STOP CHARGING</button>
      <template v-else-if="connectorInfo.status == 'Preparing'">
        <button
          class="ui-button margin0"
          type="primary"
          @click="onStart"
          v-if="connectorInfo.paymentStatus == 'PAID'">START CHARGING</button>
        <button
          class="ui-button margin0"
          type="primary"
          @click="onPayment"
          v-else>
          <view class="flexcc">
            <text>MAKE PAYMENT</text>
            <view class="icon-key" v-if="password.length == 0">
              <i-icon name="key-fill" size="32rpx" color="#333"/>
            </view>
          </view>
        </button>
      </template>
      <button
        v-else-if="connectorInfo.status == 'Available' && isLoading"
        class="ui-button margin0"
        type="cancel"
        @click="cancelAuth">CANCEL</button>
      <button
        v-else
        class="ui-button margin0"
        type="primary"
        @click="onAuthentic"
        :disabled="connectorInfo.status != 'Available' || isLoading">
        <view class="flexcc">
          <text>AUTHENTICATE</text>
          <view class="icon-key" v-if="password.length == 0">
            <i-icon name="key-fill" size="32rpx" color="#333"/>
          </view>
        </view>
      </button>
    </view>
    <PasswordView
      :visible="showPin || stopPin"
      :verify="stopPin"
      @change="changePassword"/>
  </view>
</template>
<script>
import HeaderView from './views/HeaderView.vue';
import InfoView from './views/InfoView.vue';
import PaymentView from './views/PaymentView.vue';
import PasswordView from '@/components/PasswordView.vue';
import apiCharge from '@/api/apiCharge';
import {openUrl} from '@/utils/utils.js';
import settings from '../../settings';
import auth from '../../utils/auth';

export default {
  data() {
    return {
      refreshId: 0,
      isLoading: false,
      waitPayment: false,
      isPaymentFailed: false,
      chargeInfo: {
        chargeBoxId: "",
        connectorId: ""
      },
      connectorInfo: {},
      stoped: false,
      creditHistoryPk: "",
      chargingPk: "",
      paymentId:"",
      showPin: false,
      stopPin: false,
      password: ""
    }
  },
  components: {
    HeaderView,
    InfoView,
    PaymentView,
    PasswordView
  },
  onLoad(query) {
    if (query.pk) {
      this.paymentId = query.pk;
    }
    if (query.info) {
      this.chargeInfo = JSON.parse(decodeURIComponent(query.info));
    } /*else {
      this.waitPayment = getApp().globalData.waitPayment;
      let id = auth.getPaymentId();
      if (id) {
        this.paymentId = id;
      }
    }*/
    if (!query.pk && !query.info) {
      uni.reLaunch({
        url: "/pages/index/index"
      });
      return;
    }
    this.refreshStatus(500);
  },
  methods: {
    refreshStatus(time=2000) {
      this.refreshId += 1;
      setTimeout(() => {
        if (this.stoped) {
          return;
        }
        if (this.paymentId) {
          this.getChargingStatus(this.refreshId);
        } else if (this.chargeInfo.connectorId) {
          this.getChargerInfo(this.refreshId)
        }
      }, time);
    },
    getChargerInfo(id) {
      if (id !== this.refreshId) {
        return;
      }
      apiCharge.getChargerDetails(this.chargeInfo).then(res => {
        if (res.data) {
          this.connectorInfo = res.data;
          this.showPageWithStatus()
        }
      }).catch(err => {
        uni.showModal({
          title: "Error",
          content: err,
          confirmText: "OK",
          showCancel: false,
          success: res => {
            if (res.confirm) {
              uni.navigateBack();
            }
          }
        })
      }).finally(() => {
        uni.stopPullDownRefresh();
      })
    },
    getChargingStatus(id) {
      if (id !== this.refreshId) {
        return;
      }
      apiCharge.getChargingDetails({
        creditHistoryPk: this.paymentId
      }).then(res => {
        if (res.data) {
          this.connectorInfo = res.data;
          if (res.data.creditHistoryPk) {
            this.createPayment(res.data.creditHistoryPk);
          }
          if (!this.chargeInfo.chargeBoxId && res.data.chargeBoxId) {
            this.chargeInfo.chargeBoxId = res.data.chargeBoxId;
            this.chargeInfo.connectorId = res.data.connectorId;
          }
          this.showPageWithStatus()
        }
      }).catch(err => {
        /*uni.showToast({
          icon: "none",
          title: err
        })*/
        uni.showModal({
          title: "Error",
          content: err,
          confirmText: "OK",
          showCancel: false,
          success: res => {
            if (res.confirm) {
              uni.navigateBack();
            }
          }
        })
      }).finally(() => {
        uni.stopPullDownRefresh();
      })
    },
    showPageWithStatus() {
      //this.connectorInfo.status = "Available"
      switch (this.connectorInfo.status) {
        case "Available":
          if (this.isLoading) {
            this.refreshStatus(3000);
          }
          break;
        case "Preparing":
          this.isLoading = false;
          if (this.connectorInfo.paymentStatus == "FAILED") {
            this.isPaymentFailed = true;
          }
          break;
        case "Initiating":
          if (this.isLoading || this.waitPayment) {
            this.refreshStatus(3000);
          } else {
            this.isLoading = true;
            this.refreshStatus(3000);
          }
          break;
        case "Charging":
          if (this.waitPayment) {
            this.isLoading = true;
            this.waitPayment = false;
            getApp().globalData.waitPayment = false;
            this.refreshStatus(3000);
          } else {
            this.isLoading = false;
            this.refreshStatus(10000);
          }
          break;
        case "Finishing":
          if (this.connectorInfo.chargingPk) {
            this.chargingPk = this.connectorInfo.chargingPk;
            this.toReceipt();
          } else {
            this.refreshStatus(5000);
            //uni.navigateBack();
          }
          break;
        default:
          this.refreshId = 0;
          this.isLoading = false;
          break;
      }
      uni.hideLoading();
    },
    changePassword(psd) {
      this.password = psd;
      if (this.stopPin) {
        this.stopPin = false;
        this.onStop();
      } else {
        this.showPin = false;
        this.onAuthentic();
      }
    },
    refreshPayment() {
      uni.showLoading({
        title: "Waiting..."
      });
      this.getChargingStatus();
    },
    onAuthentic() {
      if (this.password) {
        this.isLoading = true;
        this.refreshStatus();
      } else {
        this.showPin = true;
      }
    },
    cancelAuth() {
      this.isLoading = false;
    },
    onPayment() {
      if (!this.password) {
        this.showPin = true;
        return;
      }
      uni.showLoading({
        title: "Waiting..."
      })
      apiCharge.makePayment({
        ...this.chargeInfo,
        pin: this.password
      }).then(res => {
        if (res.data.creditHistoryPk) {
          this.createPayment(res.data.creditHistoryPk);
        }
        if (res.data.webPaymentUrl) {
          openUrl(res.data.webPaymentUrl);
        }
      }).catch(err => {
        uni.showModal({
          title: "Error",
          content: err,
          confirmText: "OK",
          showCancel: false,
        })
        /*uni.showToast({
          icon: "none",
          title: err
        })*/
      }).finally(() => {
        uni.hideLoading();
      });
    },
    onStart() {
      this.isLoading = true;
      uni.showLoading({
        title: "Loading..."
      })
      apiCharge.startCharge({
        //connectorPk: this.connectorPk,
        creditHistoryPk: this.paymentId
      }).then(res => {
        this.refreshStatus();
        if (res.msg) {
          uni.showToast({
            icon: "none",
            title: res.msg
          })
        } else {
          uni.hideLoading();
        }
      }).catch(err => {
        this.isLoading = false;
        //this.paymentId = "";
        //auth.setPaymentId("");
        this.connectorInfo.paymentStatus = "";
        uni.showToast({
          icon: "none",
          title: err
        })
      })
    },
    stopCharge() {
      uni.showModal({
        title: "Confirm Stop Charging?",
        content: "Your charging session will stop",
        confirmText: "CONFIRM",
        cancelText: "CANCEL",
        success: res => {
          if (res.confirm) {
            this.stopPin = true;
          }
        }
      })
    },
    onStop() {
      uni.showLoading({
        title: "Stopping..."
      })
      apiCharge.stopCharge({
        creditHistoryPk: this.paymentId,
        pin: this.password
      }).then(res => {
        this.stoped = true;
        this.paymentId = "";
        auth.setPaymentId("");
        if (res.data.chargingPk) {
          uni.hideLoading();
          this.chargingPk = res.data.chargingPk
          this.toReceipt();
        } else {
          uni.showToast({
            icon: "none",
            title: "Stop failed"
          });
          this.refreshStatus();
        }
      }).catch(err => {
        uni.showModal({
          title: "Error",
          content: err,
          confirmText: "OK",
          showCancel: false
        })
        uni.hideLoading();
        this.refreshStatus();
      })
    },
    confirmStop() {
      uni.showModal({
        title: "Confirm Stop Charging?",
        content: "Your charging session will stop",
        confirmText: "CONFIRM",
        cancelText: "BACK",
        //confirmColor: "var(--primary-color)",
        success: (res) => {
          if (res.confirm) {
            this.onStop();
          }
        }
      })
    },
    createPayment(id) {
      if (id) {
        this.paymentId = id;
        //auth.setPaymentId("" + id);
      }
    },
    resetPayment() {
      this.isLoading = false;
      this.waitPayment = false;
      this.isPaymentFailed = false;
      getApp().globalData.waitPayment = false;
    },
    toReceipt() {
      uni.navigateTo({
        url: "/pages/receipt/index?id=" + this.chargingPk
      })
    }
  },
  onPullDownRefresh() {
    this.refreshStatus(500);
  }
}
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
}
.toolbar {
  display: flex;
  padding: 16rpx;
  position: relative;
  align-items: center;
  flex-direction: column;
  justify-content: center;
  background-color: white;
}
.tool-title {
  color: #111;
  font-size: 32rpx;
  font-weight: bold;
  padding-bottom: 4rpx;
}
.tool-desc {
  color: #666;
  font-size: 24rpx;
}
.bottom-button {
  padding: 32rpx;
  background-color: white;
  box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.1);
}
.icon-key {
  padding: 0 8rpx;
  transform: rotate(-90deg);
}
.ui-button[disabled] >>> .icon-key span {
  color: #888;
}
</style>
