<template>
  <div>
    <el-upload
      style="display: inline-block; margin: 0 10px"
      action="import"
      :http-request="handleImport"
      :file-list="importFileList"
    >
      <el-button size="mini" type="primary" :icon="isIcon ? 'el-icon-download' : ''" :loading="importLoading">{{
        importLoading ? '导入中...' : imText
      }}</el-button>
    </el-upload>
  </div>
</template>

<script>
import { handleImport } from '@/utils/util'

export default {
  name: 'ImportButton',
  props: {
    imText: {
      // 按钮文字
      type: String,
      default: '导入数据'
    },
    isIcon: {
      // 是否显示icon图标
      type: Boolean,
      default: true
    },
    imUrl: {
      // 导入地址
      type: String,
      default: ''
    },
    imParams: {
      // 导入参数
      type: Object,
      default: null
    }
  },
  data() {
    return {
      importLoading: false,
      importFileList: []
    }
  },
  methods: {
    async handleImport(param) {
      this.importLoading = true
      const file = param.file
      const formData = new FormData()
      formData.append('file', file)

      if (this.imParams) {
        for (let key in this.imParams) {
          if (this.imParams.hasOwnProperty(key)) {
            formData.append(key, this.imParams[key])
          }
        }
      }
      handleImport(this.imUrl, formData).then(result=>{
        this.importLoading = false
        this.importFileList = []
        if (result.code == 200) {
          this.$alert(result.message, '导入成功', {
            confirmButtonText: '确定'
          })
          this.$emit('importSuccess', result.data)
        } else {
          this.$alert(result.message, '导入失败', {
            confirmButtonText: '确定'
          })
        }
      })
    }
  }
}
</script>

<style></style>
