<template>
  <el-popover
    placement="top"
    width="300"
    v-model="visible">
    <p>导出日期选择</p>
    <m-form ref="exportRefs" label-width="60px" :items="exportItems" v-model="exportValues"></m-form>
    <div style="text-align: right; margin: 0">
      <el-button size="mini" @click="visible = false">取消</el-button>
      <el-button type="orange" size="mini" @click="onClick">导出</el-button>
    </div>
    <m-button slot="reference" size="mini" type="orange" icon="el-icon-download" :loading="exportLoading">导出</m-button>
  </el-popover>
</template>

<script>
import { downloadFile } from '@/utils'
export default {
  name: 'exportByDate',
  props: {
    searchValue: {
      type: String,
      default: 'month'
    },
    searchType: {
      type: String,
      default: 'month'
    },
    searchFormat: {
      type: String,
      default: 'yyyy-MM'
    },
    onExport: {
      type: Function,
      default: () => {}
    }
  },
  data () {
    return {
      visible: false,
      exportValues: {
        [this.searchValue]: null
      },
      exportLoading: false
    }
  },
  computed: {
    exportItems () {
      return [
        {
          label: '时间',
          type: 'datePicker',
          prop: this.searchValue,
          options: {
            size: 'mini',
            placeholder: '请选择时间',
            type: this.searchType,
            valueFormat: this.searchFormat
          },
          rules: [
            { required: true, message: '请选择时间', trigger: 'change' }
          ]
        }
      ]
    }
  },
  methods: {
    onClick () {
      this.$refs.exportRefs.validate(async valid => {
        if (!valid) {
          return
        }
        this.visible = false
        this.exportLoading = true
        try {
          const { data, name } = await this.onExport(this.exportValues)
          downloadFile(data, name)
        } catch (error) {
          this.$message.error(error)
        } finally {
          this.exportLoading = false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
