<template>
  <el-dialog
    class="dialog-ocpp"
    :visible="visible"
    :before-close="e => hideDialog()"
    :title='isStart ? "Remote Start Transaction" : "Remote Stop Transaction"'>
    <el-form
      ref="setForm"
      :model="params"
      :rules="rules">
      <div class="form-row" v-if="isStart">
        <div class="label">Mobile Number:</div>
        <el-form-item
          label=""
          prop="idTagInfo"
          v-if="mobileOptions.idTagAll.length > 0">
          <el-select
            v-model="params.idTagInfo"
            filterable
            remote
            clearable
            :remote-method="filterMobile"
            class="flex-item"
            :loading="tagLoading"
            style="max-width: 320px;">
            <el-option
              v-for="(item, index) in mobileOptions.idTags"
              :key="index"
              :label="item.name"
              :value="item.value"/>
          </el-select>
        </el-form-item>
      </div>
      <div class="form-row" v-else>
        <div class="label">Transaction ID:</div>
        <el-form-item
          label=""
          prop="transactionId">
          <el-select
            v-model="params.transactionId"
            class="flex-item"
            style="max-width: 320px;">
            <el-option
              v-for="(item, index) in transactionOptions"
              :key="index"
              :label="item"
              :value="item"/>
          </el-select>
        </el-form-item>
      </div>
      <div class="flexcc">
        <el-button
          class="button"
          type="primary"
          :loading="loading"
          @click="onSendOcpp">
          Perform
        </el-button>
      </div>
    </el-form>
  </el-dialog>
</template>

<script>
import ocpp from '@/http/api/ocpp'
import util from '../../ocpp/operationUtil'
export default {
  name: "DialogRemoteOcpp",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    isStart: {
      type: Boolean,
      default: false
    },
    item: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      loading: false,
      tagLoading: false,
      transLoading: false,
      searchTag: "",
      params: {
        idTagInfo: "",
        transactionId: "",
      },
      mobileOptions: {
        idTags: [],
        idTagAll: []
      },
      transactionOptions: [],
      rules: {
        idTagInfo: {
          required: true,
          trigger: 'change',
          message: 'Please select a mobile'
        },
        transactionId: {
          required: true,
          trigger: 'change',
          message: 'Please select transaction id'
        }
      }
    }
  },
  mounted() {
    this.getMobileOptions();
  },
  watch: {
    item: {
      immediate: true,
      handler(value) {
        if (!this.isStart && value && value.chargeBoxId) {
          this.$nextTick(() => {
            this.getActiveIdsOptions()
          })
        }
      }
    },
    isStart: {
      immediate: true,
      handler(value) {
        if (!value) {
          this.$nextTick(() => {
            this.getActiveIdsOptions();
          })
        }
      }
    },
    visible: {
      immediate: true,
      handler(value) {
        if (value) {
          this.$nextTick(() => {
            this.$refs['setForm'].clearValidate();
          })
        }
      }
    }
  },
  methods: {
    hideDialog(success) {
      this.$emit("hide", success || false);
      this.params = {
        idTagInfo: "",
        transactionId: ""
      }
      this.$nextTick(() => {
        this.$refs['setForm'].clearValidate();
      })
    },
    getMobileOptions() {
      ocpp.getActiveIdTags().then(res => {
        if (res.data) {
          const list = []
          res.data.forEach(item => {
            list.push({
              name: item.name,
              value: JSON.stringify({
                phone: item.name,
                idTag: item.value
              })
            })
          })
          this.mobileOptions.idTagAll.push(...list);
          this.mobileOptions.idTags.push(...list);
        }
      })
    },
    getActiveIdsOptions() {
      if (this.transLoading) return;
      this.transLoading = true;
      util.getActiveConnectorIds([this.item.chargeBoxId]).then(list => {
        this.transactionOptions = list;
        this.transLoading = false;
      });
    },
    filterMobile(word) {
      if (word) {
        this.searchTag = word;
        setTimeout(() => {
          this.searchMobile(word)
        }, 300)
      } else {
        this.mobileOptions.idTags = []
        this.mobileOptions.idTags.push(...this.mobileOptions.idTagAll)
      }
    },
    searchMobile(word) {
      if (this.searchTag === word) {
        this.tagLoading = true;
        util.filterMobile(word, tags => {
          this.mobileOptions.idTags = tags;
          this.tagLoading = false;
        })
      }
    },
    onSendOcpp() {
      this.$refs['setForm'].validate(result => {
        if (result) {
          this.isStart
          ? this.onRemoteStart()
          : this.onRemoteEnd()
        }
      });
    },
    onRemoteStart() {
      const params = {
        connectorId: this.item.connectorId,
        stationIds: [this.item.chargeBoxId],
        idTagInfo: JSON.parse(this.params.idTagInfo)
      }
      this.sendOcppPerform("ocppOperations/remoteStartTransaction", params);
    },
    onRemoteEnd() {
      const params = {
        stationIds: [this.item.chargeBoxId],
        ...this.params
      }
      this.sendOcppPerform("ocppOperations/remoteStopTransaction", params);
    },
    sendOcppPerform(url, params) {
      this.loading = true;
      /*const params = {
        stationIds: [this.item.chargeBoxId],
        ...this.params
      }
      if (this.params.filterType == "ChargingProfileId") {
        params.chargingProfilePk = this.item.chargingProfilePk
        params.chargingProfilePurpose = undefined;
      } else {
        params.connectorId = this.item.connectorId
      }*/
      ocpp.sendPerform(url, params).then(res => {
        this.hideDialog(true);
        this.loading = false;
        if (res.data.taskId) {
          this.$openRoute("/ocpp-operations/result/" + res.data.taskId);
          //this.$router.push({path: '/ocpp-operations/result/' + res.data.taskId});
        }
      }).catch(err => {
        this.loading = false;
        this.$message({
          type: 'error',
          message: err
        })
      });
    }
  }
}
</script>

<style scoped>
.dialog-ocpp >>> .el-dialog {
  width: 100%;
  max-width: 500px;
}
.form-row {
  padding: 10px 0;
}
.label {
  color: #000;
  font-size: 14px;
  line-height: 21px;
  font-weight: bold;
  padding-bottom: 10px;
}
.form-text {
  color: #333;
  font-size: 14px;
}
.form-item {
  margin-bottom: 0;
}
.button {
  margin-top: 20px;
  padding: 10px 40px;
  border-radius: 2px;
}
</style>