<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%;">
        <div class="filter-view">
          <div style="flex: 1; min-width: 200px; max-width: 350px;">
            <el-input
              v-model="filter.criteria"
              placeholder="Search by User ID or Station ID"
              @keyup.enter.native="handleFilter" />
          </div>
          <div>
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="handleFilter">
              Search
            </el-button>
          </div>
          <div class="filter-flex-button"></div>
          <div>
            <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>
          </div>
          <div>
            <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>
          </div>
        </div>
      </el-form>
    </div>
    <el-table
      v-loading="listLoading"
      :data="tableList"
      class="no-border"
      style="width: 100%;min-height: 65vh;">
      <el-table-column
        min-width="120"
        label="Transaction ID"
        align="center"
        class-name="fixed-width">
        <template slot-scope="{row}">
          <span
            class="link-type"
            @click="viewTransiction(row)">
            {{ row.transactionPk }}
          </span>
        </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="Email"
        align="center"
        min-width="100">
        <template slot-scope="{row}">
          <span :title="row.email">{{ row.email }}</span>
        </template>
      </el-table-column>
      <!--el-table-column
        label="Phone No."
        align="center">
        <template slot-scope="{row}">
          <span :title="row.phoneNo">{{ row.phoneNo }}</span>
        </template>
      </el-table-column-->
      <el-table-column
        label="User Type"
        align="center"
        min-width="120">
        <template slot-scope="{row}">
          <span :title="row.userType">{{ row.userType }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="Vehicle"
        align="center"
        prop="vehicle"
        min-width="120">
        <template slot-scope="{row}" v-if="row.vehicles">
          <span
            v-for="(item, idx) in row.vehicles"
            :key="idx"
            style="display: block;"
            :title="item">
            {{item}}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="Station ID"
        align="center"
        min-width="120">
        <template slot-scope="{row}">
          <div
            class="link-detail"
            @click="viewTransiction(row)"
            :title="row.chargeBoxId">
            {{ row.chargeBoxId }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        min-width="90"
        label="Connector"
        align="center">
        <template slot-scope="{row}">
          <span>{{ row.connectorId }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="Start Date/Time"
        align="center"
        min-width="140">
        <template slot-scope="{row}">
          <span :title="row.startDateTime">{{ row.startDateTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="End Date/Time"
        align="center"
        min-width="140">
        <template slot-scope="{row}">
          <span :title="row.endDateTime">{{ row.endDateTime  }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="Power (kWh)"
        align="center"
        min-width="120">
        <template slot-scope="{row}">
          <span :title="row.power">{{ row.power  }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="Rate"
        align="center"
        min-width="150">
        <template slot-scope="{row}" v-if="row.rate">
          <span
            v-for="(item, idx) in row.rate.split(';')"
            :key="idx"
            style="display: block;"
            :title="item">
            {{item}}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="Duration"
        align="center"
        min-width="100">
        <template slot-scope="{row}">
          <span :title="row.totalHour">{{ row.totalHour }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="Total Min"
        align="center"
        min-width="100">
        <template slot-scope="{row}">
          <span :title="row.totalMin">{{ row.totalMin }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="Charges"
        align="center"
        min-width="100">
        <template slot-scope="{row}">
          <span :title="row.charges">{{ row.charges }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="Invoice"
        align="center"
        min-width="80">
        <template slot-scope="{row}">
          <i
            class="download-invoice el-icon-download"
            title="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() {
      api.getTransactionPages({
        pageSize: this.listQuery.limit,
        pageNo: this.listQuery.page,
        pageVo: this.filter
      }).then(res => {
        if (res.data && res.total) {
          this.tableList = res.data
          this.total = res.total
        } else {
          this.tableList = []
          this.total = 0
        }
      }).catch(err => {
        this.$message({
          type: "error",
          message: err
        })
      }).finally(() => {
        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)
      }
    },
    viewTransiction(row) {
      this.$router.push({
        path: "/station-activities/transactions/" + row.transactionPk
      })
    }
  }
}
</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 {
    word-break: break-word;
  }
  .download-invoice {
    color: #0000FF;
    cursor: pointer;
  }
</style>