<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>
    <el-form
      ref="certificateFrom"
      v-loading="saveBtnLoading"
      :model="certificateForm"
      :rules="certificateRules"
      label-width="80px"
      size="small"
    >
      <el-form-item
        :label="$t('curriculumVitae:clinicalTrials:form:CertificateTime')"
        prop="GCPTime"
        v-if="GCP"
      >
        <el-date-picker
          v-model="certificateForm.GCPTime"
          type="date"
          placeholder=""
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item
        :label="$t('curriculumVitae:clinicalTrials:form:certificateHospital')"
        prop="GCPAgencies"
        v-if="GCP"
      >
        <el-input
          v-model="certificateForm.GCPAgencies"
          clearable
          :maxlength="400"
        ></el-input>
      </el-form-item>
    </el-form>
    <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:tip:file:pdf')
        }}</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'
const defaultCertificateForm = () => {
  return {
    GCPTime: '',
    GCPAgencies: '',
  }
}
export default {
  name: 'GcpCertificate',
  components: {
    UploadFile,
  },
  props: {
    doctorId: {
      type: String,
      required: true,
    },
    gcp: {
      type: Number,
      default: 0,
    },
    gcpId: {
      type: String,
      default: '',
    },
    DATA: {
      type: Object,
      default: () => {
        return {}
      },
    },
  },
  data() {
    return {
      fileList: [],
      btnDisabled: false,
      saveBtnLoading: false,
      GCP: 0,
      GCPID: '',
      certificateForm: defaultCertificateForm(),
      certificateRules: {
        GCPAgencies: [
          {
            max: 400,
            message: this.$t('form:rules:maxLength:400'),
            trigger: 'blur',
          },
        ],
      },
    }
  },
  watch: {
    gcp(val) {
      this.GCP = val
    },
    gcpId(val) {
      this.GCPID = val
    },
    DATA: {
      handler() {
        Object.keys(this.certificateForm).forEach((key) => {
          this.certificateForm[key] = this.DATA[key]
        })
      },
      immediate: true,
      deep: true,
    },
  },
  mounted() {
    this.initFileList()
  },
  methods: {
    handleSaveGCP() {
      if (this.GCP && this.GCPID === '') {
        this.$message.info(
          this.$t('reviewers:GCPCertificate:message:uploadValid')
        )
        return
      }

      const param = {
        Id: this.doctorId,
        GCP: this.GCP,
        GCPId: this.GCP ? this.GCPID : '',
        GCPTime: this.GCP ? this.certificateForm.GCPTime : '',
        GCPAgencies: this.GCP ? this.certificateForm.GCPAgencies : '',
      }
      this.saveBtnLoading = true
      updateGcpExperience(param)
        .then((res) => {
          if (this.GCP === 0) {
            this.fileList = []
          }
          this.saveBtnLoading = false
          this.$message.success(this.$t('common:message:savedSuccessfully'))
        })
        .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(this.$t('common:message:savedSuccessfully'))
          }
        })
        .catch(() => {
          this.btnDisabled = false
        })
    },
    beforeUpload(file, fileList) {
      const isValidFile = this.fileValid(file.name, ['pdf'])
      if (isValidFile) {
        this.fileList = []
      } else {
        this.$alert(this.$t('trials:attachment:message:pdf'))
        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>
