<template>
  <div>
    <el-upload
      ref="upload"
      :action="fileAction"
      :file-list="fileList"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :on-error="handleError"
      name="file">
      <el-button slot="trigger" size="mini" type="primary">选取文件</el-button>
    </el-upload>
  </div>

</template>

<script>
import {uploadFileUrl, deleteFile} from "@/api/file/file";

export default {
  name: "index",
  props: {
    files: {
      type: Array,
      default: () => []
    }
  },
  watch: {
    files: {
      handler(newVal, oldVal) {
        this.fileList = newVal.map(item => {
          item['name'] = item.fileName.replace('<br/>', '')
          return item;
        })
      },
      deep: true,
      immediate: true
    }
  },
  data() {
    return {
      fileAction: '',
      fileList: []
    }
  },
  created() {
    this.fileAction = uploadFileUrl()
  },
  methods: {
    handleRemove(file, fileList) {
      let url = file.response.data.url;
      deleteFile(url).then(res => {
        this.fileList = this.fileList.filter(item => item != url);
        this.$message({
          message: '操作成功!',
          type: 'success'
        });
      });
      this.$emit('removeFile', url)
    },
    handleSuccess(response, file, fileList) {
      let fileUrl = response.data.url
      this.fileList.push(fileUrl)
      this.$emit('getFileUrl', fileUrl)
    },
    handleError() {
      this.$message({
        message: '上传失败，请稍候再试!',
        type: 'warning'
      });
    },
  }
}
</script>

<style scoped>

</style>
