<template>
  <el-upload
    class="upload-demo"
    :action="uploadUrl"
    :before-upload="beforeFileUpload"
    :on-remove="picDel"
    :on-success="picSuccess"
    :headers="headers"
    :limit="1"
    :file-list="file_list">
    <el-button size="small" type="primary" v-if="!value">{{loading ? '上传中...' : '点击上传'}}</el-button>
  </el-upload>
</template>

<script>
import { getToken } from '@/utils/auth'
export default {
  name: 'UploadFile',
  props: {
    value: {
      type: Number,
      default: null
    },
    file_name: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      headers: {},
      uploadUrl: process.env.VUE_APP_BASE_API + '/api/admin/upload-file',
      loading: false,
      picUrl: '',
      picDialog: false,
      file_list: [],
    }
  },
  created() {
    this.headers = {Authorization: "Bearer " + getToken()}
    this.file_list = this.value ? [{name: this.file_name, url: this.value.toString()}] : []
  },
  methods: {
     beforeFileUpload(file) {
      this.loading = true
      return true
    },
    picSuccess: function (res, file, fileList) {
      this.loading = false
      if (res.errcode) {
        alert(res.errmsg)
        return
      }
      fileList[fileList.length - 1].url = res.id.toString();
      this.$emit('input', res.id)
    },
    picDel: function(file, fileList) {
      this.$emit('input', null)
    },
  }
}
</script>

<style lang="scss" scoped>
  .upload-demo {
    display: flex;
  }
</style>
