<template>
  <p-button :loading="iconLoading" icon="download" type="primary" @click="handleChange">导出</p-button>
</template>
<script>
export default {
  props: {
    exportData: {
      type: Object,
      default() {
        return {
          exportParams: {},
          exportUrl: ''
        }
      }
    },
    fileName: {
      type: String,
      default: 'xxx.xls'
    },
    verify: {
      type: Function,
      default: () => new Promise(resolve => setTimeout(() => resolve(true), 500))
    }
  },
  data() {
    return {
      iconLoading: false,
      flag: false
    }
  },
  created() {
  },
  computed: {},
  methods: {
    callBack(flag) {
      return flag
    },
    async handleChange() {
      this.iconLoading = true
      const flag = await this.verify()
      if (!flag) {
        this.iconLoading = false
        return
      }
      this.$emit('handleChange')
      this.axios({
        method: 'post',
        url: this.exportData.exportUrl,
        headers: {'Content-Type': 'application/json'},
        data: JSON.stringify(this.exportData.exportParams),
        responseType: 'blob'
      }).then(_res => {
        let blob = new Blob([_res])
        let downloadElement = document.createElement('a')
        let href = window.URL.createObjectURL(blob) //创建下载的链接
        downloadElement.href = href
        downloadElement.download = this.fileName //下载后文件名
        document.body.appendChild(downloadElement)
        downloadElement.click() //点击下载
        document.body.removeChild(downloadElement) //下载完成移除元素
        window.URL.revokeObjectURL(href) //释放掉blob对象
      }).finally(()=>{
        this.iconLoading = false
      })
    }
  }
}
</script>
<style lang="less">
.ant-upload-list-text {
  display: none;
}
</style>
