<template>
  <div class="app-container">
    <el-tabs v-model="activeName" @tab-click="handleTabClick">
      <el-tab-pane :label="$t('counter.screen')" name="screen">
        <transition>
          <screen 
            :deviceID="this.$store.getters.deviceID"
            :lastItem="lastItem"
            v-if="flag"
          >
          </screen>
        </transition>
      </el-tab-pane>
      <el-tab-pane :label="$t('counter.trendChart')" name="chart">
        <el-row style="background:#fff;padding:16px 16px 0;margin-bottom:32px;">
          <chart
            :chart-data="lineChartData.total"
            :showChart="showChart"
          >
          </chart>
        </el-row>
      </el-tab-pane>
      <el-tab-pane :label="$t('counter.humitureChart')" name="humiture">
        <el-row style="background:#fff;padding:16px 16px 0;margin-bottom:32px;">
          <humiture
            :humiture-data="HumitureData.total"
            :showHumiture="showHumiture"
          >
          </humiture>
        </el-row>
      </el-tab-pane>
    </el-tabs>

    <div class="filter-container">
      <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>
    </div>
    
    <el-table
      v-show="!showHumiture"
      v-loading="listLoading"
      :data="deviceLogs"
      style="width: 100%">
      <el-table-column
        type="index"
        :label="$t('counter.sn')">
      </el-table-column>
      <el-table-column
        prop="device_id"
        :label="$t('counter.device')"
        min-width="150">
      </el-table-column>
      <el-table-column
        prop="total"
        :label="$t('counter.count')"
        min-width="80">
      </el-table-column>
      <el-table-column
        prop="date"
        :label="$t('counter.date')"
        min-width="100">
      </el-table-column>
    </el-table>

    <div v-show="!showHumiture" class="pagination-container">
      <el-pagination background
        :current-page="1"
        :page-sizes="[10,20,30,50]"
        :page-size="deviceHistoryListQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="logsTotal" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <!-- humiture table -->
    <el-table
      v-show="showHumiture"
      v-loading="tempLoading"
      :data="deviceTempTableLogs"
      style="width: 100%">
      <el-table-column
        prop="create_time"
        :label="$t('counter.date')"
        min-width="100">
      </el-table-column>
      <el-table-column
        prop="temperature"
        :label="$t('counter.temperature')"
        min-width="80">
      </el-table-column>
      <el-table-column
        prop="humidity"
        :label="$t('counter.humidity')"
        min-width="80">
      </el-table-column>
    </el-table>

    <!-- humiture paging -->
    <div v-show="showHumiture" class="pagination-container">
      <el-pagination background
        :current-page="1"
        :page-sizes="[10,20,30,50]"
        :page-size="deviceTempListQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tempTotal" @size-change="handleTempSizeChange" @current-change="handleTempCurrentChange" />
    </div>
  </div>
</template>

<script>
import waves from '@/directive/waves' // 水波纹指令
import { fetchDeviceList, fetchDeviceLogsHistory, fetchDeviceTempLog } from '@/api/counter'
import Screen from './components/screen'
import Chart from './components/chart'
import Humiture from './components/humiture'

export default {
  name: 'deviceDetail',
  components: {
    Screen,
    Chart,
    Humiture
  },
  directives: {
    waves
  },
  data() {
    return {
      lineChartData: {
        total: {
          historyData: [],
          xAxis: [],
          title: 'Trend'
        }
      },
      HumitureData: {
        total: {
          historyData: {
            temperature: [],
            humidity: []
          },
          xAxis: [],
          title: ['temperature', 'humidity']
        }
      },
      deviceTempListQuery: {
        device_id: undefined,
        page: 1,
        limit: 20,
        start: undefined,
        end: undefined,
        ordering: '-create_time'
      },
      deviceHistoryListQuery: {
        page: 1,
        limit: 20,
        device_id: undefined,
        start: undefined,
        end: undefined
      },
      listLoading: true,
      tempLoading: true,
      device_id: undefined,
      deviceLogs: [],
      deviceTempLogs: [],
      deviceTempTableLogs: [],
      activeName: 'screen',
      logsTotal: 0,
      tempTotal: 0,
      lastItem: {},
      showScreen: true,
      showChart: false,
      showHumiture: false,
      flag: false,
      pickerOptions: null,
      dateRange: undefined
    }
  },
  watch: {
    activeName(val) {
      if (val === 'chart') {
        this.showChart = true
      }
      if (val === 'humiture') {
        this.showHumiture = true
      }
    }
  },
  methods: {
    getDeviceLogsHistory(params) {
      fetchDeviceLogsHistory(params).then(response => {
        const dateList = []
        this.deviceLogs = response.data.results
        this.deviceLogs.forEach((item, index) => {
          this.lineChartData.total.historyData.push(item.total)
          dateList.push(item.date.substr(5))
        })
        this.lineChartData.total.historyData = this.lineChartData.total.historyData.reverse()
        this.lineChartData.total.xAxis = dateList.reverse()
        this.logsTotal = response.data.count
        this.listLoading = false
      })
    },
    // getDeviceLogsTableHistory(params) {
    //   fetchDeviceLogsHistory(params).then(response => {
    //     this.deviceLogs = response.data.results
    //     this.logsTotal = response.data.count
    //     this.listLoading = false
    //   })
    // },
    getDeviceTempLog(params) {
      fetchDeviceTempLog(params).then(response => {
        const dateList = []
        this.deviceTempLogs = response.data.results
        this.deviceTempLogs.forEach((item, index) => {
          if (index % 2 === 0) {
            this.HumitureData.total.historyData.temperature.push(item.temperature)
            this.HumitureData.total.historyData.humidity.push(item.humidity)
            dateList.push(item.last_time.substr(11, 5))
          }
        })
        this.HumitureData.total.xAxis = dateList
        this.tempTotal = response.data.count
        this.tempLoading = false
      })
    },
    getDeviceTempTableLog(params) {
      fetchDeviceTempLog(params).then(response => {
        this.deviceTempTableLogs = response.data.results
        this.tempTotal = response.data.count
        this.tempLoading = false
      })
    },
    getDevices(params) {
      let device_id = params.device_id
      fetchDeviceList(params).then(response => {
        this.deviceList = response.data.results
        this.lastItem = this.deviceList[0]
        if (!device_id) {
          device_id = this.lastItem.device_id
          this.$store.dispatch('changeDeviceID', device_id)
          console.log(device_id)
        }
        this.getDeviceLogsHistory({ device_id, limit: 20 })
        if (typeof (this.lastItem.count) === 'number') {
          this.lastItem.count = this.lastItem.count.toString()
        }
        this.flag = true
      })
    },
    coordinate(row, column) {
      return row.longitude + ', ' + row.latitude
    },
    handleDateSelect(value) {
      if (value === null) {
        this.deviceHistoryListQuery.start = undefined
        this.deviceHistoryListQuery.end = undefined
      } else {
        const [start, end] = value
        this.deviceHistoryListQuery.start = start
        this.deviceHistoryListQuery.end = end
        this.deviceTempListQuery.start = start
        this.deviceTempListQuery.end = end
      }
    },
    handleFilter() {
      this.deviceHistoryListQuery.page = 1
      this.deviceTempListQuery.page = 1
      this.getDeviceLogsHistory(this.deviceHistoryListQuery)
      this.getDeviceTempTableLog(this.deviceTempListQuery)
    },
    handleCurrentChange(page) {
      this.listLoading = true
      this.deviceHistoryListQuery.device_id = this.device_id
      this.deviceHistoryListQuery.page = page
      // this.getDeviceLogsTableHistory(this.deviceHistoryListQuery)
      this.getDeviceLogsHistory(this.deviceHistoryListQuery)
    },
    handleSizeChange(val) {
      this.listLoading = true
      this.deviceHistoryListQuery.device_id = this.device_id
      this.deviceHistoryListQuery.limit = val
      // this.getDeviceLogsTableHistory(this.deviceHistoryListQuery)
      this.getDeviceLogsHistory(this.deviceHistoryListQuery)
    },
    handleTempCurrentChange(page) {
      this.tempLoading = true
      this.deviceTempListQuery.page = page
      this.deviceTempListQuery.device_id = this.device_id
      this.getDeviceTempLog(this.deviceTempListQuery)
    },
    handleTempSizeChange(val) {
      this.tempLoading = true
      this.deviceTempListQuery.limit = val
      this.deviceTempListQuery.device_id = device_id
      const device_id = this.$store.getters.deviceID
      this.getDeviceTempLog(this.deviceTempListQuery)
    },
    handleTabClick(tab, event) {
      // console.log(tab, event)
      // 解决siderbar变化，disactiveTab没有resize
      if (tab.name === 'chart') {
        this.showHumiture = false
      }
      if (tab.name === 'humiture') {
        this.showChart = false
      }
      if (tab.name === 'screen') {
        this.showHumiture = false
      }
    }
  },
  created() {
    this.device_id = this.$store.getters.deviceID
    this.deviceHistoryListQuery.device_id = this.device_id
    this.deviceTempListQuery.device_id = this.device_id
    this.getDevices({ device_id: this.device_id })
    // this.getDeviceLogsTableHistory({ device_id: this.device_id, limit: 20 })
    this.getDeviceTempLog({ device_id: this.device_id, last_day: 1, limit: 30 })
    this.getDeviceTempTableLog(this.deviceTempListQuery)
  }
}
</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 {
        margin-bottom: 10px;
        display: block;
      }
      .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>

<style lang="scss">
    .v-enter, .v-leave-to {
      opacity: 0;
    }
  .v-enter-active, .v-leave-active {
    transition: opacity 1s
  }
</style>
