<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}">
        <img
          class="el-upload-list__item-thumbnail"
          :src="OSSclientConfig.basePath + file.url"
          alt=""
        >
        <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>
      </div>
    </el-upload>
    <el-dialog
      append-to-body
      :visible.sync="imgVisible"
      width="600px"
    >
      <el-image :src="imageUrl" width="100%">
        <div slot="placeholder" class="image-slot">
          加载中<span class="dot">...</span>
        </div>
      </el-image>
    </el-dialog>
  </div>
</template>

<script>
import { uploadReadingAnswerImage, getTrialOrganList, getCustomTableQuestionPreview } from '@/api/trials'
export default {
name: "CustomizeReportPageUpload",
  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('|')
    this.fileList = []
    this.urls.map(url => {
      this.fileList.push({ name: '', url: `/api/${url}` })
    })
  },
  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
      }
    },
    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'
      })
      const formData = new FormData()
      formData.append('file', param.file)
      uploadReadingAnswerImage(this.$route.query.trialId, this.visitTaskId, formData).then(res => {
        if (res.IsSuccess) {
          this.fileList.push({ url: `/api/${res.Result.Path}` })
          this.urls.push(res.Result.Path)
          // this.questionForm[]
          this.$emit('setImageUrl', this.urls.length > 0 ? this.urls.join('|') : '')
        }
        loading.close()
      }).catch(() => {
        loading.close()
      })
    },
    handleBeforeUpload(file) {
      // 检测文件类型是否符合要求
      if (this.checkFileSuffix(file.name)) {
        // this.fileList = []
        return true
      } else {
        this.$alert(`必须是 ${this.accept} 格式`)
        return false
      }
    },
    // 预览图片
    handlePictureCardPreview(file) {
      this.imageUrl = this.OSSclientConfig.basePath + file.url
      this.imgVisible = true
    },
    // 删除图片
    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>
