<template>
  <div class="upload">
    <el-upload action :disabled="disabled" :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>
        <div>
          <a
            href="javascript:;"
            @click="handleRemove(index)"
            style="margin-right:10px;"
            v-if="!disabled"
          >
            <el-tooltip effect="dark" content="删除">
              <i class="el-icon-delete"></i>
            </el-tooltip>
          </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>
  </div>
</template>

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

export default {
  name: 'VUpload',
  props: {
    value: { type: [String, Array] },
    disabled: { type: Boolean, default: false }
  },
  data() {
    return {
      fileList: []
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(value) {
        if (value) {
          if (Array.isArray(value)) {
            this.fileList = value.map(item => {
              return item.url || item
            })
          } else {
            this.fileList = [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)
          }
        }
      })
    },
    handleRemove(index) {
      this.fileList.splice(index, 1)
      this.$emit('input', Array.isArray(this.value) ? this.fileList : '')
    }
  }
}
</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>
