<!--
 * @Descripttion: 
 * @version: 
 * @Author: congsir
 * @Date: 2022-08-08 16:52:58
 * @LastEditors: fakerwu fakerwu@msi.com
 * @LastEditTime: 2023-07-06 16:09:57
-->


<template>
  <el-button v-bind="$attrs" @click="handleClick()">
    <slot>汇出</slot>
  </el-button>
</template>
  
  <script>
export default {
  name: 'firefly-export',

  props: {
    searForm: {
      type: Object,
      default: () => {}
    },
    path: {
      type: String
    },
    exportApi: {
      type: Function,
      require: true
    }
  },

  data() {
    return {
      name: ''
    };
  },

  mounted() {},

  methods: {
    // 导出excel
    handleClick() {
      let isApi = this.isPromise(this.exportApi());
      if (isApi) {
        this.exportApi(this.searForm, this.path).then(res => {
          console.log(res, 'res');
          if (!res.headers) {
            this.$message.error('请填写正确的接口地址');
            // throw new Error('请填写正确的接口');
          } else {
            this.name = decodeURIComponent(res.headers['content-disposition'].split('=')[2]).slice(7);
            this.downLoad(res.data, this.name);
          }
        });
      } else {
        this.$message.error('请配置一个返回promise接口函数');
        // throw new Error('请配置一个返回promise接口函数');
      }
    },
    isPromise(obj) {
      if (Promise && Promise.resolve) {
        return Promise.resolve(obj) == obj;
      } else {
        this.$message.error('当前环境不支持 Promise !');
        // throw new Error('当前环境不支持 Promise !');
      }
    },
    downLoad(res, name) {
      const link = document.createElement('a');
      link.style.display = 'none';
      link.href = URL.createObjectURL(res);
      link.setAttribute('download', name);

      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  }
};
</script>
  
  <style lang="scss" scoped></style>
  