<template>
  <div class="gcp-container">
    <el-radio-group v-model="GCP" style="margin-bottom:20px">
      <el-radio :label="1">Yes</el-radio>
      <el-radio :label="0">No</el-radio>
    </el-radio-group>
    <div v-if="GCP" 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" :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>
    <div>
      <el-button :loading="saveBtnLoading" :disabled="(fileList.length === 0 && GCP === 1)" type="primary" size="small" style="margin-top:20px" @click="handleSaveGCP">
        Save
      </el-button>
    </div>
  </div>
</template>
<script>
import { uploadFile, deleteAttachment, getAttachmentByType, saveAttachments } from '@/api/attachment'
import { updateGcpExperience } from '@/api/reviewers'
export default {
  name: 'UploadFile',
  props: {
    doctorId: {
      type: String,
      required: true
    },
    gcp: {
      type: Number,
      default: 0
    },
    gcpId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      fileList: [],
      btnDisabled: false,
      saveBtnLoading: false,
      GCP: 0,
      GCPID: ''
    }
  },
  watch: {
    gcp(val) {
      this.GCP = val
    },
    gcpId(val) {
      this.GCPID = val
    }
  },
  mounted() {
    this.initFileList()
  },
  methods: {
    handleSaveGCP() {
      if (this.GCP && this.GCPID === '') {
        this.$message.info('Please upload the GCP certificate')
        return
      }
      const param = {
        Id: this.doctorId,
        GCP: this.GCP,
        GCPId: this.GCPID
      }
      this.saveBtnLoading = true
      updateGcpExperience(param).then(res => {
        if (this.GCP === 0) {
          this.fileList = []
        }
        this.saveBtnLoading = false
        this.$message.success('Saved successfully')
      }).catch(() => {
        this.saveBtnLoading = false
      })
    },
    initFileList() {
      getAttachmentByType(this.doctorId, 'GCP')
        .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) {
      var fileName = param.file.name
      this.btnDisabled = true
      uploadFile(param.file, 'GCP', this.doctorId)
        .then(res => {
          if (res.IsSuccess) {
            this.fileList.push({ name: fileName, path: res.Result.FilePath, fullPath: res.Result.FullFilePath, type: 'GCP' })
            this.saveFile()
          }
        })
        .catch(() => {
          this.btnDisabled = 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.GCPID = res.Result[0].Id
          this.$message.success('Uploaded successfully')
        }
      })
        .catch(() => {
          this.btnDisabled = false
        })
    },
    beforeUpload(file, fileList) {
      const isValidFile = this.fileValid(file.name, ['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.GCPID = ''
              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 lang="scss">
.gcp-container{
  .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>
