<template>
  <el-form
    ref="clinicalDataForm"
    v-loading="loading"
    :model="form"
    size="small"
    :rules="rules"
    :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"
            :disabled="type === 'consistencyAnalysis'"
          >
            <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>
      <!-- 数据内容: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" 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 style="margin-left: 10px">{{
                $t('trials:attachment:message:pdf')
              }}</span>
            </div>
          </div>
        </form>
        <!-- 文件列表 -->
        <el-table
          ref="filesTable"
          :data="fileList"
          class="dicomFiles-table"
          height="300"
          style="width: 100%;margin-top:5px;"
          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
            prop="size"
            :label="$t('trials:uploadClinicalData:table:fileSize')"
          >
            <template slot-scope="scope">
              <span>{{
                scope.row.size && scope.row.size > 0
                  ? $FormatSize(scope.row.size)
                  : scope.row.Size && scope.row.Size > 0
                  ? $FormatSize(scope.row.Size)
                  : ''
              }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('common:action:action')">
            <template slot-scope="scope">
              <!-- 删除 -->
              <el-button
                circle
                :title="$t('trials:readingPeriod:cd:action:deleteFile')"
                icon="el-icon-delete"
                @click="handleDeleteFile(scope.$index, scope.row)"
              />
              <!-- 下载 -->
              <el-button
                v-if="type === 'consistencyAnalysis'"
                circle
                :title="$t('trials:readingPeriod:cd:action:upload')"
                icon="el-icon-download"
                @click="handleUploadFile(scope.row)"
              />
            </template>
          </el-table-column>
        </el-table>
    </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,
  addOrUpdateConsistencyAnalysisReadingClinicalData,
} from '@/api/trials'
import { downLoadFile } from '@/utils/stream.js'
export default {
  name: 'AddOrUpdateClinicalData',
  props: {
    trialReadingCriterionId: {
      type: String,
      default: '',
    },
    data: {
      type: Object,
      default() {
        return {}
      },
    },
    type: {
      default: 'readingPeriod',
    },
    option: {
      default: () => [],
    },
  },

  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: {
    // 下载临床数据
    handleUploadFile(row) {
      let href = this.OSSclientConfig.basePath + row.Path
      let name = row.FileName
      downLoadFile(href, name)
    },
    async initForm() {
      if (this.type === 'readingPeriod') {
        await this.getClinicalDatas()
      } else {
        this.clinicalDatas = this.option
      }
      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 = []
        let uploadBatchId = this.$guid()
        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,
            {
              fileName: this.pendingUploadList[i].name,
              fileSize: this.pendingUploadList[i].size,
              fileType: this.pendingUploadList[i].type,
              uploadBatchId: uploadBatchId,
              batchDataType: 4,
              trialId: this.data.TrialId,
              subjectId: this.data.SubjectId,
              subjectVisitId: this.data.SubjectVisitId
            }
          )
          this.form.AddFileList.push({
            fileName: this.pendingUploadList[i].name,
            path: this.$getObjectName(res.url),
            size: this.pendingUploadList[i].size,
            type: this.pendingUploadList[i].type,
          })
        }
        this.saveClinicalData(this.form.AddFileList)
        resolve()
      })
    },
    saveClinicalData() {
      return new Promise((resolve, reject) => {
        this.btnLoading = true
        this.form.DeleteFileIds = this.pendingDeleteList
        if (this.type === 'consistencyAnalysis') {
          addOrUpdateConsistencyAnalysisReadingClinicalData(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()
            })
        } else {
          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],
            size: files[i].size,
            type: fileName.split('.')[1],
          })
        }
      }
    },
    handleClinicalDataSetChange(v) {
      var index = this.clinicalDatas.findIndex((item) => item.Id === v)
      if (index > -1) {
        this.currentTpl.id = this.clinicalDatas[index].Id
        this.currentTpl.path = this.clinicalDatas[index].Path
        this.currentTpl.isExist = !!this.clinicalDatas[index].FileName
      }
    },
    handleDownloadTpl() {
      this.loading = true
      window.open(
        this.OSSclientConfig.basePath + this.currentTpl.path,
        '_blank'
      )
      this.loading = false
      // DownloadTrialClinicalFile(this.currentTpl.id).then(data => {
      //   this.loading = false
      // }).catch(() => { this.loading = false })
    },
    close() {
      this.$emit('close')
    },
  },
}
</script>
<style lang="scss" scoped>
</style>
