<template>
  <div class="upload">
    <el-upload action :show-file-list="false" :http-request="httpRequest">
      <el-button size="small" icon="el-icon-upload">点击上传</el-button>
      <template v-slot:tip>
        <div class="el-upload__tips">
          <slot name="tip"></slot>
        </div>
      </template>
    </el-upload>
    <div class="file-list" v-if="value">
      <div class="file-list-item">
        <a :href="value" target="_blank">
          <i class="el-icon-document"></i>
          {{ fileName }}
        </a>
        <a :href="value" :download="fileName" target="_blank">
          <el-tooltip effect="dark" content="下载">
            <i class="el-icon-download"></i>
          </el-tooltip>
        </a>
      </div>
    </div>
  </div>
</template>

<script>
import * as api from '../api/index'

export default {
  name: 'VUpload',
  props: {
    value: { type: String }
  },
  data() {
    return {}
  },
  computed: {
    fileName() {
      return this.value ? this.value.split('/').pop() : ''
    }
  },
  methods: {
    httpRequest(xhr) {
      api
        .uploadFile({ file: xhr.file })
        .then(response => {
          if (response.success) {
            this.$emit('input', response.url)
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    handleRemove() {
      this.$emit('input', '')
    }
  }
}
</script>

<style lang="scss" scoped>
.file-list-item {
  display: flex;
  margin-bottom: 10px;
  padding: 0 10px;
  justify-content: space-between;
  background-color: #fff;
  border-radius: 4px;

  a {
    text-decoration: none;
    color: #333;
    &:hover {
      color: #b49441;
    }
  }
}
</style>
