<template>
  <!-- 上传非医生个人相关附件 -->
  <div class="upload-container">
    <el-upload
      class="upload-demo"
      action
      :accept="accept"
      :before-upload="beforeUpload"
      :http-request="handleUploadFile"
      :on-preview="handlePreview"
      :on-remove="handleRemoveFile"
      :show-file-list="true"
      :file-list="fileList"
      :limit="1"
      :on-exceed="handleExceed"
    >
      <el-button size="small" type="primary" :loading="btnDisabled">Upload</el-button>
      <span slot="tip" style="margin-left:10px;" class="el-upload__tip">(must be in pdf format)</span>
    </el-upload>
  </div>
</template>
<script>
import { uploadNonDoctorFile } from '@/api/attachment'
export default {
  name: 'Upload',
  props: {
    type: {
      type: String,
      required: true
    },
    accept: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      fileList: [],
      btnDisabled: false
    }
  },
  methods: {
    initFileList(fileList) {
      this.fileList = fileList
    },
    beforeUpload(file) {
      // 检测文件类型是否符合要求
      if (this.checkFileSuffix(file.name)) {
        this.fileList = []
        return true
      } else {
        this.$alert(`Must be in ${this.accept} format`)
        return false
      }
    },
    handleUploadFile(param) {
      this.btnDisabled = true
      uploadNonDoctorFile(param.file, this.type).then(res => {
        this.btnDisabled = false
        if (res.IsSuccess) {
          this.fileList.push({ name: param.file.name, path: res.Result.FilePath, fullPath: res.Result.FullFilePath, type: this.type })
          this.$emit('getFileList', this.fileList)
        }
      }).catch(() => {
        this.btnDisabled = false
      })
    },
    handleRemoveFile() {
      this.fileList = []
      this.$emit('getFileList', this.fileList)
    },
    handlePreview(file) {
      if (file.fullPath) {
        window.open(file.fullPath, '_blank')
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(`Upload is currently limited to 1 file`)
    },
    checkFileSuffix(fileName) {
      var index = fileName.lastIndexOf('.')
      var suffix = fileName.substring(index + 1, fileName.length)
      if (this.accept.toLocaleLowerCase().search(suffix.toLocaleLowerCase()) === -1) {
        return false
      } else {
        return true
      }
    }
  }
}
</script>
<style>
.upload-container .el-upload--text {
  border: none;
  width: 80px;
  height: 40px;
}
.upload-container .el-input--small {
  margin-bottom: 5px;
}
.upload-container .el-icon-circle-check {
  color: #428bca;
  font-size: 13px;
}
</style>
