<style scoped>
.file-icon {
  color: #8c8c8c;
}
.file-link {
  color: #2f54eb;
  display: flex;
  align-items: center;
}
.file-name {
  padding: 0px 15px;
}
.file-name:hover {
  color: #69c0ff;
}
.file-delete {
  color: #d9d9d9;
}
.file-delete:hover {
  color: #f5222d;
}
</style>

<template>
  <el-upload
    :action="url"
    :show-file-list="false"
    :headers="headers"
    :data="param"
    :on-success="handleSuccess"
    :before-upload="beforeUpload"
    style="width: 100%;"
  >
    <span v-if="value" class="file-link" @click.stop>
      <i class="iconfont icon-attachment file-icon"></i>
      <a class="file-name" :href="value" target="_blank">点击下载</a>
      <i class="iconfont icon-close file-delete" title="点击删除" @click="deleteFile"></i>
    </span>
    <el-button v-else size="small" type="primary">点击上传</el-button>
  </el-upload>
</template>

<script>
export default {
  props: {
    headers: {
      type: Object,
      default() {
        return {}
      }
    },
    url: {
      type: String,
      required: true
    },
    value: String,
    param: {
      type: Object,
      default() {
        return {};
      }
    },
    maxMB: {
      type: Number,
      default: 2
    }
  },
  name: 'FileUpload',
  methods: {
    handleSuccess(response = {}, file, fileList) {
      const { result = [] } = response
      const url = result[0]
      this.$emit('input', url)
    },
    beforeUpload(file) {
      const isLtMaxMB = file.size / 1024 / 1024 < this.maxMB
      if (!isLtMaxMB) {
        this.$message.error(`上传附件大小不能超过 ${this.maxMB}MB!`)
      }
      return isLtMaxMB
    },
    deleteFile() {
      this.$emit('input', undefined)
    }
  }
}
</script>
