<template>
  <confirm-dialog
    ref="dialog"
    title="设备预警"
    confirm-text="下载"
    @confirm="onConfirm"
  >
    <template #default>
      <div class="c-grid-form auto u-align-self--center">
        <div class="c-grid-form__label u-required">
          日期范围
        </div>
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
          :editable="false"
          :clearable="false"
          @change="handleDateChange"
        />
      </div>
    </template>
  </confirm-dialog>
</template>

<script>
import { parseTime } from '@/utils'
import { getDeviceWarnExcel } from '../api.js'

export default {
  name: 'DeviceWarnDialog',
  data () {
    return {
      dateRange: null
    }
  },
  computed: {
    pickerOptions () {
      return {
        disabledDate: date => date > Date.now()
      }
    }
  },
  methods: {
    handleDateChange (value) {
      if (value && value.length === 2) {
        const startDate = new Date(value[0])
        const endDate = new Date(value[1])
        const dayCount = Math.ceil(Math.abs(endDate - startDate) / (1000 * 60 * 60 * 24))
        if (dayCount > 7) {
          this.$message.error('最多导出7天数据')
          const date = parseTime(new Date(), '{y}-{m}-{d}')
          this.dateRange = [date, date]
        }
      }
    },
    show () {
      const date = parseTime(new Date(), '{y}-{m}-{d}')
      this.dateRange = [date, date]
      this.$refs.dialog.show()
    },
    onConfirm (done) {
      const time = this.dateRange[0] === this.dateRange[1] ? this.dateRange[0] : `${this.dateRange[0]}~${this.dateRange[1]}`
      const endDate = new Date(this.dateRange[1].replace(/-/g, '/'))
      endDate.setDate(endDate.getDate() + 1)
      getDeviceWarnExcel({
        startDate: this.dateRange[0],
        endDate: parseTime(endDate, '{y}-{m}-{d}')
      }, time).then(done)
    }
  }
}
</script>
