<template>
  <el-upload
    action="/api-web/uploadFile"
    :headers="headers"
    :on-success="success"
    :on-remove="remove"
    :on-error="error"
    :limit="1"
    :file-list="filelist"
    :accept="accept">
    <el-button size="small" type="primary" plain>点击上传</el-button>
    <div slot="tip" v-if="tips" class="el-upload__tip">{{tips}}</div>
  </el-upload>
</template>

<script>
import { getToken } from '@/utils/auth'
export default {
  name: 'singe-file-upload',
  props: {
    tips: {
      type: String,
      default: ''
    },
    value: {
      type: String,
      default: ''
    },
    accept: {
      type: String,
      default: ''
    }
  },
  watch: {
    value: {
      handler() {
        if (this.value) {
          this.filelist = [{
            name: this.value,
            url: this.value,
          }]
        } else {
          this.remove()
        }
      },
      immediate: true
    }
  },
  data() {
    return {
      filelist: [],
      headers: {
        Authorization: getToken()
      },
    }
  },
  methods: {
    remove() {
      this.filelist = []
      this.$emit('update:value', '')
      this.$emit('input', '')
    },
    error() {
      this.remove()
    },
    success(res) {
      if (res.code == 200) {
        this.filelist = [{
          name: res.data.url,
          url: res.data.url,
        }]
        this.$emit('update:value', res.data.url)
        this.$emit('input', res.data.url)
      } else {
        this.remove()
        this.$message.error(res.msg || '上传失败')
      }
    },
  }
}
</script>
