<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        @keyup.enter.native="handleFilter"
        @keyup.esc.native="handleEsc"
        size="small" style="width: 220px;"
        class="filter-item"
        :placeholder="$t('counter.logSeachContent')" v-model="logsListQuery.device">
      </el-input>
      <div class="date-selector filter-item">
        <el-date-picker
          v-model="dateRange"
          size="small"
          type="daterange"
          align="right"
          :range-separator="$t('counter.to')"
          :start-placeholder="$t('counter.start_date')"
          :end-placeholder="$t('counter.end_date')"
          :picker-options="pickerOptions"
          value-format="yyyy-MM-dd"
          @change="handleDateSelect"
        />
      </div>
      <el-button class="filter-item" size="small" type="primary" v-waves icon="el-icon-search" @click="handleFilter">{{$t('table.search')}}</el-button>
      <el-button :disabled="downloadDisabled" class="filter-item export" :loading="downloadLoading" size="small"
        type="primary" icon="el-icon-document" @click="handleDownload">{{ $t('table.export') }}</el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="logList"
      style="width: 100%"
      :default-sort = "{prop: 'calc_time', order: 'descending'}"
    >
      <el-table-column
        type="index"
        :label="$t('counter.sn')">
      </el-table-column>
      <el-table-column
        prop="device_id"
        :label="$t('counter.device')"
        sortable
        min-width="150">
      </el-table-column>
      <el-table-column
        prop="device_name"
        :label="$t('counter.deviceName')"
        sortable
        min-width="150">
      </el-table-column>
      <el-table-column
        prop="signal"
        :label="$t('counter.signal')"
        min-width="80">
      </el-table-column>
      <el-table-column
        sortable
        prop="mosq_count"
        :label="$t('counter.count')"
        min-width="100">
      </el-table-column>
      <el-table-column
        prop="energy"
        :label="$t('counter.energy')"
        min-width="100">
      </el-table-column>
      <el-table-column
        prop="coordinate"
        :label="$t('counter.coordinate')"
        min-width="280px"
        :formatter="coordinate">
      </el-table-column>
      <el-table-column
        prop="calc_time"
        :label="$t('counter.time')"
        min-width="150">
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination background
        :current-page="1"
        :page-sizes="[10,20,30,50]"
        :page-size="logsListQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
  </div>
</template>

<script>
import { fetchDeviceLogs } from '@/api/counter'
import waves from '@/directive/waves' // 水波纹指令
import { parseTime } from '@/utils'
export default {
  name: 'count',
  directives: {
    waves
  },
  data() {
    return {
      logList: [],
      logExportList: [],
      listLoading: true,
      total: 0,
      logsListQuery: {
        device: undefined,
        limit: 10,
        page: 1,
        start: undefined,
        end: undefined
      },
      pickerOptions: null,
      dateRange: undefined,
      downloadLoading: false,
      downloadDisabled: false,
      filename: undefined
    }
  },
  methods: {
    async getDeviceLogs(params, type = 'table') {
      await fetchDeviceLogs(params).then(response => {
        if (type === 'table') {
          this.logList = response.data.results
        }
        if (type === 'export') {
          this.logExportList = response.data.results
        }
        this.total = response.data.count
        this.listLoading = false
      })
    },
    coordinate(row, column) {
      return row.longitude + ', ' + row.latitude
    },
    handleCurrentChange(page) {
      // console.log(page)
      this.listLoading = true
      this.logsListQuery.page = page
      this.getDeviceLogs(this.logsListQuery)
    },
    handleSizeChange(val) {
      this.logsListQuery.limit = val
      this.getDeviceLogs(this.logsListQuery)
    },
    handleFilter() {
      this.logsListQuery.page = 1
      this.getDeviceLogs(this.logsListQuery)
    },
    handleEsc() {
      this.logsListQuery.page = 1
      this.logsListQuery.device = undefined
      this.getDeviceLogs(this.logsListQuery)
    },
    handleDateSelect(value) {
      if (value === null) {
        this.logsListQuery.start = undefined
        this.logsListQuery.end = undefined
      } else {
        const [start, end] = value
        this.logsListQuery.start = start
        this.logsListQuery.end = end
      }
      // this.getDeviceLogs(this.logsListQuery)
    },
    async handleDownload() {
      const start = this.logsListQuery.start
      const end = this.logsListQuery.end
      if (!start || !end) {
        this.$message({
          message: 'Please select the start/end date',
          type: 'warning'
        })
        return
      }
      this.downloadLoading = true
      const exportQuery = Object.assign({}, this.logsListQuery)
      exportQuery.limit = 5000
      await this.getDeviceLogs(exportQuery, 'export')
      this.filename = 'Device Log List ' + String(start).replace(/-/g, '') + '_' + String(end).replace(/-/g, '') + '.xlsx'

      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['Id', 'Time', 'Device ID', 'Device Name', 'Signal', 'Count', 'Energy', 'Coordinate']
        const filterVal = ['id', 'calc_time', 'device_id', 'device_name', 'signal', 'mosq_count', 'energy', 'coordinate']
        const list = this.logExportList
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
        this.downloadLoading = false
        this.logsListQuery.limit = 10
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  },
  created() {
    this.getDeviceLogs(this.logsListQuery)
  },
  deactivated() {
    this.$destroy(true)
  }
}
</script>

<style lang="scss" scoped>
  .date-selector {
      margin-left: 10px;
  }
  .date-selector /deep/ .el-date-editor .el-range-separator {
      margin-right: 10px !important;
  }
  @media only screen and (max-width: 768px) {
    .filter-container {
    display: block;
      .filter-item {
        display: block;
        float: left;
        margin: 0 0 15px 10px;
      }
      .date-selector {
        margin-left: 0;
        margin-bottom: 0;
      }
      .time-selector {
        margin-left: 0;
      }
    }
  }
</style>

<style lang="scss">
  @media only screen and (max-width: 500px) {
      .el-date-range-picker {
        width: 100% !important;
      }
      .el-date-range-picker__content {
        float: none;
        width: 80%;
      }
  }
</style>
