<template>
  <div class="upload-layout">
    <div v-if="file.downloadUrl" class="file-box">
      <div>
        <a-icon type="file" style="margin-right: 8px" />
        <span class="hover-pointer" @click="downloadfile">{{file.fileName}}</span>
      </div>
      <a-icon type="delete" class="hover-pointer" @click="deletefile" style="margin-left: 8px" />
    </div>
    <div v-else>
      <input type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" ref="fileElem" class="visually-hidden" @change="handleFiles">
      <a-button @click="fileSelect">
        <a-icon type="upload" />选择文件
      </a-button>
    </div>
  </div>
</template>
<script>
const File = { fileName: null, downloadUrl: null, fileExplain: null, downloadId: null }
export default {
  name: "FileUpload",
  data () {
    return {
      file: { ...File },
    };
  },
  props: {
    value: {
      type: String,
      default () {
        return null
      }
    }
  },
  created () {
    this.fileLoad(this.value)
  },
  methods: {
    fileLoad (value) {
    },
    fileSelect () {
      let fileElem = this.$refs['fileElem']
      if (fileElem) {
        fileElem.click()
      }
    },
    handleFiles () {
      let fileElem = this.$refs['fileElem']
      let files = fileElem.files
      if (files.length <= 0) {
        this.$message.error('未选中文件，请尝试重新选择')
        return
      }
      this.file.fileName = files[0].name
      this.file.downloadUrl = '/' + files[0].name
      this.$emit("beforeUpload", files[0]);
    },
    downloadfile () {

    },
    deletefile () {
      this.file = { ...File }
      this.$emit("cancel");
    },
    uploadHandle (file, fileName) {
      let formData = new FormData()
      formData.append('file', file)
      formData.append('fileName', fileName)
      return formData
    },
  },
  watch: {
    value: {
      handler (value) {
        this.selected = value
      },
    }
  }
};
</script>
<style scoped lang="less">
.upload-layout {
  display: inline-block;
  margin: 0 10px;
  height: 30px;
  line-height: 30px;

  .file-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 0 8px;

    > div:nth-child(1) {
      max-width: 90%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
  .visually-hidden {
    display: none !important;
  }
}
</style>

