<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="filter-view">
        <div
          v-if="sitePk"
          class="back-icon"
          @click="goBack">
          <i class="el-icon el-icon-back"></i>
        </div>
        <el-select
          class="filter-view-item"
          v-model="filter.pageVo.providerPk"
          placeholder="Service Provider"
          @change="handleFilter"
          clearable>
          <el-option
            v-for="(item, index) in providerOptions"
            :key="index"
            :label="item.providerName"
            :value="item.providerPk"/>
        </el-select>
        <el-select
          class="filter-view-item"
          v-model="filter.pageVo.heartbeatPeriod"
          placeholder="Heartbeat Period"
          @change="handleFilter"
          clearable>
          <el-option
            v-for="(item, index) in heartOptions"
            :key="index"
            :value="item.value"
            :label="item.name"/>
        </el-select>
        <el-select
          class="filter-view-item"
          clearable
          v-model="filter.pageVo.dataStatus"
          placeholder="Station Status"
          @change="handleFilter"
          v-if="sitePk">
          <el-option
            v-for="(item, index) in statusOptions"
            :key="index"
            :value="item.value"
            :label="item.name"/>
        </el-select>
        <div class="flex1" style="max-width: 350px;">
          <el-input
            class="filter-view-item"
            v-model="filter.pageVo.criteria"
            prefix-icon="el-icon-search"
            placeholder="Station ID, Site Name, Carpark Code"
            @keyup.enter.native="handleFilter"
            @change="handleFilter"
            clearable/>
        </div>
        <div>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="handleFilter">
            Search
          </el-button>
        </div>
          
        <div class="filter-flex-button">
          <el-button
            v-if="!$route.meta.onlyView"
            type="primary"
            icon="el-icon-plus"
            @click="addStation">
              Add Station
          </el-button>
        </div>
      </div>
    </div>
    <el-table
      v-loading="listLoading"
      :data="stationList"
      class="no-border"
      style="width: 100%;min-height: 65vh;">
      <el-table-column
        label="Station ID"
        align="center"
        min-width="150">
          <template slot-scope="{row}">
            <span>{{ row.chargeBoxId }}</span>
          </template>
      </el-table-column>
      <el-table-column
        label="Site Name"
        align="center"
        min-width="150">
          <template slot-scope="{row}">
            <span>{{ row.siteName }}</span>
          </template>
      </el-table-column>
      <el-table-column
        label="Carpark Code"
        prop="carParkCode"
        align="center"
        min-width="120"/>
      <el-table-column
        label="Service Provider"
        align="center"
        min-width="140">
          <template slot-scope="{row}">
            <span>{{ row.providerName }}</span>
          </template>
      </el-table-column>
      <el-table-column
        label="Last Heartbeat"
        align="center"
        min-width="150">
          <template slot-scope="{row}">
            <span>{{ row.lastHeartbeat }}</span>
          </template>
      </el-table-column>
      <el-table-column
        label="Connector"
        align="center"
        min-width="100">
        <template slot="header" slot-scope="scope">
          <div>Connector</div>
          <div style="font-size: 0.8em; margin-top: -5px;">(In Use/Total)</div>
        </template>
          <template slot-scope="{row}">
            <span>{{row.inUse || "0" }}/{{row.all || "0"}}</span>
          </template>
      </el-table-column>
      <el-table-column
        label="Status"
        align="center"
        prop="dataStatus"
        min-width="90"/>
      <el-table-column
        v-if="!$route.meta.onlyView"
        label="Action"
        align="center"
        min-width="70">
          <template slot-scope="{row}" v-if="row.dataStatus != 'Inactive'">
            <el-dropdown
              class="action-dropdown"
              @command="(v) => handleCommand(v, row)">
              <i class="el-icon-more icon-action"></i>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  command="editStation">
                  Edit
                </el-dropdown-item>
                <el-dropdown-item
                  command="softReset">
                  Soft Reset
                </el-dropdown-item>
                <el-dropdown-item
                  command="hardReset">
                  Hard Reset
                </el-dropdown-item>
                <el-dropdown-item
                  command="delStation">
                  Delete
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <!-- <TableAction
              @edit="editStation(row)"
              @delete="delStation(row)"/> -->
          </template>
      </el-table-column>
    </el-table>
    <div class="right">
      <Pagination
        v-show="total > 0"
        :total="total"
        :page.sync="filter.pageNo"
        :limit.sync="filter.pageSize"
        @pagination="getList" />
    </div>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import TableAction from '@/components/TableAction.vue'
import api from '../../http/api/charge'
import ocpp from '../../http/api/ocpp'
import provider from '../../http/api/provider'
export default {
  components: { Pagination, TableAction },
  data() {
    return {
      filter: {
        pageNo: 1,
        pageSize: 10,
        pageVo: {
          criteria: '',
          dataStatus: '',
          providerPk: '',
          heartbeatPeriod: 'ALL'
        }
      },
      listLoading: true,
      stationList: [],
      heartOptions: [],
      statusOptions: [],
      providerOptions: [],
      total: 1,
      sitePk: ""
    }
  },
  created() {
    if (this.$route.params.id) {
      this.filter.sitePk = this.sitePk = this.$route.params.id;
      this.getStatusOptions();
    }
    this.getAllProvider();
    this.getHeartbeatOptions();
    this.getList();
  },
  methods: {
    goBack() {
      this.$router.push({
        path: "/site-management/edit/" + this.sitePk
      })
    },
    handleFilter() {
      this.filter.pageNo = 1;
      this.getList();
    },
    handlePageChange() {
      this.listLoading = true;
      this.getList();
    },
    getHeartbeatOptions() {
      api.getHeartbeatPeriodList().then(res => {
        this.heartOptions = res.data;
      }).catch(err => {
        this.$message.error(err);
      });
    },
    getStatusOptions() {
      api.getStatusOptions().then(res => {
        this.statusOptions = res.data;
        /*this.statusOptions.unshift({
          name: "All",
          value: ""
        })*/
      }).catch(err => {
        this.$message.error(err);
      });
    },
    getAllProvider() {
      provider.getAllServiceProvider().then(res => {
        if (res.data && res.data.length > 0) {
          this.providerOptions = res.data
        }
      }).catch(err => {
        this.$message.error(err);
      });
    },
    getList() {
      this.listLoading = true;
      api.getStationPages(this.filter).then(res => {
        this.listLoading = false;
        this.total = res.total;
        this.stationList = res.data;
      }).catch(err => {
        this.$message.error(err);
        this.listLoading = false;
        this.total = 0;
        this.stationList = [];
      });
    },
    handleCommand(cb, item) {
      this[cb](item)
    },
    addStation() {
      this.$router.push({
        path: '/charge-station-management/add-station',
      });
    },
    editStation(row) {
      //console.log('row', row);
      //this.$store.commit('charge/SET_StationId', row.chargeBoxPk)
      this.$router.push({
        path: '/charge-station-management/edit-station/' + row.chargeBoxPk,
      });
    },
    softReset(row) {
      this.$confirm("Confirm soft reset?", "Reset",  {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(res => {
        const params = {
          resetType: "SOFT",
          stationIds: [row.chargeBoxId]
        }
        this.resetStation(params);
      }).catch(err => {
        this.$message.error(err);
      });
    },
    hardReset(row) {
      this.$confirm("Confirm hard reset?", "Reset",  {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(res => {
        const params = {
          resetType: "HARD",
          stationIds: [row.chargeBoxId]
        }
        this.resetStation(params);
      }).catch(err => {
        this.$message.error(err);
      });
    },
    resetStation(params) {
      this.listLoading = true;
      ocpp.sendPerform("ocppOperations/reset", params).then(res => {
        this.listLoading = 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.listLoading = false;
        this.$message({
          type: 'error',
          message: err
        })
      });
    },
    delStation(row) {
      this.$confirm('Are you sure you want to delete this station ?', 'Delete', {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(res => {
        this.deleteStation(row.chargeBoxPk)
      }).catch(err => {
        this.$message.error(err);
      });
    },
    deleteStation(id) {
      api.deleteStation({chargeBoxPk: id}).then(res => {
        this.$message({
          message: 'Delete station successfully',
          type: 'success'
        });
        this.listLoading = true;
        this.getList();
      }).catch(err => {
        this.$message({
          message: err,
          type: 'error'
        })
      })
    }
  }
}
</script>
<style>
  .back-icon {
    width: 30px;
    height: 30px;
    padding: 10px;
    display: flex;
    cursor: pointer;
    font-size: 18px;
    align-items: center;
  }
</style>