<template>
  <div v-loading="loading" class="study-wrapper">
    <div class="study-info">
      <div v-if="taskInfo && taskInfo.IsReadingShowSubjectInfo" :title="taskInfo.SubjectCode">
        {{ taskInfo.SubjectCode }}
      </div>
      <div :title="visitTaskInfo.TaskBlindName">
        <span v-if="taskInfo && !taskInfo.IsReadingShowSubjectInfo">
          {{ $t('trials:reading:title:taskName') }}
        </span>
        {{ visitTaskInfo.TaskBlindName }}
      </div>
    </div>
    <div class="ps" ref="studyBox_ps">
      <el-collapse v-model="activeNames" @change="handleChange">
        <el-collapse-item v-for="(study, index) in studyList" :key="`${study.Id}`" :name="`${study.Id}`">
          <template slot="title">
            <div v-if="!study.IsCriticalSequence" class="dicom-desc">
              <!-- <div v-if="taskInfo && taskInfo.IsShowStudyName">{{ study.StudyName }}</div> -->
              <div style="text-overflow: ellipsis;overflow: hidden;">
                <span v-if="taskInfo && taskInfo.IsReadingTaskViewInOrder !== 0" :title="study.CodeView">{{
                  study.CodeView }}</span>
                <span v-if="taskInfo && taskInfo.IsShowStudyName" :title="study.StudyName" style="margin-left: 5px;">{{
                  study.StudyName }}</span>
              </div>
              <div style="text-overflow: ellipsis;overflow: hidden;">
                <span :title="study.DisplayBodyPart">{{ study.DisplayBodyPart }}</span>
                <span style="margin-left: 5px;" :title="study.Modality">{{ study.Modality }}</span>
              </div>
            </div>
            <div v-else>
              <!-- 关键文件 -->
              {{ $t('trials:noneDicom:title:keyFiles') }}
            </div>
          </template>
          <div class="file-list-container">
            <div v-for="(k, i) in study.NoneDicomStudyFileList" :key="i" style="position:relative;margin-top:1px;"
              @click="selectFile(study, index, i, k)" :ref="`noneDicomRef_${i}`">
              <div :class="{ 'file-active': index === activeStudyIndex && i === activeFileIndex }" class="file-wrapper">
                <div class="file-image">
                  <el-image
                    v-if="k.FileType === 'image/jpeg' || k.FileType === 'image/jpg' || k.FileType === 'image/bmp' || k.FileType === 'image/png'"
                    style="width: 100%;height: 100%;"
                    :src="`${OSSclientConfig.basePath}${k.Path}?x-oss-process=image/resize,w_50,h_50/format,png`"
                    fit="contain" crossorigin="anonymous" />
                  <el-image v-else-if="k.FileType === 'application/pdf'" style="width: 100%;height: 100%;" :src="pdf"
                    fit="contain" crossorigin="anonymous" />
                  <el-image v-else-if="
                    !!~k.FileType.indexOf('mp4')
                  " style="width: 100%; height: 100%" :src="mp4" fit="contain" crossorigin="anonymous" />
                </div>
                <div class="file-text" :title="k.FileName">
                  {{ k.FileName }}
                </div>
                <div>
                  <i v-if="visitTaskInfo.ReadingTaskState < 2 && (currentMarkedFiles[k.Id] && currentMarkedFiles[k.Id].count > 0)"
                    class="el-icon-star-on" style="font-size: 12px;color: #ff5722;" />
                  <i v-else-if="visitTaskInfo.ReadingTaskState >= 2 && k.IsBeMark" class="el-icon-star-on"
                    style="font-size: 12px;color: #ff5722;" />
                </div>
              </div>
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
  </div>
</template>
<script>
import pdf from '@/assets/pdf.png'
import mp4 from '@/assets/mp4.png'
export default {
  name: 'StudyList',
  props: {
    visitTaskInfo: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      loading: false,
      activeNames: [],
      activeStudyIndex: -1,
      activeFileIndex: -1,
      taskInfo: null,
      studyList: [],
      pdf,
      mp4,
      BodyPart: {},
      currentMarkedFiles: {}
    }
  },
  async mounted() {
    this.taskInfo = JSON.parse(localStorage.getItem('taskInfo'))
    this.BodyPart.Bodypart = await this.$getBodyPart(this.$route.query.trialId)
    this.studyList = this.decorateStudyList(this.visitTaskInfo.StudyList || [])
    this.initCurrentMaredFiles(this.visitTaskInfo.Annotations)
    if (this.studyList.length === 0) return
    this.$nextTick(() => {
      this.activeStudy(this.studyList[0].Id)
    })
  },
  watch: {
    activeFileIndex() {
      if (this.$refs[`noneDicomRef_${this.activeFileIndex}`]) {
        this.scrollElementToTop(this.$refs[`noneDicomRef_${this.activeFileIndex}`][0], {
          offset: 50
        })
      }
    },
    'visitTaskInfo.Annotations': {
      handler(annotations) {
        this.initCurrentMaredFiles(annotations)
      },
      deep: true
    }
  },
  methods: {
    buildCurrentMarkedFiles(annotations = []) {
      return annotations.reduce((result, item) => {
        const fileId = item?.NoneDicomFileId
        if (!fileId) return result
        if (!Object.hasOwn(result, fileId)) {
          result[fileId] = { count: 1 }
        } else {
          result[fileId].count++
        }
        return result
      }, {})
    },
    decorateStudyList(studyList = []) {
      return studyList.map(study => ({
        ...study,
        DisplayBodyPart: this.getBodyPart(study.BodyPart, study.BodyPartForEditOther)
      }))
    },
    scrollElementToTop(element, options = {}) {
      const container = this.$refs['studyBox_ps']
      if (!container || !element) return
      const elementTop = element.offsetTop
      const elementBottom = elementTop + element.offsetHeight
      const visibleTop = container.scrollTop
      const visibleBottom = visibleTop + container.clientHeight
      if (elementTop >= visibleTop && elementBottom <= visibleBottom) return
      const targetPosition = Math.max(elementTop - (options.offset || 0), 0)
      container.scrollTo({
        top: targetPosition,
        behavior: options.behavior || 'smooth'
      })
    },
    getBodyPart(bodyPart, other) {
      if (!bodyPart && !other) return ''
      if (!bodyPart) return other || ''
      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(' | ')
    },
    // 设置初始化激活文件
    setInitActiveFile() {
      if (this.studyList.length === 0) {
        this.studyList = this.decorateStudyList(this.visitTaskInfo.StudyList || [])
      }
      if (this.studyList.length === 0) return
      this.$nextTick(() => {
        this.activeStudy(this.studyList[0].Id)
        this.selectFile(this.studyList[0], 0, 0, this.studyList[0].NoneDicomStudyFileList[0])
      })
    },
    // 切换文件
    selectFile(study, studyIndex, fileIndex, item) {
      // if (item.FileType.includes('mp4')) return this.$preview({
      //   path: item.Path || item.FilePath,
      //   type: 'mp4',
      //   title: item.FileName,
      // }) 
      this.activeStudyIndex = studyIndex
      this.activeFileIndex = fileIndex
      const fileList = study.NoneDicomStudyFileList
      this.$emit('selectFile', { fileInfo: fileList[fileIndex], fileList, visitTaskInfo: this.visitTaskInfo, studyId: study.Id })
    },
    activeImage(obj) {
      if (this.studyList.length === 0) return
      const i = this.studyList.findIndex(i => i.Id === obj.studyId)
      if (i === -1) return
      this.activeStudy(obj.studyId)
      this.activeStudyIndex = i
      const fileList = this.studyList[i].NoneDicomStudyFileList
      const fIndex = fileList.findIndex(f => f.Path === obj.path)
      if (fIndex === -1) return
      this.activeFileIndex = fIndex
    },
    activeStudy(id) {
      const studyId = `${id}`
      if (this.activeNames.indexOf(studyId) > -1) return
      this.activeNames.push(studyId)
    },
    handleChange(v) {
      console.log(v)
    },
    getMarkedFileIds(obj) {
      const { type, fileId, visitTaskId } = obj
      if (this.visitTaskInfo.ReadingTaskState >= 2 || visitTaskId !== this.taskInfo.VisitTaskId) {
        return
      }
      if (!fileId) return
      if (type === 'remove') {
        if (Object.hasOwn(this.currentMarkedFiles, fileId)) {
          this.currentMarkedFiles[fileId].count--
          if (this.currentMarkedFiles[fileId].count <= 0) {
            this.$delete(this.currentMarkedFiles, fileId)
          }
        }
      } else if (type === 'add') {
        if (!Object.hasOwn(this.currentMarkedFiles, fileId)) {
          this.$set(this.currentMarkedFiles, fileId, { count: 1 })
        } else {
          this.currentMarkedFiles[fileId].count++
        }

      }
    },
    initCurrentMaredFiles(annotations = this.visitTaskInfo.Annotations || []) {
      this.currentMarkedFiles = this.buildCurrentMarkedFiles(annotations)
    },
  }
}
</script>
<style lang="scss" scoped>
.study-wrapper {
  width: 100%;
  height: 100%;
  overflow-y: hidden;
  overflow-x: hidden;
  display: flex;
  flex-direction: column;

  .study-info {
    font-size: 16px;
    font-weight: bold;
    color: #ddd;
    padding: 5px 0px;
    margin: 0;
    text-align: center;
    background-color: #4c4c4c;
    min-height: 50px;
    height: auto;
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    word-break: break-word;
  }

  .dicom-desc {
    font-weight: bold;
    font-size: 13px;
    text-align: left;
    color: #d0d0d0;
    padding: 2px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .ps {
    flex: 1;
    overflow-anchor: none;
    touch-action: auto;
    overflow-y: auto;
  }

  .file-active {
    background-color: #607d8b !important;
    border: 1px solid #607d8b !important;
  }

  ::v-deep .el-progress__text {
    color: #ccc;
    font-size: 12px;
  }

  .file-list-container {
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;

    .file-wrapper {
      width: 100%;
      padding: 5px;
      display: flex;
      flex-direction: row;
      align-items: center;
      cursor: pointer;
      background-color: #3a3a3a;

      // color: #ddd;
      // white-space: nowrap;
      // overflow: hidden;
      // text-overflow: ellipsis;
      .el-progress__text {
        display: none;
      }

      .el-progress-bar {
        padding-right: 0px;
      }

      .file-image {
        width: 50px;
        height: 50px;
      }

      .file-text {
        flex: 1;
        padding-left: 5px;
        color: #ddd;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

    }
  }

  ::v-deep .el-collapse {
    border: none;

    .el-collapse-item {
      background-color: #000 !important;
      color: #ddd;

    }

    .el-collapse-item__content {
      padding-bottom: 0px;
      background-color: #000 !important;
    }

    .el-collapse-item__header {
      background-color: #000 !important;
      color: #ddd;
      border-bottom-color: #5a5a5a;
      padding-left: 5px;
      height: 60px;
      line-height: 20px;
    }
  }

  ::v-deep .el-progress-bar__inner {
    transition: width 0s ease;
  }
}
</style>
