<template>
  <div>
    <el-date-picker
      v-model="timeRange"
      :picker-options="pickerOptions"
      type="daterange"
      range-separator="至"
      start-placeholder="开始日期"
      end-placeholder="结束日期"
      style="margin-bottom: 10px;" />
    <ve-histogram :data="chartData" :settings="settings" height="350px" />
  </div>
</template>

<script>
import { formatToString, getDate, oneDayTime } from '@/utils/calendarUtil'
import { devAlarmCount } from '@/api/statistics'

const now = new Date()

export default {
  name: 'DevAlarmCount',
  data() {
    return {
      params: {
        beginDate: '',
        endDate: ''
      },
      chartData: {
        columns: ['name', 'count'],
        rows: []
      },
      settings: {
        labelMap: {
          'name': '设备类型',
          'count': '报警数量'
        },
        max: [4]
      },
      timeRange: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近七日',
          onClick(picker) {
            const end = now
            const start = new Date()
            start.setTime(start.getTime() - oneDayTime * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近十日',
          onClick(picker) {
            const end = now
            const start = new Date()
            start.setTime(start.getTime() - oneDayTime * 10)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三十日',
          onClick(picker) {
            const end = now
            const start = new Date()
            start.setTime(start.getTime() - oneDayTime * 30)
            picker.$emit('pick', [start, end])
          }
        }],
        disabledDate(time) {
          const oneMonthLater = new Date(now.getTime() - (oneDayTime * 31))
          return time.getTime() < oneMonthLater
        }
      }
    }
  },
  watch: {
    timeRange: function(newV) {
      if (newV) {
        this.params.beginDate = formatToString(newV[0], 'DATE')
        this.params.endDate = formatToString(newV[1], 'DATE')
      } else {
        this.initTime()
      }
      this.fetchData()
    }
  },
  created() {
    this.initTime()
  },
  activated() {
    this.fetchData()
  },
  methods: {
    initTime() {
      this.params.beginDate = getDate(-7, 'DATE')
      this.params.endDate = getDate(1, 'DATE')

      this.timeRange = [this.params.beginDate, this.params.endDate]
    },
    fetchData() {
      devAlarmCount(this.params).then(response => {
        if (response.code === 200) {
          this.chartData.rows = response.data
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
