<template>
  <div>
    <el-upload
      :action="accept"
      :limit="question.ImageCount"
      :on-preview="handlePictureCardPreview"
      :before-upload="handleBeforeUpload"
      :http-request="uploadScreenshot"
      list-type="picture-card"
      :on-remove="handleRemove"
      :file-list="fileList"
      :class="{disabled:readingTaskState >= 2 || (fileList.length >= question.ImageCount) || (task.VisitTaskId !== visitTaskId) || question.IsShowInDicom || ((task.IsBaseLine && question.LimitEdit === 2) || (!task.IsBaseLine && question.LimitEdit === 1))}"
      :disabled="readingTaskState >= 2  || task.VisitTaskId !== visitTaskId || question.IsShowInDicom || ((task.IsBaseLine && question.LimitEdit === 2) || (!task.IsBaseLine && question.LimitEdit === 1))"
    >
      <i slot="default" class="el-icon-plus" />
      <div slot="file" slot-scope="{file}">
        <viewer
          :ref="file.url"
          :images="[imageUrl]"
          style="
            display: flex;
            align-items: center;
            justify-content: center;
            width: 100%;
            height: 100%;
          "
        >
          <img
            class="el-upload-list__item-thumbnail"
            :src="OSSclientConfig.basePath + file.url"
            crossOrigin="anonymous"
            alt=""
            style="max-width: 100%; max-height: 100%"
          />
          <span class="el-upload-list__item-actions">
            <span
              class="el-upload-list__item-preview"
              @click="handlePictureCardPreview(file)"
            >
              <i class="el-icon-zoom-in" />
            </span>

            <span
              v-if="readingTaskState < 2"
              class="el-upload-list__item-delete"
              @click="handleRemove(file)"
            >
              <i class="el-icon-delete" />
            </span>
          </span>
        </viewer>
      </div>
    </el-upload>
  </div>
</template>

<script>
export default {
name: "UploadFile",
  props: {
    task: {
      Type: Object,
      required: true
    },
    question: {
      Type: Object,
      required: true
    },
    visitTaskId: {
      type: String,
      required: true
    },
    readingTaskState: {
      type: Number,
      required: true
    },
    initUrl: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      imgVisible: false,
      imageUrl: null,
      accept: '.png,.jpg,.jpeg',
      fileList: [],
    }
  },
  mounted() {
    this.urls = this.initUrl === '' ? [] : this.initUrl.split('|')
    console.log(this.visitTaskId, this.urls)
    this.fileList = []
    this.urls.map(url => {
      this.fileList.push({ name: '', url: `${url}` })
    })
    console.log(this.fileList)
  },
  methods: {
    checkFileSuffix(fileName) {
      var index = fileName.lastIndexOf('.')
      var suffix = fileName.substring(index + 1, fileName.length)
      if (this.accept.toLocaleLowerCase().search(suffix.toLocaleLowerCase()) === -1) {
        return false
      } else {
        return true
      }
    },
    async uploadScreenshot(param) {
      if (!this.visitTaskId) return
      const loading = this.$loading({
        target: document.querySelector('.ecrf-wrapper'),
        fullscreen: false,
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading'
      })
      var trialId = this.$route.query.trialId
      var subjectId = this.$route.query.trialId
      var file = await this.fileToBlob(param.file)
      const res = await this.OSSclient.put(`/${trialId}/Read/${subjectId}/Visit/${param.file.name}`, file)
      console.log(res)
      this.fileList.push({ name: param.file.name, path: this.$getObjectName(res.url), url: this.$getObjectName(res.url)})
      this.urls.push(this.$getObjectName(res.url))
      this.$emit('setImageUrl', this.urls.length > 0 ? this.urls.join('|') : '')
      loading.close()
    },
    handleBeforeUpload(file) {
      // 检测文件类型是否符合要求
      if (this.checkFileSuffix(file.name)) {
        // this.fileList = []
        return true
      } else {
        this.$alert(`必须是 ${this.accept} 格式`)
        return false
      }
    },
    // 预览图片
    handlePictureCardPreview(file) {
      var suffix = file.url.substring(file.url.lastIndexOf(".")+1)
      suffix = suffix ? suffix.toLowerCase() : ''
      if (suffix === 'doc' || suffix === 'docx' || suffix === 'pdf'){
        window.open(this.OSSclientConfig.basePath + file.url,'_blank')
      }else{
        this.imageUrl = this.OSSclientConfig.basePath + file.url
        // this.imgVisible = true
        this.$refs[file.url].$viewer.show()
      }
    },
    // 删除图片
    handleRemove(file, fileList) {
      this.imageUrl = ''
      this.fileList.splice(this.fileList.findIndex(f => f.url === file.url), 1)
      this.urls.splice(this.fileList.findIndex(f => f === file.url), 1)
      this.$emit('setFormItemData', { key: this.question.Id, val: this.urls.length > 0 ? this.urls.join('|') : '' })
    },
  }
}
</script>

<style lang="scss" scoped>
.disabled{
  /deep/ .el-upload--picture-card {
    display: none;
  }
}
</style>
