<template>
  <el-upload
    action="/api-web/uploadFile"
    :headers="headers"
    :on-success="success"
    :on-remove="remove"
    :on-progress="progress"
    :on-error="error"
    :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>
    <div slot="file" slot-scope="{file}">
      <div style="display: flex; align-items: center;flex: 1 auto;justify-content: space-between;">
        <div style="display: flex; align-items: center;overflow: hidden;">
          <i v-if="!!file.url" @click.stop="copyText(file.url)" title="复制" style="padding-right: 5px" class="el-icon-document-copy"></i>
          <span class="upload-text" :title="file.url">{{ file.url }}</span>
        </div>
        <i v-if="!!file.url" class="el-icon-delete" @click="remove"></i>
      </div>
    </div>
  </el-upload>
</template>

<script>
import copy from 'copy-to-clipboard'
import { getToken } from '@/utils/auth'
import load from '@/utils/loading'
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()
      load.endLoading()
    },
    progress() {
      load.startLoading()
    },
    success(res) {
      load.endLoading()
      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 || '上传失败')
      }
    },
    copyText(text) {
      if (text) {
        copy(text)
        this.$message.success('复制成功')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.upload-text {
  display: inline-block;
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>
