<template>
  <!-- 上传医生附件(PDF) -->
  <div class="upload-container">
    <el-upload
      class="upload-demo"
      action
      :http-request="uploadFile"
      :before-upload="beforeUpload"
      :file-list="fileList"
      :before-remove="beforeRemove"
      :on-remove="handleRemoveFile"
      :on-preview="handlePreview"
      :limit="1"
      :on-exceed="handleExceed"
      accept=".pdf"
    >
      <el-button size="small" type="primary" :disabled="btnDisabled || $route.query.ReviewStatus === '1'" >Upload</el-button>
      <span slot="tip" class="el-upload__tip">(must be in pdf format)</span>
    </el-upload>
  </div>
</template>
<script>
import { uploadFile, deleteAttachment, getAttachmentByType, saveAttachments } from '@/api/attachment'

export default {
  name: 'UploadFile',
  props: {
    type: {
      type: String,
      required: true
    },
    doctorId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      fileList: [],
      btnDisabled: false
    }
  },
  mounted() {
    this.initFileList()
  },
  methods: {
    initFileList() {
      getAttachmentByType(this.doctorId, this.type)
        .then(res => {
          if (res.IsSuccess) {
            if (res.Result.length > 0) {
              this.fileList = this.formatterFileList(res.Result)
            } else {
              this.fileList = []
            }
          }
        })
    },
    formatterFileList(list) {
      var arr = []
      list.forEach(item => {
        var data = {
          name: item.FileName,
          path: item.Path,
          fullPath: item.FullPath,
          id: item.Id,
          type: item.Type
        }
        arr.push(data)
      })
      return arr
    },
    uploadFile(param) {
      this.$emit('handleUpload', true)
      var fileName = param.file.name
      this.btnDisabled = true
      uploadFile(param.file, this.type, this.doctorId)
        .then(res => {
          if (res.IsSuccess) {
            this.fileList.push({ name: fileName, path: res.Result.FilePath, fullPath: res.Result.FullFilePath, type: this.type })
            this.saveFile()
          }
        })
        .catch(() => {
          this.btnDisabled = false
          this.$emit('handleUpload', false)
        })
    },
    saveFile() {
      const { name, path, fullPath, type } = this.fileList[0]
      const param = [{ DoctorId: this.doctorId, Type: type, Path: path, FullPath: fullPath, FileName: name }]
      saveAttachments(param).then(res => {
        this.btnDisabled = false
        if (res.IsSuccess) {
          this.fileList[0].id = res.Result[0].Id
          this.$message.success('Uploaded successfully')
          this.$emit('getFileList', res.Result[0].Id, res.Result[0].Path)
        }
      })
        .catch(() => {
          this.btnDisabled = false
          this.$emit('handleUpload', false)
        })
    },
    beforeUpload(file, fileList) {
      const isValidFile = this.fileValid(file.name, ['pdf', 'PDF'])
      if (isValidFile) {
        this.fileList = []
      } else {
        this.$message.error('must be in pdf format')
        return false
      }
    },
    beforeRemove(file, fileList) {
      if (file && file.status === 'success') {
        return this.$confirm(`Sure to remove ${file.name}?`)
      }
    },
    handleRemoveFile(file, fileList) {
      if (file && file.status === 'success') {
        if (file.id) {
          deleteAttachment(file.id, file.path).then(res => {
            if (res.IsSuccess) {
              this.fileList = []
              this.$emit('getFileList', '', '')
              this.$message({
                message: 'Deleted successfully!',
                type: 'success'
              })
            }
          })
        } else {
          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`)
    },
    fileValid(fileName, typeArr) {
      var extendName = fileName.substring(fileName.lastIndexOf('.') + 1).toLocaleLowerCase()
      if (typeArr.indexOf(extendName) > -1) {
        return true
      } else {
        return false
      }
    }
  }
}
</script>
<style>
.upload-container .el-upload--text {
  border: none;
  width: 80px;
  height: 30px;
}
.upload-container .el-form-item__label {
  font-size: 12px;
}
.upload-container .el-upload-list__item {
  font-size: 12px;
}
</style>
