<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="filter-view">
        <el-select
          v-model="filter.pageVo.errorCode"
          placeholder="Error Code"
          @change="handleFilter"
          class="filter-view-item"
          clearable>
          <el-option
            v-for="(item,index) in errCodeOptions"
            :key="index"
            :label="item.name"
            :value="item.value"/>
        </el-select>
        <el-date-picker
          v-model="filter.pageVo.dateTime"
          type="date"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          clearable
          class="filter-view-item"
          placeholder="Filter Date"
          @change="handleFilter"/>
        <div class="flex2" style="max-width: 500px;">
          <el-input
            v-model="filter.pageVo.criteria"
            prefix-icon="el-icon-search"
            placeholder="Search by Site Name, Station ID, Carpark Code, Vendor Error 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
            type="primary"
            icon="el-icon-download"
            :loading="logLoading"
            @click="handleDownloadLog">
            LOG
          </el-button> -->
          <el-button
            type="primary"
            icon="el-icon-download"
            :loading="logLoading"
            @click="handleExport">
            Export
          </el-button>
        </div>
      </div>
    </div>
    <el-table
      v-loading="listLoading"
      :data="tableList"
      style="width: 100%;">
      <el-table-column
        label="Site"
        align="center"
        min-width="120">
          <template slot-scope="{row}">
            <span>{{ row.siteName }}</span>
          </template>
      </el-table-column>
      <el-table-column
        label="Station ID"
        align="center"
        min-width="120">
          <template slot-scope="{row}">
            <span>{{ row.chargeBoxId }}</span>
          </template>
      </el-table-column>
      <el-table-column
        label="Carpark Code"
        prop="carParkCode"
        align="center"
        min-width="120"/>
      <el-table-column
        label="Connector ID"
        align="center"
        min-width="120">
          <template slot-scope="{row}">
            <span>{{ row.connectorId }}</span>
          </template>
      </el-table-column>
      <el-table-column
        label="Connector Status"
        align="center"
        min-width="140">
          <template slot-scope="{row}">
            <span>{{ row.status }}</span>
          </template>
      </el-table-column>
      <el-table-column
        label="Error Code"
        align="center"
        min-width="100">
          <template slot-scope="{row}">
            <span>{{ row.errorCode }}</span>
          </template>
      </el-table-column>
      <el-table-column
        label="Vendor Error Code"
        align="center"
        min-width="150">
          <template slot-scope="{row}">
            <span>{{ row.vendorErrorCode }}</span>
          </template>
      </el-table-column>
      <el-table-column
        label="Timestamp"
        align="center"
        min-width="120">
          <template slot-scope="{row}">
            <span>{{ row.statusTimestamp }}</span>
          </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="handlePageChange" />
    </div>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import TableAction from '@/components/TableAction.vue'
import api from '../../http/api/incident'
import charge from '../../http/api/charge'

export default {
  components: { Pagination, TableAction },
  data() {
    return {
      filter: {
        pageNo: 1,
        pageSize: 10,
        pageVo: {
          dateTime: "",
          criteria: "",
          errorCode: "",
        }
      },
      listLoading: true,
      logLoading: false,
      tableList: [],
      errCodeOptions: [],
      total: 0
    }
  },
  created() {
    this.getErrorCodeOptions();
    this.getList();
  },
  methods: {
    handleFilter() {
      this.filter.pageNo = 1;
      this.getList();
    },
    getErrorCodeOptions() {
      charge.getErrorCodeOption().then(res => {
        if (res.data.length > 0) {
          res.data.forEach(item => {
            this.errCodeOptions.push({
              name: item,
              value: item
            })
          })
        }
        this.getConnectorList();
      }).catch(err => {
        this.$message.error(err)
      })
    },
    getList() {
      this.listLoading = true
      api.fetchErrorPages(this.filter).then((response) => {
        const {success, data, total } = response
        if (success) {
          this.tableList = data
          this.total = total
        } else {
          this.tableList = []
          this.total = 0
        }
      }).catch(err => {
        this.$message({
          type: 'error',
          message: err
        })
        this.tableList = []
        this.total = 0
      }).finally(() => {
        this.listLoading = false
      })
    },
    handlePageChange() {
      this.listLoading = true;
      this.getList();
    },
    handleDownloadLog() {
      this.logLoading = true;
      api.downloadLog().then(res => {
        if (res && res.size > 0) {
          const name = 'Log-' + new Date().getTime() + '.log'
          this.downloadFile(res, name);
        } else {
          this.$message.error('Empty files');
        }
      }).catch(err => {
        this.$message({
          type: 'error',
          message: err
        })
      }).finally(() => {
        this.logLoading = false
      })
    },
    handleExport() {
      this.logLoading = true;
      setTimeout(() => {
        if (this.filter.pageVo.dateTime) {
          this.exportTable();
        } else {
          this.logLoading = false;
          this.$message.error('Please select date');
        }
      }, 1500);
    },
    exportTable() {
      api.exportError(this.filter).then(res => {
        if (res && res.size > 0) {
          const name = 'Error Table - ' + new Date().getTime() + '.xls';
          this.downloadFile(res, name);
        } else {
          this.$message.error('Empty files');
        }
      }).catch(err => {
        this.$message({
          type: 'error',
          message: err
        })
      }).finally(() => {
        this.logLoading = 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>
