<template>
  <div class="upload">
    <el-upload action :show-file-list="false" :http-request="httpRequest">
      <slot></slot>
      <el-button type="text" 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="fileList.length">
      <div class="file-list-item" v-for="(fileUrl, index) in fileList" :key="index">
        <a :href="fileUrl" target="_blank">
          <i class="el-icon-document"></i>
          {{ fileUrl | fileName }}
        </a>
        <a :href="fileUrl" :download="fileUrl | 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'

export default {
  name: 'VUpload',
  props: {
    value: { type: [String, Array] }
  },
  data() {
    return {
      fileList: []
    }
  },
  watch: {
    value(value) {
      if (value) {
        this.fileList = Array.isArray(value) ? value : [value]
      }
    }
  },
  filters: {
    fileName(value) {
      return value ? value.split('/').pop() : ''
    }
  },
  methods: {
    httpRequest(xhr) {
      api.uploadFile({ file: xhr.file }).then(response => {
        if (response.success) {
          if (Array.isArray(this.value)) {
            this.fileList.push(response.url)
            this.$emit('input', this.fileList)
          } else {
            this.fileList = [response.url]
            this.$emit('input', response.url)
          }
        }
      })
    }
  }
}
</script>

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

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