<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form
        :model="filter"
        v-bind:inline="true"
        label-position="left"
        label-width="0px"
        style="width: 100%;">
        <el-row :gutter="0">
          <el-col :xs="16" :sm="12" :md="8">
            <el-form-item
              class="flex-item">
              <el-input
                v-model="filter.criteria"
                placeholder="Search by User ID or Station ID"
                @keyup.enter.native="handleFilter" />
            </el-form-item>
          </el-col>
          <el-col :xs="8" :sm="12" :md="8">
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="handleFilter">
              Search
            </el-button>
          </el-col>
        </el-row>
        <el-row :gutter="0">
          <el-col :sm="12" :md="8">
            <el-form-item
              class="flex-item">
              <el-select
                v-model="filter.filter"
                placeholder="Select"
                @change="handleFilter">
                <el-option
                  v-for="(item, index) in filterOPtions"
                  :key="index"
                  :label="item.name"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="6">
            <el-form-item
              class="flex-item">
              <el-date-picker
                v-model="filter.dateRange"
                type="daterange"
                range-separator="To"
                start-placeholder="Start Date"
                end-placeholder="End Date"
                value-format="yyyy-MM-dd"
                @change="handleFilter">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <el-table
      v-loading="listLoading"
      :data="tableList"
      fit
      style="width: 100%;min-height: 65vh;">
      <el-table-column
        width="150"
        label="Transaction ID"
        align="center"
        class-name="fixed-width">
        <template slot-scope="{row}">
          <router-link :to="'/transactions-reservations/transactions/'+row.transactionPk" class="table-link">{{ row.transactionPk }}</router-link>
        </template>
      </el-table-column>
      <el-table-column
        label="User ID"
        align="center"
        width="80">
          <template slot-scope="{row}">
            <span>{{ row.userPk }}</span>
          </template>
      </el-table-column>
      <el-table-column
        label="User Type"
        align="center"
        prop="userType"/>
      <el-table-column
        label="Vehicle"
        align="center"
        prop="vehicle">
        <template slot-scope="{row}" v-if="row.vehicle">
          <span
            v-for="(item, idx) in row.vehicle.split(',')"
            :key="idx"
            style="display: block;">
            {{item}}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="Station ID"
        align="center"
        class-name="fixed-width">
          <template slot-scope="{row}">
            <router-link :to="'/transactions-reservations/transactions/'+row.transactionPk" class="table-link">{{ row.chargeBoxId }}</router-link>
          </template>
      </el-table-column>
      <el-table-column
        width="100"
        label="Connector"
        align="center"
        class-name="fixed-width">
          <template slot-scope="{row}">
            <span>{{ row.connectorId }}</span>
          </template>
      </el-table-column>
      <el-table-column
        label="Start Date/Time"
        align="center"
        class-name="fixed-width">
          <template slot-scope="{row}">
            <span :title="row.startDateTime">{{ row.startDateTime }}</span>
          </template>
      </el-table-column>
      <el-table-column
        label="End Date/Time"
        align="center"
        class-name="fixed-width">
          <template slot-scope="{row}">
            <span :title="row.endDateTime">{{ row.endDateTime  }}</span>
          </template>
      </el-table-column>
      <el-table-column
        label="Power (kWH)"
        align="center"
        class-name="fixed-width">
          <template slot-scope="{row}">
            <span>{{ row.power  }}</span>
          </template>
      </el-table-column>
      <el-table-column
        label="Rate"
        align="center"
        class-name="fixed-width">
          <template slot-scope="{row}">
            <span>{{ row.rate }}</span>
          </template>
      </el-table-column>
      <el-table-column
        label="Charges"
        align="center"
        class-name="fixed-width">
          <template slot-scope="{row}">
            <span>{{ row.charges }}</span>
          </template>
      </el-table-column>
      <el-table-column
        label="Invoice"
        align="center"
        class-name="fixed-width">
          <template slot-scope="{row}">
            <i class="download-invoice el-icon-download" @click="downloadPdf(row.transactionPk)"></i>
          </template>
      </el-table-column>
    </el-table>
    <div class="right">
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="handlePageChange" />
    </div>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import api from '../../http/api/transaction'

export default {
  components: { Pagination },
  data() {
    return {
      filter: {
        filter: "",
        criteria: "",
        dateRange: []
      },
      filterOPtions: [],
      listLoading: true,
      tableList: [],
      total: 0,
      listQuery: {
        page: 1,
        limit: 10,
      }
    }
  },
  created() {
    this.getFilters();
  },
  methods: {
    handleFilter() {
      this.listLoading = true;
      this.listQuery.page = 1;
      this.getList();
    },
    handlePageChange() {
      this.listLoading = true;
      this.getList();
    },
    async getFilters() {
      const data = await api.getTransactionFilters()
      if (data.success && data.data) {
        this.filterOPtions = data.data
        this.filter.filter = data.data[0].value
        this.getList()
      } else {
        this.listLoading = false
      }
    },
    async getList() {
      const data = await api.getTransactionPages({
        pageSize: this.listQuery.limit,
        pageNo: this.listQuery.page,
        pageVo: this.filter
      })
      if (data.success && data.total) {
        this.tableList = data.data
        this.total = data.total
      } else {
        this.tableList = []
        this.total = 0
      }
      this.listLoading = false
    },
    async downloadPdf(id) {
      try {
        this.listLoading = true;
        const res = await api.downloadInvoice(id);
        if (res && res.size > 0) {
          const name = 'T' + id + '-' + new Date().getTime() + '.pdf'
          this.downloadFile(res, name);
        } else {
          this.$message.error('Empty files');
        }
      } catch (err) {
        
      } finally {
        this.listLoading = false;
      }
    },
    downloadFile(res, fileName) {
      const blob = new Blob([res], {
        type: 'application/pdf;charset=utf-8'
      })
      // let href = window.URL.createObjectURL(blob)
      if ('download' in document.createElement('a')) {
        // 非IE下载
        const elink = document.createElement('a')
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      } else {
        // IE10+下载
        navigator.msSaveBlob(blob, fileName)
      }
    }
  }
}
</script>
<style scoped="scoped">
  .table-link {
    color: #333;
    display: inline-block;
    cursor: pointer;
    white-space: nowrap;
    text-decoration: underline;
  }
  .table-link:hover {
    color: #1290BF;
    text-decoration: none;
  }
  .el-table >>> tr div {
    white-space: nowrap;
  }
  .download-invoice {
    color: #0000FF;
    cursor: pointer;
  }
</style>