<template>
  <div class="gcp-container">
    <el-radio-group v-model="GCP" style="margin-bottom:20px">
      <el-radio :label="1">{{ $t('system:GcpCertificate:radio:Yes') }}</el-radio>
      <el-radio :label="0">{{ $t('system:GcpCertificate:radio:No') }}</el-radio>
    </el-radio-group>
    <div v-if="GCP" class="upload-container">
<!--      <upload-file :doctor-id="doctorId" type="GCP" />-->
      <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">{{ $t('system:GcpCertificate:upload:Upload') }}</el-button>
        <span slot="tip" style="margin-left:10px;" class="el-upload__tip">{{ $t('system:GcpCertificate:tap:must') }}</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">
        {{ $t('common:button:save') }}
      </el-button>
    </div>
  </div>
</template>
<script>
import UploadFile from '@/components/UploadFile'
import { uploadFile, deleteAttachment, getAttachmentByType, saveAttachments } from '@/api/attachment'
import { updateGcpExperience } from '@/api/reviewers'
export default {
  name: 'GcpCertificate',
  components: {
    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.GCP ? 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() {
      if(!this.doctorId) return
      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
    },
    async uploadFile(param) {
      var fileName = param.file.name
      this.btnDisabled = true
      const file = await this.fileToBlob(param.file)
      const res = await this.OSSclient.put(`/SystemData/reviewer/GCP/${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: 'GCP' })
      this.saveFile()
    },
    // 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.$alert('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: this.$t('common:message:deletedSuccessfully'),
                type: 'success'
              })
            }
          })
        } else {
          this.fileList = []
           this.GCPID = ''
        }
      }
    },
    handlePreview(file) {
      if (file.fullPath) {
        window.open(this.OSSclientConfig.basePath + 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>
