<template>
  <base-model :config="config">
    <div slot="dialog-body">
      <el-form
        ref="certificateForm"
        :model="form"
        label-width="140px"
        size="small"
        :rules="rules"
      >
        <div class="base-dialog-body">
          <el-form-item
            :label="$t('trials:trialDocument:certificate:form:fileType')"
            prop="Type"
          >
            <el-select
              v-model="form.Type"
              placeholder=""
              clearable
              :disabled="config.status === 'edit' && !!this.data.Type"
            >
              <el-option
                v-for="item in $d.CertificateFileType"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            :label="$t('trials:trialDocument:certificate:form:DoctorId')"
            prop="DoctorId"
          >
            <el-select
              v-model="form.DoctorId"
              placeholder=""
              clearable
              :disabled="config.status === 'edit' && !!this.data.DoctorId"
            >
              <el-option
                v-for="item in doctorList"
                :key="item.Id"
                :label="item.FullName"
                :value="item.Id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            :label="$t('trials:trialDocument:certificate:form:pdfFileRecord')"
            prop="Path"
          >
            <el-upload
              class="upload-demo"
              action
              :before-upload="(param) => beforeUpload(param, '.pdf')"
              :http-request="handleUploadFile"
              :on-remove="handleRemoveFile"
              :limit="1"
              accept=".pdf"
              :file-list="PDFFile"
            >
              <el-button size="small" type="primary" :disabled="!!form.Path"
                >{{ $t('common:button:upload') }}
              </el-button>
              <span slot="tip" class="el-upload__tip">
                {{ $t('trials:trialDocument:certificate:rule:mustPDF') }}
              </span>
            </el-upload>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div slot="dialog-footer">
      <el-button size="small" @click="canel">
        {{ $t('trials:trialDocument:certificate:button:canel') }}
      </el-button>
      <el-button size="small" type="primary" :loading="loading" @click="save">
        {{ $t('trials:trialDocument:certificate:button:save') }}
      </el-button>
    </div>
  </base-model>
</template>
    <script>
import baseModel from '@/components/BaseModel'
import { saveTrialAttachments, updateTrialAttachments } from '@/api/dictionary'
export default {
  props: {
    config: {
      required: true,
      default: () => {
        return {}
      },
    },
    data: {
      required: true,
      default: () => {
        return {}
      },
    },
    ArchiveTypeEnum: {
      type: Number,
      default: 0,
    },
    doctorList: {
      type: Array,
      default: () => {
        return []
      },
    },
  },
  components: {
    'base-model': baseModel,
  },
  data() {
    return {
      form: {
        Type: null,
        DoctorId: null,
        FileName: null,
        Path: null,
        FullPath: null,
      },
      rules: {
        Type: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur', 'change'],
          },
        ],
        DoctorId: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur', 'change'],
          },
        ],
        Path: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!this.form.Path) {
                callback(
                  new Error(
                    this.$t('trials:trialDocument:certificate:msg:noFile')
                  )
                )
              } else {
                callback()
              }
            },
            // message: this.$t('common:ruleMessage:specify'),
            trigger: ['blur', 'change'],
          },
        ],
      },
      loading: false,
      PDFFile: [],
    }
  },
  created() {
    if (this.config.status === 'edit') {
      Object.keys(this.form).forEach((key) => {
        this.form[key] = this.data[key]
      })
      if (this.form.Path) {
        this.PDFFile = []
        this.PDFFile.push({
          name: this.form.FileName,
          url: this.form.Path,
        })
      }
    }
  },
  methods: {
    async save() {
      try {
        let validate = await this.$refs.certificateForm.validate()
        if (!validate) return false
        this.loading = true
        this.form.TrialId = this.$route.query.trialId
        let res = null
        if (this.config.status === 'edit') {
          this.form.Id = this.data.Id
          res = await updateTrialAttachments(this.form)
        } else {
          res = await saveTrialAttachments([this.form])
        }
        if (res.IsSuccess) {
          this.$emit('close')
          this.$emit('getList')
        }
      } catch (err) {
        console.log(err)
        this.loading = false
      }
    },
    canel() {
      this.$emit('close')
    },
    handleRemoveFile() {
      this.form.Path = null
      this.form.FileName = null
      this.form.FullPath = null
      this.PDFFile = []
    },
    beforeUpload(param, accept) {
      if (this.PDFFile && this.PDFFile[0]) {
        this.$alert(
          this.$t('trials:trialDocument:certificate:msg:hasFile')
        ).catch()
        return
      }
      let extendName = param.name
        .substring(param.name.lastIndexOf('.'))
        .toLocaleLowerCase()
      if (accept !== extendName) {
        this.$alert(
          this.$t('trials:trialDocument:certificate:msg:typeErr')
        ).catch()
        return
      }
    },
    async handleUploadFile(param) {
      let trialId = this.$route.query.trialId
      let extendName = param.file.name
        .substring(param.file.name.lastIndexOf('.'))
        .toLocaleLowerCase()
      if (!trialId)
        return this.$alert(
          this.$t('trials:trialDocument:certificate:msg:noTrialId')
        ).catch()
      this.loading = true
      var file = await this.fileToBlob(param.file)
      let typeArr = ['', 'Report', 'Doc', 'Record', 'Reviewer', 'Template']
      let types = typeArr[this.ArchiveTypeEnum]
      // let fileNameNoType = param.file.name
      //   .substring(0, param.file.name.lastIndexOf('.'))
      //   .toLocaleLowerCase()
      const res = await this.OSSclient.put(
        `/${trialId}/Document/${types}/${this.$guid()}${extendName}`,
        file
      )
      this.form.Path = this.$getObjectName(res.url)
      this.form.FullPath = this.$getObjectName(res.url)
      this.form.FileName = param.file.name
      this.loading = false
    },
  },
}
</script>