<template>
  <el-form
    ref="clinicalDataForm"
    v-loading="loading"
    :model="form"
    size="small"
    :rules="rules"
    label-width="110px"
    :inline="true"
  >
    <div class="base-dialog-body">
      <!-- 临床数据名称 -->
      <el-form-item
        :label="$t('trials:readingPeriod:cd:table:clinicalDataName')"
        prop="ClinicalDataTrialSetId"
      >
        <el-col :span="20">
          <el-select
            v-model="form.ClinicalDataTrialSetId"
            @change="handleClinicalDataSetChange"
          >
            <el-option
              v-for="item of clinicalDatas"
              :key="item.Id"
              :label="item.ClinicalDataSetName"
              :value="item.Id"
            />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button
            v-if="currentTpl.isExist"
            type="text"
            @click="handleDownloadTpl"
          >
            {{ $t('trials:readingPeriod:cd:title:downloadTpl') }}
          </el-button>
        </el-col>
      </el-form-item>
      <!-- 数据内容 -->
      <el-form-item :label="$t('trials:readingPeriod:cd:form:data')">
        <!-- 多文件上传 -->
        <form id="inputForm" ref="uploadForm">
          <div class="form-group">
            <div
              id="directoryInputWrapper"
              class="btn btn-link"
              style="position: relative;overflow: hidden;display: inline-block;"
            >
              <el-button
                type="primary"
                style="width: 56px;"
                size="small"
              >
                {{ $t('trials:uploadClinicalData:button:selectFile') }}
              </el-button>
              <input
                type="file"
                name="file"
                multiple
                style="position: absolute;top: 0;left: 0;width: 56px;height: 100%;opacity: 0;cursor: pointer;"
                :accept="faccept.join(',')"
                @change="beginScanFiles($event)"
              >
              <span>{{ ($t('trials:attachment:message:pdf')) }}</span>
            </div>

          </div>
        </form>
        <!-- 文件列表 -->
        <el-table
          ref="filesTable"
          :data="fileList"
          class="dicomFiles-table"
          height="300"
          style="width:100%"
          border
        >
          <el-table-column type="index" width="40" />
          <el-table-column
            prop="FileName"
            :label="$t('trials:uploadClinicalData:table:fileName')"
            width="190"
            show-overflow-tooltip
          />
          <el-table-column
            :label="$t('common:action:action')"
            width="100"
          >
            <template slot-scope="scope">
              <!-- 删除 -->
              <el-button
                circle
                :title="$t('trials:readingPeriod:cd:action:deleteFile')"
                icon="el-icon-delete"
                @click="handleDeleteFile(scope.$index,scope.row)"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

    </div>
    <div
      class="base-dialog-footer"
      style="text-align:right;margin-top:10px;"
    >
      <el-form-item>
        <!-- 取消 -->
        <el-button
          :disabled="btnLoading"
          size="small"
          type="primary"
          @click="close"
        >
          {{ $t('common:button:cancel') }}
        </el-button>
        <!-- 保存 -->
        <el-button
          size="small"
          type="primary"
          :loading="btnLoading"
          @click="save"
        >
          {{ $t('common:button:save') }}
        </el-button>
      </el-form-item>
    </div>
  </el-form>
</template>
<script>
import { getTrialClinicalDataSelect,
  addOrUpdateReadingClinicalData, uploadClinicalData, DownloadTrialClinicalFile } from '@/api/trials'
export default {
  name: 'AddOrUpdateClinicalData',
  props: {
    trialReadingCriterionId: {
      type: String,
      default: ''
    },
    data: {
      type: Object,
      default() { return {} }
    }
  },

  data() {
    return {
      fileList: [],
      faccept: ['.pdf'],
      form: {
        Id: '',
        TrialId: '',
        SubjectId: '',
        ReadingId: '',
        ClinicalDataTrialSetId: '',
        IsVisist: true,
        AddFileList: [],
        DeleteFileIds: [],
        FileList: []
      },
      rules: {
        ClinicalDataTrialSetId: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur', 'change'] }]
      },
      loading: false,
      btnLoading: false,
      clinicalDatas: [],
      pendingUploadList: [],
      pendingDeleteList: [],
      currentTpl: { id: '', isExist: false }
    }
  },
  mounted() {
    this.initForm()
  },
  methods: {
    async initForm() {
      await this.getClinicalDatas()
      if (Object.keys(this.data).length > 0) {
        for (const k in this.form) {
          if (this.data.hasOwnProperty(k)) {
            this.form[k] = this.data[k]
          }
        }
        this.handleClinicalDataSetChange(this.form.ClinicalDataTrialSetId)
        this.fileList = this.form.FileList.concat()
      }
    },
    save() {
      this.$refs.clinicalDataForm.validate(valid => {
        if (!valid) return
        if (this.fileList.length === 0) {
          // 请上传文件！
          this.$alert(this.$t('trials:readingPeriod:cd:message:uploadFile'))
          return
        }
        this.pendingUploadList = []
        for (let i = 0; i < this.fileList.length; ++i) {
          if (this.fileList[i].Status === 0) {
            this.pendingUploadList.push(this.fileList[i].Files)
          }
        }
        if (this.pendingUploadList.length > 0) {
          this.uploadFilesAndSave()
        } else {
          this.saveClinicalData()
        }
      })
    },
    uploadFilesAndSave() {
      return new Promise(async(resolve, reject) => {
        this.form.AddFileList = []
        for (var i = 0; i < this.pendingUploadList.length; ++i) {
          // const file = await this.convertBase64ToBlob(this.pendingUploadList[i])
          const file = await this.fileToBlob(this.pendingUploadList[i])
          const res = await this.OSSclient.put(`/${this.data.TrialId}/ClinicalData/${this.pendingUploadList[i].name}`, file)
          this.form.AddFileList.push({ fileName: this.pendingUploadList[i].name, path: this.$getObjectName(res.url) })
        }
        this.saveClinicalData(this.form.AddFileList)
        resolve()
      })
    },
    saveClinicalData() {
      return new Promise((resolve, reject) => {
        this.btnLoading = true
        this.form.DeleteFileIds = this.pendingDeleteList
        addOrUpdateReadingClinicalData(this.form).then(response => {
          this.btnLoading = false
          this.$emit('getList')
          this.$emit('close')
          this.$message.success(this.$t('common:message:savedSuccessfully'))
          resolve()
        }).catch(() => {
          this.btnLoading = false
          reject()
        })
      })
    },
    getClinicalDatas() {
      return new Promise((resolve, reject) => {
        this.loading = true
        var param = {
          trialId: this.data.TrialId,
          IsVisit: this.data.IsVisit,
          ReadingId: this.data.ReadingId,
          SubjectId: this.data.SubjectId,
          ReadingClinicalDataId: this.data.Id ? this.data.Id : '',
          IsBaseLine: this.data.IsBaseLine,
          TrialReadingCriterionId: this.trialReadingCriterionId
        }
        getTrialClinicalDataSelect(param).then(res => {
          this.clinicalDatas = res.Result
          this.loading = false
          resolve()
        }).catch(() => {
          this.loading = false
          reject()
        })
      })
    },
    handleDeleteFile(index, row) {
      this.$confirm(this.$t('trials:readingPeriod:cd:message:delete'), {
        type: 'warning',
        distinguishCancelAndClose: true
      })
        .then(() => {
          if (row.Id) {
            this.pendingDeleteList.push(row.Id)
          }
          this.fileList.splice(index, 1)
        }).catch(() => {})
    },
    beginScanFiles(e) {
      var files = e.target.files
      for (var i = 0; i < files.length; ++i) {
        const fileName = files[i].name
        var extendName = fileName.substring(fileName.lastIndexOf('.')).toLocaleLowerCase()
        if (this.faccept.indexOf(extendName) !== -1) {
          this.fileList.push({ FileName: fileName, Path: '', Status: 0, Files: files[i] })
        }
      }
    },
    handleClinicalDataSetChange(v) {
      var index = this.clinicalDatas.findIndex(item => item.Id === v)
      if (index > -1) {
        this.currentTpl.id = this.clinicalDatas[index].Id
        this.currentTpl.isExist = !!this.clinicalDatas[index].FileName
      }
    },
    handleDownloadTpl() {
      this.loading = true
      DownloadTrialClinicalFile(this.currentTpl.id).then(data => {
        this.loading = false
      }).catch(() => { this.loading = false })
    },
    close() {
      this.$emit('close')
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
