<template>
  <base-model :config="config">
    <div slot="dialog-body">
      <el-form ref="trainRecordForm" :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:trainRecord:form:TrianingDate')"
            prop="TrianingDate">
            <el-date-picker v-model="form.TrianingDate" type="date" placeholder="" format="yyyy-MM-dd"
              value-format="yyyy-MM-dd" style="width: 100%">
            </el-date-picker>
          </el-form-item>
          <el-form-item v-if="!config.upload" :label="$t('trials:trialDocument:trainRecord:form:TrianingCount')"
            prop="TrianingCount">
            <el-input v-model.number="form.TrianingCount" type="number" />
          </el-form-item>
          <el-form-item v-if="!config.upload" :label="$t('trials:trialDocument:trainRecord:form:TrianingState')"
            prop="TrianingState">
            <el-input v-model="form.TrianingState" />
          </el-form-item>
          <el-form-item v-if="!config.upload" :label="$t('trials:trialDocument:trainRecord:form:Note')" prop="Note">
            <el-input v-model="form.Note" />
          </el-form-item>
          <el-form-item v-if="!config.upload || config.upload === 'Trial'"
            :label="$t('trials:trialDocument:trainRecord:form:TrialFileRecord')" prop="TrialFileRecord">
            <el-upload class="upload-demo" action :before-upload="(param) => beforeUpload(param, 'Trial', '.pdf')"
              :http-request="(param) => handleUploadFile(param, 'Trial')" :on-remove="() => handleRemoveFile('Trial')"
              :limit="1" accept=".pdf" :file-list="TrialFile">
              <el-button size="small" type="primary" :disabled="!!form.TrialFileRecord && !!form.TrialFileRecord.FilePath
                ">{{ $t('common:button:upload') }}
              </el-button>
              <span slot="tip" class="el-upload__tip">
                {{ $t('trials:trialDocument:trainRecord:rule:mustPDF') }}
              </span>
            </el-upload>
          </el-form-item>
          <!-- <el-form-item v-if="!config.upload || config.upload === 'History'" :label="$t('trials:trialDocument:trainRecord: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:trainRecord: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:trainRecord:button:canel') }}
      </el-button>
      <el-button size="small" type="primary" :loading="loading" @click="save">
        {{ $t('trials:trialDocument:trainRecord:button:save') }}
      </el-button>
    </div>
  </base-model>
</template>
<script>
import baseModel from '@/components/BaseModel'
import { addOrUpdateTrialTrianingRecord } 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: {
        Note: null,
        TrianingCount: null,
        TrianingDate: null,
        TrianingState: null,
        IsAuthorizedView: true,
        TrialFileRecord: null,
        HistoryFileRecord: null,
      },
      rules: {
        TrianingDate: [
          {
            required: true,
            message: this.$t('common:ruleMessage:specify'),
            trigger: ['blur', 'change'],
          },
        ],
        TrianingCount: [
          {
            type: 'number',
            min: 0,
            message: this.$t(
              'trials:trialDocument:trainRecord:ruleMessage:TrianingCountPattern'
            ),
            trigger: 'blur',
          },
          {
            validator: (rule, value, callback) => {
              if (
                value &&
                (String(value).includes('.') ||
                  new RegExp(/\D/g).test(String(value)))
              ) {
                callback(
                  new Error(
                    this.$t(
                      'trials:trialDocument:trainRecord:ruleMessage:TrianingCountPattern'
                    )
                  )
                )
              } else {
                callback()
              }
            },
            trigger: 'blur',
          },
        ]
      },
      loading: false,
      TrialFile: [],
      HistoryFile: [],
    }
  },
  created() {
    if (this.config.status === 'edit') {
      Object.keys(this.form).forEach((key) => {
        this.form[key] = this.data[key]
      })
      let arr = ['Trial', '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.trainRecordForm.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 addOrUpdateTrialTrianingRecord(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:trainRecord:msg:hasFile')
        ).catch()
        return
      }
      let extendName = param.name
        .substring(param.name.lastIndexOf('.'))
        .toLocaleLowerCase()
      if (accept !== extendName) {
        this.$alert(
          this.$t('trials:trialDocument:trainRecord: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:trainRecord: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>