<template>
  <!-- 上传发票excel -->
  <div class="upload-container">
    <el-upload
      class="upload-demo mr10 mb15"
      :class="[fileInfo.name ? 'upload-wrap' : '']"
      action
      :http-request="handleUploadForm"
      :headers="myHeaders"
      :show-file-list="true"
      multiple
      :on-remove="clear"
    >
      <div v-if="!fileInfo.name" class="upload-icon">
        <i class="el-icon-plus upload-plus"></i>
      </div>
    </el-upload>
  </div>
</template>
<script>
import { importInvoiceApi } from '@/api/finance';
import { getToken } from '@/utils/auth';
export default {
  name: 'UploadFile',
  data() {
    return {
      myHeaders: { 'X-Token': getToken() },
      url: '',
      fileType: '',
      fileInfo: {},
    };
  },
  beforeMount() {
    if (this.value) {
      this.url = this.value;
      this.getFileType(this.value);
    }
  },
  methods: {
    // 上传
    handleUploadForm(param) {
      const formData = new FormData();
      const loading = this.$loading({
        lock: true,
        text: '上传中，请稍候...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      this.fileInfo = param.file;
      formData.append('file', param.file);
      importInvoiceApi(formData)
        .then((res) => {
          this.$emit('onSuccess', res);
          loading.close();
          this.url = res.url;
          this.getFileType(res.url);
          this.$message.success('上传成功');
        })
        .catch((res) => {
          loading.close();
        });
    },
    getFileType(file) {
      var first = file.lastIndexOf('.'); //取到文件名开始到最后一个点的长度
      var namelength = file.length; //取到文件名长度
      var filesuffix = file.substring(first + 1, namelength); //截取获得后缀名
      this.fileType = filesuffix.toUpperCase();
    },
    clear() {
      this.fileInfo = {};
    },
  },
};
</script>

<style scoped lang="scss">
.flex-column {
  display: flex;
  flex-direction: column;
}
.column {
  display: flex;
  flex-direction: column;
  line-height: 16px;
}
.file-type {
  font-size: 12px;
  padding-top: 2px;
}
.upload-icon {
  width: 45px;
  height: 45px;
  border: 1px dashed #c8c8c8;
  border-radius: 5px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}
.upload-plus {
  color: #b6b6b6;
  font-size: 18px;
}
.upload-wrap {
  margin-top: -37px;
}
::v-deep .el-upload-list__item-name {
  color: #1890ff;
}
</style>
