<template>
  <el-button v-bind="$attrs" v-on="$listeners" @click="onDownloadClick">{{ btnName }}</el-button>
</template>

<script>
import { download } from '@/utils/request'
import { downloadFiles, getDownloadName } from '@/utils'

export default {
  props: {
    btnName: {
      type: String,
      default: '下载'
    },
    downloadUrl: {
      type: [String, Function],
      default: function() {}
    },
    paramsObj: {
      type: Object,
      default: function() {}
    },
    methodType: {
      type: String,
      default: 'post'
    }
  },
  mounted() {},
  methods: {
    onDownloadClick() {
      if (this.methodType === 'post') {
        console.log(this.downloadUrl, this.methodType, this.paramsObj)
        download(this.downloadUrl, this.methodType, this.paramsObj)
      } else {
        this.doDownload()
      }
    },
    doDownload() {
      const loading = this.$loading({
        lock: true,
        text: '正在下载中，请稍候...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.downloadUrl(this.paramsObj)
        .then((res) => {
          downloadFiles(res, getDownloadName(res))
        })
        .catch((err) => console.error(err))
        .finally(() => {
          setTimeout(() => {
            loading.close()
          }, 500)
        })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>