<template>
  <base-model :config="config">
    <div slot="dialog-body">
      <el-form ref="reportDocForm" :model="form" label-width="140px" size="small" :rules="rules">
        <div class="base-dialog-body">
          <el-form-item v-if="!config.upload" :label="$t('trials:trialDocument:reportDoc:form:name')" prop="Name">
            <el-input v-model="form.Name" />
          </el-form-item>
          <el-form-item v-if="!config.upload" :label="$t('trials:trialDocument:reportDoc:form:version')" prop="Version">
            <el-input v-model="form.Version" />
          </el-form-item>
          <el-form-item v-if="!config.upload" :label="$t('trials:trialDocument:reportDoc:form:isAuthorizedView')"
            prop="IsAuthorizedView">
            <el-switch v-model="form.IsAuthorizedView" :active-value="true" :inactive-value="false"
              :active-text="$fd('YesOrNo', true)" :inactive-text="$fd('YesOrNo', false)">
            </el-switch>
          </el-form-item>
          <el-form-item v-if="!config.upload || config.upload === 'PDF'"
            :label="$t('trials:trialDocument:reportDoc:form:pdfFileRecord')" prop="PDFFileRecord">
            <el-upload class="upload-demo" action :before-upload="(param) => beforeUpload(param, 'PDF', '.pdf')"
              :http-request="(param) => handleUploadFile(param, 'PDF')" :on-remove="() => handleRemoveFile('PDF')"
              :limit="1" accept=".pdf" :file-list="PDFFile">
              <el-button size="small" type="primary" :disabled="!!form.PDFFileRecord && !!form.PDFFileRecord.FilePath
                ">{{ $t('common:button:upload') }}
              </el-button>
              <span slot="tip" class="el-upload__tip">
                {{ $t('trials:trialDocument:reportDoc:rule:mustPDF') }}
              </span>
            </el-upload>
          </el-form-item>
          <el-form-item v-if="!config.upload || config.upload === 'Word'"
            :label="$t('trials:trialDocument:reportDoc:form:wordFileRecord')">
            <el-upload class="upload-demo" action :before-upload="(param) => beforeUpload(param, 'Word', '.docx')"
              :http-request="(param) => handleUploadFile(param, 'Word')" :on-remove="() => handleRemoveFile('Word')"
              :limit="1" accept=".docx" :file-list="WordFile">
              <el-button size="small" type="primary" :disabled="!!form.WordFileRecord && !!form.WordFileRecord.FilePath
                ">{{ $t('common:button:upload') }}
              </el-button>
              <span slot="tip" class="el-upload__tip">
                {{ $t('trials:trialDocument:reportDoc:rule:mustDOCX') }}
              </span>
            </el-upload>
          </el-form-item>
          <el-form-item v-if="!config.upload || config.upload === 'Sign'"
            :label="$t('trials:trialDocument:reportDoc:form:signFileRecord')" :prop="rowData.IsConfirmRecord &&
                (!config.upload || config.upload === 'Sign')
                ? 'SignFileRecord'
                : ''
              ">
            <el-upload class="upload-demo" action :before-upload="(param) => beforeUpload(param, 'Sign', '.pdf')"
              :http-request="(param) => handleUploadFile(param, 'Sign')" :on-remove="() => handleRemoveFile('Sign')"
              :limit="1" accept=".pdf" :file-list="SignFile">
              <el-button size="small" type="primary" :disabled="!!form.SignFileRecord && !!form.SignFileRecord.FilePath
                ">{{ $t('common:button:upload') }}
              </el-button>
              <span slot="tip" class="el-upload__tip">
                {{ $t('trials:trialDocument:reportDoc:rule:mustPDF') }}
              </span>
            </el-upload>
          </el-form-item>
          <!-- <el-form-item
            v-if="!config.upload || config.upload === 'History'"
            :label="$t('trials:trialDocument:reportDoc:form:historyFileRecord')"
          >
            <el-upload
              class="upload-demo"
              action
              :before-upload="(param) => beforeUpload(param, 'History', '.zip')"
              :http-request="(param) => handleUploadFile(param, 'History')"
              :on-remove="() => handleRemoveFile('History')"
              :limit="1"
              accept=".zip"
              :file-list="HistoryFile"
            >
              <el-button
                size="small"
                type="primary"
                :disabled="
                  !!form.HistoryFileRecord && !!form.HistoryFileRecord.FilePath
                "
                >{{ $t('common:button:upload') }}
              </el-button>
              <span slot="tip" class="el-upload__tip">
                {{ $t('trials:trialDocument:reportDoc:rule:mustZIP') }}
              </span>
            </el-upload>
          </el-form-item> -->
        </div>
      </el-form>
    </div>
    <div slot="dialog-footer">
      <el-button size="small" @click="canel">
        {{ $t('trials:trialDocument:reportDoc:button:canel') }}
      </el-button>
      <el-button size="small" type="primary" :loading="loading" @click="save">
        {{ $t('trials:trialDocument:reportDoc:button:save') }}
      </el-button>
    </div>
  </base-model>
</template>
<script>
import baseModel from '@/components/BaseModel'
import { addOrUpdateTrialFinalRecord } from '@/api/dictionary'
export default {
  props: {
    config: {
      required: true,
      default: () => {
        return {}
      },
    },
    data: {
      required: true,
      default: () => {
        return {}
      },
    },
    ArchiveTypeEnum: {
      type: Number,
      default: 0,
    },
    rowData: {
      type: Object,
      default: () => {
        return {}
      },
    },
  },
  components: {
    'base-model': baseModel,
  },
  data() {
    return {
      form: {
        Version: null,
        Name: null,
        IsAuthorizedView: true,
        PDFFileRecord: null,
        WordFileRecord: null,
        SignFileRecord: null,
        HistoryFileRecord: null,
      },
      rules: {
        Name: [
          {
            required: true,
            message: this.$t('common:ruleMessage:specify'),
            trigger: ['blur', 'change'],
          },
        ],
        Version: [
          {
            required: true,
            message: this.$t('common:ruleMessage:specify'),
            trigger: ['blur', 'change'],
          },
        ],
        IsAuthorizedView: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur', 'change'],
          },
        ],
        PDFFileRecord: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (
                !this.form.PDFFileRecord ||
                !this.form.PDFFileRecord.FilePath
              ) {
                callback(
                  new Error(
                    this.$t(
                      'trials:trialDocument:reportDoc:msg:noPdfFileRecord'
                    )
                  )
                )
              } else {
                callback()
              }
            },
            // message: this.$t('common:ruleMessage:specify'),
            trigger: ['blur', 'change'],
          },
        ],
        SignFileRecord: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (
                !this.form.SignFileRecord ||
                !this.form.SignFileRecord.FilePath
              ) {
                callback(
                  new Error(
                    this.$t(
                      'trials:trialDocument:reportDoc:msg:noSignFileRecord'
                    )
                  )
                )
              } else {
                callback()
              }
            },
            // message: this.$t('common:ruleMessage:specify'),
            trigger: ['blur', 'change'],
          },
        ],
      },
      loading: false,
      PDFFile: [],
      WordFile: [],
      SignFile: [],
      HistoryFile: [],
    }
  },
  created() {
    if (this.config.status === 'edit') {
      Object.keys(this.form).forEach((key) => {
        this.form[key] = this.data[key]
      })
      let arr = ['PDF', 'Word', 'Sign', 'History']

      arr.forEach((key) => {
        if (
          this.form[`${key}FileRecord`] &&
          this.form[`${key}FileRecord`].FilePath
        ) {
          this[`${key}File`] = []
          this[`${key}File`].push({
            name: this.form[`${key}FileRecord`].FileName,
            url: this.form[`${key}FileRecord`].FilePath,
          })
        }
      })
    }
  },
  methods: {
    async save() {
      try {
        let validate = await this.$refs.reportDocForm.validate()
        if (!validate) return false
        this.loading = true
        this.form.TrialFileTypeId = this.rowData.Id
        if (this.config.status === 'edit') {
          this.form.Id = this.data.Id
        }
        let res = await addOrUpdateTrialFinalRecord(this.form)
        if (res.IsSuccess) {
          this.$emit('close')
          this.$emit('getList')
        }
      } catch (err) {
        console.log(err)
        this.loading = false
      }
    },
    canel() {
      this.$emit('close')
    },
    handleRemoveFile(key) {
      this.form[`${key}FileRecord`] = null
      this[`${key}File`] = []
    },
    beforeUpload(param, key, accept) {
      if (this[`${key}File`] && this[`${key}File`][0]) {
        this.$alert(
          this.$t('trials:trialDocument:reportDoc:msg:hasFile')
        ).catch()
        return
      }
      let extendName = param.name
        .substring(param.name.lastIndexOf('.'))
        .toLocaleLowerCase()
      if (accept !== extendName) {
        this.$alert(
          this.$t('trials:trialDocument:reportDoc:msg:typeErr')
        ).catch()
        return
      }
    },
    async handleUploadFile(param, key) {
      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:reportDoc: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[`${key}FileRecord`] = {
        FileName: param.file.name,
        FilePath: this.$getObjectName(res.url),
        FileSize: param.file.size,
        FileFormat: extendName,
      }
      this.loading = false
    },
  },
}
</script>