<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'" >{{ $t('system:GcpCertificate:upload:Upload') }}</el-button>
      <span slot="tip" class="el-upload__tip">{{$t('system:tip:file:pdf') }}</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() {
      if(!this.doctorId) return
      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,
          url: item.FullPath
        }
        arr.push(data)
      })
      return arr
    },
    async uploadFile(param) {
      this.$emit('handleUpload', true)
      var fileName = param.file.name
      this.btnDisabled = true
      const file = await this.fileToBlob(param.file)
      const res = await this.OSSclient.put(`/SystemData/reviewer/${this.type}/${this.doctorId}/${fileName}`, file)
      this.fileList.push({ name: fileName, path: this.$getObjectName(res.url), fullPath: this.$getObjectName(res.url),url: this.$getObjectName(res.url), type: this.type })
      this.saveFile()
      // 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(this.$t('trials:uploadDicomList:table:Uploaded'))
          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.$alert(this.$t('upload:rule:MUSTPDF'))
        return false
      }
    },
    beforeRemove(file, fileList) {
      if (file && file.status === 'success') {
        return this.$confirm(this.$t('system:reviewer:confirm:delete'))
      }
    },
    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: this.$t('common:message:deletedSuccessfully'),
                type: 'success'
              })
            }
          })
        } else {
          this.fileList = []
        }
      }
    },
    handlePreview(file) {
      if (file.fullPath) {
        window.open(this.OSSclientConfig.basePath + file.fullPath, '_blank')
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(this.$t('upload:rule:maxFile1'))
    },
    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>
