<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="filter-view">
        <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>
        <div class="flex1" style="max-width: 350px;">
          <el-input
            class="filter-view-item"
            v-model="filter.pageVo.criteria"
            prefix-icon="el-icon-search"
            placeholder="Search by Site Name, Address, Carpark Code"
            @keyup.enter.native="handleFilter"
            @change="handleFilter"
            clearable/>
        </div>
        <div>
          <el-button
            v-waves
            type="primary"
            icon="el-icon-search"
            @click="handleFilter">
            Search
          </el-button>
        </div>
        <div class="filter-flex-button">
          <el-button
            v-if="visible.addButton"
            type="primary"
            icon="el-icon-plus"
            @click="handleClickAddSiteButton">
              Add Site
          </el-button>
        </div>
      </div>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      style="width: 100%;">
      <!--el-table-column
        label="Site ID"
        prop="sitePk"
        align="center"
        width="80">
          <template slot-scope="{row}">
            <span>{{ row.sitePk }}</span>
          </template>
      </el-table-column-->
      <el-table-column
        label="Site Name"
        prop="siteName"
        align="center"
        min-width="260">
          <template slot-scope="{row}">
            <span>{{ row.siteName }}</span>
          </template>
      </el-table-column>
      <el-table-column
        label="Carpark Code"
        prop="carParkCode"
        align="center"
        min-width="125"/>
      <el-table-column
        label="Address"
        prop="siteAddress"
        align="center"
        min-width="280">
        <template slot-scope="{row}">
          <span>{{ row.siteAddress }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="Service Provider"
        prop="siteName"
        align="center"
        min-width="180">
        <template slot-scope="{row}">
          <div
            v-for="item in row.serviceProviders"
            :key="item">
            {{item}}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="Rate Plan"
        prop="siteName"
        align="center"
        min-width="200">
        <template slot-scope="{row}" v-if="row.dynamicRates">
          <div
            v-for="(item,index) in row.dynamicRates"
            :key="index"
            style="cursor: alias;"
            @click="viewRateDialog(row)">
            {{item}}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="Total Stations"
        prop="stationNo"
        align="center"
        min-width="100">
          <template slot="header" slot-scope="scope">
            <div>Stations</div>
            <div style="font-size: 0.8em; margin-top: -5px;">(In Use/Total)</div>
          </template>
          <template slot-scope="{row}">
            <span>{{ row.stationInUse || "0" }}/{{ row.stationNo || "0" }}</span>
          </template>
      </el-table-column>
      <el-table-column
        label="Total Connectors"
        prop="connectorNo"
        align="center"
        min-width="100"
        class-name="fixed-width">
          <template slot="header" slot-scope="scope">
            <div>Connectors</div>
            <div style="font-size: 0.8em; margin-top: -5px;">(In Use/Total)</div>
          </template>
          <template slot-scope="{row}">
            <span>{{ row.connectorInUse || "0" }}/{{ row.connectorNo || "0"}}</span>
          </template>
      </el-table-column>
      <!--el-table-column
        label="Connectors in Use"
        prop="connectorNo"
        align="center"
        class-name="fixed-width">
          <template slot-scope="{row}">
            <span>{{ row.connectorInUse || "0" }}</span>
          </template>
      </el-table-column-->
      <el-table-column
        v-if="visible.actions"
        label="Action"
        align="center"
        min-width="70">
          <template slot-scope="{row, $index}">
            <!-- <TableAction
              :showDel="visible.actionDelete"
              @edit="handleUpdateSite(row, $index)"
              @delete="handleDeleteSite(row, $index)"/> -->
            <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="handleUpdateSite">
                  Edit
                </el-dropdown-item>
                <el-dropdown-item
                  command="handleDeleteSite">
                  Delete
                </el-dropdown-item>
                <el-dropdown-item
                  command="viewRateDialog">
                  View Rate
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </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>
    <history-rate
      v-bind="actionRate"
      @hide="hideRateDialog"
    />
  </div>
</template>

<script>

// waves directive
import waves from '@/directive/waves'
// secondary package based on el-pagination
import Pagination from '@/components/Pagination'
import TableAction from '@/components/TableAction.vue'
import site from '../../http/api/site'
import provider from '../../http/api/provider'
import { getRoleName } from '@/utils/auth'
import historyRate from './historyRate.vue'

export default {
  name: 'SiteManagement',
  components: { Pagination, TableAction, historyRate },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      filter: {
        pageNo: 1,
        pageSize: 10,
        pageVo: {
          criteria: '',
          providerPk: ''
        }
      },
      providerOptions: [],
      visible: {
        actions: true,
        actionDelete: true,
        addButton: true,
      },
      actionRate: {
        id: 0,
        visible: false
      }
    }
  },
  created() {
    this.getAllProvider();
    this.getList();
    this.setVisible();
  },
  methods: {
    setVisible() {
      const role = getRoleName()
      if (role === "MCST") {
        this.visible.actionDelete = false
        this.visible.addButton = false
      } else if (this.$route.meta.onlyView) {
        this.visible.actions = false
        this.visible.addButton = false
      }
    },
    getAllProvider() {
      provider.getAllServiceProvider().then(res => {
        if (res.data && res.data.length > 0) {
          this.providerOptions = res.data
        }
      });
    },
    getList() {
      this.listLoading = true
      site.getSiteList(this.filter).then(res => {
        if (res.data && res.total) {
          this.list = res.data
          this.total = res.total
        } else {
          this.list = []
          this.total = 0
        }
      }).catch(err => {
        this.$message({
          message: err,
          type: 'error'
        })
        this.list = []
        this.total = 0
      }).finally(() => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.filter.pageNo = 1
      this.getList()
    },
    handleClickAddSiteButton() {
      //this.$router.push({ path: '/site-management/add-site' })
      this.$router.push({ path: '/site-management/add' })
    },
    handleUpdateSite(row) {
      /*this.$store.commit('site/SET_SELECTED_SITE', row)
      this.$router.push({ path: '/site-management/update-site' })*/
      this.$router.push({ path: '/site-management/edit/' + row.sitePk })
    },
    handleDeleteSite(row) {
      this.$confirm(
        'Are you sure you want to delete this site ?',
        'Delete', {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(res => {
        site.deleteSite({ sitePk: row.sitePk }).then(() => {
          this.$message({
            message: `delete site success ${row.siteName}`,
            type: "success",
            duration: 3000,
          })
          this.list.splice(index, 1)
        }).catch(error => {
          this.$message({
            message: error,
            type: "error",
            duration: 3000,
          })
        })
      })
    },
    handleCommand(cb, item) {
      this[cb](item)
    },
    viewRateDialog(row) {
      this.actionRate.visible = true;
      this.actionRate.id = row.sitePk;
    },
    hideRateDialog() {
      this.actionRate.visible = false;
    }
  }
}
</script>

