<template>
  <div class="previous-files-wrapper">

    <!-- 多文件上传 -->
    <form id="inputForm" ref="uploadForm">
      <!-- 必须是PDF格式 -->
<!--      <el-divider content-position="left">{{ $t('trials:attachment:message:pdf') }}</el-divider>-->
      <div class="form-group">
        <div id="directoryInputWrapper" class="btn btn-link" style="position: relative;overflow: hidden;display: inline-block;">
          <el-button size="small">{{ $t('trials:uploadClinicalData:button:selectFile') }}</el-button>
          <input
            type="file"
            name="file"
            multiple
            style="position: absolute;top: 0;left: 0;width: 100%;height: 100%;opacity: 0;cursor: pointer;"
            :accept="faccept.join(',')"
            @change="beginScanFiles($event)"
          >
          <!-- <span>共扫描了，符合要求的有</span> -->
        </div>
      </div>
    </form>
    <!-- 文件列表 -->
    <el-table
      ref="filesTable"
      :data="fileList"
      class="dicomFiles-table"
      height="300"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
      />
      <el-table-column
        prop="name"
        :label="$t('trials:uploadClinicalData:table:fileName')"
        min-width="180"
      />
    </el-table>
    <div style="text-align:right;padding: 10px 0px">
      <!-- 上传 -->
      <el-button
        size="small"
        type="primary"
        :disabled="selectArr.length == 0"
        :loading="btnLoading"
        @click="handleUploadFile"
      >
        {{ $t('trials:uploadClinicalData:button:uploadFile') }}
      </el-button>
    </div>
  </div>
</template>
<script>
// import { uploadVisitClinicalData } from '@/api/trials'
import { addOrUpdateReadingClinicalData, uploadClinicalData } from '@/api/trials'
export default {
  props: {
    data: {
      type: Object,
      default() { return {} }
    },
    subjectVisitId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      fileList: [],
      btnLoading: false,
      faccept: ['.pdf'],
      trialId: this.$route.query.trialId,
      selectArr: [],
      addFileList: []
    }
  },
  methods: {
    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(files[i])
        }
      }
    },
    // 获取待上传文件信息
    handleSelectionChange(selection) {
      this.selectArr = selection
    },

    async handleUploadFile() {
      this.btnLoading = true
      this.addFileList = []
      for (var i = 0; i < this.selectArr.length; ++i) {
        const file = await this.fileToBlob(this.selectArr[i])
        const res = await this.OSSclient.put(`/${this.trialId}/ClinicalData/${this.selectArr[i].name}`, file)
        this.addFileList.push({ fileName: this.selectArr[i].name, path: this.$getObjectName(res.url), url: this.$getObjectName(res.url) })
      }
      this.saveClinicalData()
      this.btnLoading = false
      // var fileData = new FormData()
      // for (var i = 0; i < this.selectArr.length; ++i) {
      //   fileData.append('file', this.selectArr[i])
      // }
      // uploadClinicalData(this.trialId, this.data.SubjectId, this.subjectVisitId, fileData).then(res => {
      //   this.btnLoading = false
      //   this.addFileList = res.Result
      //   this.saveClinicalData()
      // }).catch(() => {
      //   this.btnLoading = false
      // })
    },
    fileToBlob(file) {
      // 创建 FileReader 对象
      const reader = new FileReader()
      return new Promise(resolve => {
        // FileReader 添加 load 事件
        reader.addEventListener('load', (e) => {
          let blob
          if (typeof e.target.result === 'object') {
            blob = new Blob([e.target.result])
          } else {
            blob = e.target.result
          }
          resolve(blob)
        })
        // FileReader 以 ArrayBuffer 格式 读取 File 对象中数据
        reader.readAsArrayBuffer(file)
      })
    },
    saveClinicalData() {
      this.btnLoading = true
      var param = {
        id: this.data.Id,
        trialId: this.trialId,
        subjectId: this.data.SubjectId,
        readingId: this.subjectVisitId,
        clinicalDataTrialSetId: this.data.ClinicalDataTrialSetId,
        isVisit: true,
        deleteFileIds: [],
        addFileList: this.addFileList
      }
      addOrUpdateReadingClinicalData(param).then(response => {
        this.btnLoading = false
        // 刷新文件列表并关闭弹窗
        this.$emit('closeUpDialog')
        this.$emit('refresh')
        this.$message.success(this.$t('trials:uploadClinicalData:message:uploadSuccessfully'))
      }).catch(() => {
        this.btnLoading = false
      })
    }
  }
}
</script>
