<template>
  <div class="img-container">
    <el-card v-loading="loading" class="box-card left">
      <div v-if="isReadingShowSubjectInfo" class="title">
        <h4>{{ subjectCode }} </h4>
        <h4>{{ taskBlindName }}</h4>
      </div>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane :label="$t('trials:clinicaldara:title:currentTask')" name="first" class="left-content">
          <div>
            <!-- 检查层级 -->
            <div v-for="(study, i) in studyList" :key="study.CodeView">
              <div class="study-desc">
                <span>{{ study.CodeView }}</span>
                <span style="margin:0 5px">{{ study.Modality }}</span>
                <span>{{ getBodyPart(study.BodyPart, study.BodyPartForEditOther) }}</span>
              </div>
              <!-- 文件层级 -->
              <div v-if="study.NoneDicomStudyFileList.length === 0" class="empty-text">
                <slot name="empty">{{ $t('trials:audit:message:noData') }}</slot>
              </div>
              <div v-else id="imgList" style="height:100%;">
                <div v-for="(item, j) in study.NoneDicomStudyFileList" :id="`img${item.Id}`" :key="item.Id" :class="{
                  'is-boxActive': item.Id === currentFileId
                }" class="img-box" @click="selected(item, i, j, true)">
                  <div v-if="item.FileName.length < 15" class="img-text">
                    {{ `${j + 1}. ${item.FileName}` }}
                  </div>
                  <el-tooltip v-else :content="item.FileName" placement="bottom">
                    <div class="img-text">
                      {{ `${j + 1}. ${item.FileName}` }}
                    </div>
                  </el-tooltip>
                </div>

              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane v-if="showOtherTask === true" :label="$t('trials:clinicaldara:title:relatedTask')" name="second">
          <div style="height:100%;">
            <!-- 文件层级 -->
            <div v-if="associatedList.length === 0" class="empty-text">
              <slot name="empty">{{ $t('trials:audit:message:noData') }}</slot>
            </div>
            <div v-else>
              <div v-for="(task, j) in associatedList" :key="task.VisitTaskId" :class="{
                'is-boxActive': task.VisitTaskId === currentTaskId
              }" class="img-box" @click="handleImageRead(task)">
                <div v-if="task.TaskBlindName.length < 15" class="img-text">
                  {{ `${j + 1}. ${task.TaskBlindName}` }}
                </div>
                <el-tooltip v-else :content="task.TaskBlindName" placement="bottom">
                  <div class="img-text">
                    {{ `${j + 1}. ${task.TaskBlindName}` }}
                  </div>
                </el-tooltip>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>

    </el-card>
    <!-- 预览图像 -->
    <el-card v-loading="loading" class="box-card right">
      <div style="width:100%;height: 100%;">
        <Preview v-if="previewImage.imgList.length > 0" ref="previewImage" style="width:100%;"
          :preview-image="previewImage" :value="currentStudyFileIndex" @selectedImg="selectedImg" />
      </div>

    </el-card>

    <el-card class="box-card" style="width:400px;height:100%;padding: 10px;margin-left:10px;overflow-y: auto;">
      <!-- <div style="text-align:right;">
        <el-button
          v-if="otherInfo && otherInfo.IsExistsClinicalData"
          type="text"
          @click="previewCD"
        >
          {{ $t('trials:crcUpload:label:clinicalData') }}
        </el-button>
      </div> -->
      <Criterions
        v-if="otherInfo && visitTaskId !== '' && subjectId !== '' && readingCategory !== null && readingCategory !== 4"
        :trial-id="trialId" :subject-id="subjectId" :visit-task-id="visitTaskId"
        :criterion-id="otherInfo.TrialCriterionId" :subject-code="subjectCode" :task-blind-name="taskBlindName"
        :is-reading-show-subject-info="isReadingShowSubjectInfo"
        :ise-c-r-f-show-in-dicom-reading="iseCRFShowInDicomReading" :isExistsClinicalData="isExistsClinicalData"
        @previewCD="previewCD" />
    </el-card>
  </div>

</template>

<script>
import { getReadingImageFile, getReadingPastResultList } from '@/api/trials'
import { getToken } from '@/utils/auth'
import Preview from '@/views/none-dicom-show/components/preview'
import Criterions from './Criterions'
export default {
  name: 'VisitReview',
  components: {
    Preview,
    Criterions
  },
  props: {
    trialId: {
      type: String,
      required: true
    },
    subjectId: {
      type: String,
      required: true
    },
    subjectCode: {
      type: String,
      required: true
    },
    visitTaskId: {
      type: String,
      required: true
    },
    taskBlindName: {
      type: String,
      required: true
    },
    readingCategory: {
      type: Number,
      required: true
    },
    isReadingShowSubjectInfo: {
      type: Boolean,
      required: true
    },
    readingTool: {
      type: String,
      required: true
    },
    criterionType: {
      type: String,
      required: true
    },
    isReadingTaskViewInOrder: {
      type: Number,
      required: true
    },
    iseCRFShowInDicomReading: {
      type: Boolean,
      required: true
    },
    isExistsClinicalData: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      activeName: 'first',
      currentFileId: '',
      currentStudyIndex: 0,
      currentStudyFileIndex: 0,
      pageSize: 0, // 一页展示的图片数
      previewImage: {
        imgList: [],
        index: 0, // 当前点击的图片的索引
        infinite: true, // 是否可以循环切换
        popup: true, // 弹窗的显示隐藏
        studyCode: '',
        modality: '',
        bodyPart: ''
      },
      previewVisible: false,
      studyList: [],
      loading: false,
      isRenderAssocicatedTasks: false,
      associatedList: [],
      currentTaskId: '',
      otherInfo: null,
      isReadingShowPreviousResults: false,
      BodyPart: {},
      openWindow: null
    }
  },
  computed: {
    showOtherTask() {
      return this.otherInfo && this.otherInfo.IsReadingShowPreviousResults && this.isReadingShowPreviousResults
    }
  },
  async mounted() {
    this.BodyPart.Bodypart = await this.$getBodyPart(this.$route.query.trialId)
    this.isReadingShowPreviousResults = this.$router.currentRoute.query.isReadingShowPreviousResults !== undefined ? this.$router.currentRoute.query.isReadingShowPreviousResults : true

    this.getNoneDicomList(this.isReadingShowPreviousResults)
  },
  beforeDestroy() {
    if (this.openWindow) {
      this.openWindow.close()
    }
  },
  methods: {
    // 获取非Dicom检查信息
    getNoneDicomList() {
      this.loading = true
      var param = {
        subjectId: this.subjectId,
        trialId: this.trialId,
        visistTaskId: this.visitTaskId
      }
      getReadingImageFile(param).then(res => {
        this.otherInfo = res.OtherInfo
        if (res.Result.length > 0) {
          this.studyList = res.Result
          const studyIndex = this.studyList.findIndex(item => {
            return item.NoneDicomStudyFileList.length > 0
          })
          if (studyIndex > -1) {
            var fileObj = this.studyList[studyIndex]['NoneDicomStudyFileList']
            this.selected(fileObj[0], studyIndex, 0, true)
          }
        } else {
          // this.$alert('当前影像存在问题，请联系PM！')
        }
        this.loading = false
      }).catch(() => { this.loading = false })
    },
    selected(file, studyIndex, fileIndex, isChangeSub = false) {
      this.currentFileId = file.Id
      this.currentStudyIndex = studyIndex
      this.previewImage.imgList = this.studyList[studyIndex].NoneDicomStudyFileList
      this.currentStudyFileIndex = fileIndex
      this.previewImage.index = fileIndex
      this.previewImage.studyCode = this.studyList[studyIndex].CodeView
      this.previewImage.bodyPart = this.studyList[studyIndex].BodyPart
      this.previewImage.modality = this.studyList[studyIndex].Modality
      this.$nextTick(() => {
        if (isChangeSub) {
          this.$refs['previewImage'].selected(fileIndex)
        }
      })
    },
    selectedImg(fileIndex) {
      if (this.studyList.length > 0) {
        this.currentStudyFileIndex = fileIndex
        this.currentFileId = this.studyList[this.currentStudyIndex].NoneDicomStudyFileList[fileIndex].Id
        this.previewImage.index = fileIndex
        this.previewImage.studyCode = this.studyList[this.currentStudyIndex].CodeView
        this.previewImage.bodyPart = this.studyList[this.currentStudyIndex].BodyPart
        this.previewImage.modality = this.studyList[this.currentStudyIndex].Modality
        this.$nextTick(() => {
          const target = document.getElementById(`img${this.currentFileId}`)
          const parent = document.getElementsByClassName('left-content')[0]
          parent.scrollTop = target.offsetTop - parent.offsetTop
        })
      }
    },
    preview() {
      this.previewVisible = true
    },
    handleClick(tab) {
      if (tab.name === 'second' && !this.isRenderAssocicatedTasks) {
        this.getAssociatedTask()
      }
    },
    getAssociatedTask() {
      this.loading = true
      var param = {
        trialId: this.trialId,
        subjectId: this.subjectId,
        visitTaskId: this.visitTaskId
      }
      getReadingPastResultList(param).then(res => {
        this.associatedList = res.Result
        this.isRenderAssocicatedTasks = true
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleImageRead(task) {
      if (this.openWindow) {
        this.openWindow.close()
      }
      this.currentTaskId = task.VisitTaskId
      var criterionType = this.criterionType
      var readingTool = this.readingTool
      var isReadingTaskViewInOrder = this.isReadingTaskViewInOrder
      var trialReadingCriterionId = this.$router.currentRoute.query.TrialReadingCriterionId
      var token = getToken()
      const path = `/noneDicomReading?TrialReadingCriterionId=${trialReadingCriterionId}&trialId=${this.trialId}&visitTaskId=${task.VisitTaskId}&subjectCode=${this.subjectCode}&subjectId=${this.subjectId}&isReadingTaskViewInOrder=${isReadingTaskViewInOrder}&criterionType=${criterionType}&readingTool=${readingTool}&TokenKey=${token}`
      // const routeData = this.$router.resolve({
      //   path: `/readingPage?subjectId=${this.subjectId}&trialId=${this.trialId}&visitTaskId=${task.VisitTaskId}&TokenKey=${token}`
      // })
      const routeData = this.$router.resolve({ path })
      this.openWindow = window.open(routeData.href, '_blank')
    },
    previewCD() {
      // var token = getToken()
      // const routeData = this.$router.resolve({
      //   path: `/clinicalData?subjectId=${this.subjectId}&trialId=${this.trialId}&visitTaskId=${this.visitTaskId}&TokenKey=${token}`
      // })
      // window.open(routeData.href, '_blank')
      this.$emit('previewCD', this.visitTaskId)
    },
    getBodyPart(bodyPart, other) {
      if (!bodyPart && !other) return ''
      var separator = ','
      if (bodyPart.indexOf('|') > -1) {
        separator = '|'
      } else if (bodyPart.indexOf(',') > -1) {
        separator = ','
      } else if (bodyPart.indexOf('，') > -1) {
        separator = '，'
      }
      var arr = bodyPart.split(separator)
      var newArr = arr.map((i) => {
        return this.$fd('Bodypart', i.trim(), 'Code', this.BodyPart, 'Name')
      })
      if (other) {
        newArr.push(other)
      }
      newArr = newArr.filter(Boolean)
      return newArr.join(' | ')
    },
  }
}
</script>

<style lang="scss" scoped>
.img-container {
  flex: 1;
  width: 100%;
  height: 100%;
  padding-bottom: 10px;
  display: flex;

  ::-webkit-scrollbar {
    width: 7px;
    height: 7px;
  }

  ::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background: #d0d0d0;
  }

  ::v-deep .el-card__body {
    padding: 0px;
  }
}

.study-desc {
  padding: 10px 5px;
  line-height: 1;
  background-color: #ebebeb;
  font-weight: 500;
}

.left {
  width: 240px;
  height: 100%;

  ::v-deep .el-card__body {
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
  }

  .title {
    // height: 40px;
    // line-height: 40px;
    border: 1ppx solid;
    border: 1px solid #ebe7e7;
    // padding-left: 10px;
    background-color: #4e4e4e;
    color: #ffffff;

    h4 {
      padding: 5px 0px;
      margin: 0;
      text-align: center;
      background-color: #4c4c4c;
    }
  }

  .left-content {
    flex: 1;
    overflow-y: auto;
  }

  ::v-deep .el-tabs {
    height: 100%;
    display: flex;

    flex-direction: column;
  }

  ::v-deep .el-tabs__header {
    height: 40px;
    padding: 0 5px;
    margin-bottom: 5px;
  }

  ::v-deep .el-tabs__content {
    flex: 1;
    overflow-y: auto;
    padding: 0 5px;
  }

  .img-box {
    // position: relative;
    display: inline-block;
    box-sizing: border-box;
    border-bottom: 2px solid #f3f3f3;
    cursor: pointer;
    // margin-bottom: 5px;
    padding-left: 5px;
  }

  .img-text {
    display: inline-block;
    width: 200px;
    height: 50px;
    line-height: 50px;
    overflow: hidden;
    text-overflow: ellipsis;
    /* 用省略号表示溢出的文本 */
    white-space: nowrap;
  }

  .img-box:nth-last-child(1) {
    margin-bottom: 0px;
  }

  .is-boxActive {
    // border-color: #409eff;
    color: #409eff;
  }

  .is-boxActiv:after {
    opacity: 0;
  }
}

.right {
  flex: 1;
  height: 100%;
  margin-left: 10px;

  ::v-deep .el-card__body {
    height: 100%;
    width: 100%;
  }
}
</style>
