<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">
      <el-collapse v-model="activeNames">

        <el-collapse-item v-for="(study, index) in studyList" :key="`${study.StudyId}`" :name="`${study.StudyId}`">
          <template slot="title">
            <div v-if="!study.IsCriticalSequence" class="dicom-desc">
              <div style="text-overflow: ellipsis;overflow: hidden;">
                <span v-if="taskInfo && taskInfo.IsShowStudyName && study.StudyName" :title="study.StudyName">
                  {{ study.StudyName }}
                </span>
              </div>
              <div>
                <span class="study-meta-line" :title="study.Modalities">
                  <span v-if="taskInfo && taskInfo.IsReadingTaskViewInOrder !== 0" class="study-code"
                    :title="study.StudyCode">{{ study.StudyCode }}</span>
                  <span class="study-modality">{{ `${study.Modalities}(${study.SeriesCount})` }}</span>
                  <span class="patient-info" v-if="['PT、CT', 'CT、PT', 'PET-CT'].includes(study.Modalities)">
                    <el-popover placement="right-start" trigger="hover" popper-class="patient-info-popper">
                      <h4>{{ $t('trials:ptData:title') }}</h4>
                      <div class="patient-info-row">
                        <label>{{ $t('trials:ptData:label:patientSex') }}</label>
                        <span>{{ study.PatientSex }}</span>
                      </div>
                      <div class="patient-info-row">
                        <label>{{ $t('trials:ptData:label:patientWeight') }}</label>
                        <span>{{ study.PatientWeight }}</span>
                      </div>
                      <div class="patient-info-row">
                        <label>{{ $t('trials:ptData:label:totalDose') }}</label>
                        <span>{{ study.RadionuclideTotalDose }}</span>
                      </div>
                      <div class="patient-info-row">
                        <label>{{ $t('trials:ptData:label:halfLife') }}</label>
                        <span>{{ study.RadionuclideHalfLife }}</span>
                      </div>
                      <div class="patient-info-row">
                        <label>{{ $t('trials:ptData:label:injectTime') }}</label>
                        <span>{{ study.RadiopharmaceuticalStartTime }}</span>
                      </div>
                      <div class="patient-info-row">
                        <label>{{ $t('trials:ptData:label:acquisitionTime') }}</label>
                        <span>{{ study.AcquisitionTime }}</span>
                      </div>
                      <i slot="reference" class="el-icon-document"
                        style="font-size: 15px;cursor: pointer;color: #f5f7fa;" />
                    </el-popover>
                  </span>
                </span>
              </div>

            </div>
            <div v-else class="dicom-desc">
              <!-- 关键序列 -->
              {{ $t('trials:reading:title:keySeries') }}
            </div>
          </template>
          <div class="dicom-list-container">
            <div v-for="(series, i) in study.SeriesList" :key="series.Id" style="position:relative;margin-top:1px;"
              @click="activeSeries(series, i, index)">
              <div :class="{ 'series-active': index === activeStudyIndex && i === activeSeriesIndex }"
                class="series-wrapper">
                <div class="series-image">
                  <el-image style="width: 100%;height: 100%;"
                    :src="`${OSSclientConfig.basePath}${series.ImageResizePath || series.NoneDicomFileFirstFile}`"
                    fit="fill" crossorigin="anonymous" />
                </div>
                <div class="series-text">
                  <div v-if="series.IsExistMutiFrames && series.InstanceCount > 1"
                    style="position: absolute;right: 0;top: 0;">
                    <el-popover placement="right" trigger="hover" popper-class="instance_frame_wrapper">
                      <div class="frame_list">
                        <div v-for="(instance, idx) in series.InstanceInfoList" :key="instance.Id" class="frame_content"
                          :class="{ 'frame_content_active': activeInstanceId === instance.Id }"
                          :style="{ 'margin-bottom': idx < series.InstanceInfoList.length - 1 ? '5px' : '0px' }"
                          @click.stop="showMultiFrames(index, series, i, instance)">
                          <div>
                            <div>{{ instance.InstanceNumber }}</div>
                            <div>{{ `${instance.NumberOfFrames > 0 ? instance.KeyFramesList.length > 0 ?
                              instance.KeyFramesList.length : instance.NumberOfFrames : 1} frame` }}</div>
                          </div>

                        </div>
                      </div>
                      <i slot="reference" class="el-icon-connection"
                        style="font-size: 15px;cursor: pointer;color: #ffeb3b;" />
                    </el-popover>
                  </div>
                  <div v-if="!study.IsCriticalSequence" class="text-desc" :title="series.SeriesNumber">
                    #{{ series.SeriesNumber }}

                  </div>
                  <div v-if="series.Description" class="text-desc" :title="series.Description">
                    {{ series.Description }}

                  </div>
                  <div v-if="series.SliceThickness && !study.IsCriticalSequence" class="text-desc">
                    T: {{ parseFloat(series.SliceThickness).toFixed(digitPlaces) }}
                  </div>
                  <div class="text-desc">
                    <span v-show="series.LoadedImageCount < series.InstanceCount">
                      {{ series.Modality }}: {{ series.LoadedImageCount }}/{{ series.InstanceCount }} image
                    </span>
                    <span v-show="series.LoadedImageCount >= series.InstanceCount">{{ series.Modality }}: {{
                      series.InstanceCount
                    }} image</span>
                  </div>
                  <div style="line-height: 12px;">
                    <i v-show="series.IsBeSegment || series.IsBeMark || markedSeriesIds.includes(series.Id)"
                      class="el-icon-star-on" style="font-size: 12px;color: #ff5722;" />
                  </div>
                </div>
              </div>
              <div v-if="series.LoadedImageCount > 0 && series.LoadedImageCount < series.InstanceCount"
                style="width: 100%;">
                <el-progress :percentage="parseInt((series.LoadedImageProgress / series.InstanceCount).toFixed(2))" />
              </div>
            </div>
          </div>
        </el-collapse-item>


      </el-collapse>
    </div>
  </div>
</template>
<script>
import DicomEvent from '@/views/trials/trials-panel/reading/dicoms/components/DicomEvent'
export default {
  name: 'StudyList',
  props: {
    visitTaskInfo: {
      type: Object,
      default() {
        return {}
      }
    },
    markedSeriesIds: {
      type: Array,
      default() {
        return []
      }
    },
    readingTool: {
      type: Number,
      default: 2
    }
  },
  data() {
    return {
      loading: false,
      activeNames: [],
      activeStudyIndex: -1,
      activeSeriesIndex: -1,
      taskInfo: null,
      studyList: [],
      annotations: [],
      digitPlaces: 2,
      activeInstanceId: null
    }
  },
  mounted() {
    this.taskInfo = JSON.parse(sessionStorage.getItem('taskInfo'))
    const digitPlaces = Number(localStorage.getItem('digitPlaces'))
    this.digitPlaces = digitPlaces === -1 ? this.digitPlaces : digitPlaces
    this.studyList = this.visitTaskInfo.StudyList
    console.log(this.studyList)
    this.annotations = this.visitTaskInfo.Annotations
    if (this.studyList.length === 0) return
    this.$nextTick(() => {
      this.activeStudy(this.studyList[0].StudyId)
    })
    DicomEvent.$on('IsBeSegment', (obj) => {
      this.studyList.some(study => {
        if (study.StudyId === obj.StudyId) {
          study.SeriesList.some(series => {
            if (series.Id === obj.Id) {
              series.IsBeSegment = obj.IsBeSegment
            }
            return series.Id === obj.Id
          })
        }
        return study.StudyId === obj.StudyId
      })
    })
  },
  methods: {
    activeSeries(series, seriesIndex, studyIndex) {
      const photometricInterpretation = series?.InstanceInfoList[0]?.PhotometricInterpretation;
      if ((!photometricInterpretation || (photometricInterpretation !== 'MONOCHROME1' && photometricInterpretation !== 'MONOCHROME2')) && this.readingTool === 3)
        return this.$confirm(this.$t('trials:histogram:confirm:activeSeriesPhotometricInterpretationNotSupported'))
      this.$emit('activeSeries', series)
      this.activeStudyIndex = studyIndex
      this.activeSeriesIndex = seriesIndex
      this.activeInstanceId = null
    },
    activeStudy(id) {
      console.log('activeStudy')
      if (this.activeNames.indexOf(id) > -1) return
      this.activeNames.push(id)
    },
    setSeriesActive(studyIndex, seriesIndex, isSave = false) {
      this.activeStudyIndex = studyIndex
      this.activeSeriesIndex = seriesIndex
      const studyId = this.studyList[studyIndex].StudyId
      if (!studyId) return
      this.activeStudy(studyId)
      if (isSave) return false
      DicomEvent.$emit('activeSeries', this.studyList[studyIndex].SeriesList[this.activeSeriesIndex])
    },
    showMultiFrames(studyIndex, series, seriesIndex, instance) {
      let obj = Object.assign({}, series)
      this.activeStudyIndex = studyIndex
      this.activeSeriesIndex = seriesIndex
      this.activeInstanceId = instance.Id
      let taskId = this.visitTaskInfo.VisitTaskId
      const nFrames = instance.NumberOfFrames || 0
      let imageIds = []
      const stack = []
      if (nFrames === 0) {
        // 单帧
        stack.push(`wadouri:${this.OSSclientConfig.basePath}${instance.Path}?instanceId=${instance.Id}`)
      } else {
        // 多帧
        for (let i = 0; i < nFrames; i++) {
          const newImageId = `wadouri:${this.OSSclientConfig.basePath}${instance.Path}?instanceId=${instance.Id}&frame=${i + 1}`
          stack.push(newImageId)
        }
      }
      imageIds.push(`wadouri:${this.OSSclientConfig.basePath}${instance.Path}?instanceId=${instance.Id}`)
      obj.Stack = stack
      obj.ImageIds = imageIds
      obj.SliceIndex = 0
      this.$emit('showMultiFrame', obj)

    },
    getPreviousOrNextSeries(type, series) {
      const seriseList = this.studyList.map(s => s.SeriesList).flat()
      const i = seriseList.findIndex(i => i.Id === series.Id && i.StudyId === series.StudyId)
      if (i === -1) return
      let newIndex = null
      if (type === -1) {
        newIndex = i === 0 ? i : i - 1
      } else {
        newIndex = i >= seriseList.length - 1 ? i : i + 1
      }
      const studyIndex = seriseList[newIndex].StudyIndex
      const seriesIndex = seriseList[newIndex].SeriesIndex
      this.setSeriesActive(studyIndex, seriesIndex)
      this.activeSeries(seriseList[newIndex], seriesIndex, studyIndex)
    },
    showPatientInfo(study) {
      console.log(study)
    }
  }
}
</script>
<style lang="scss">
// .patient-info {
//   // display: inline-block;
//   // text-align: right;
// }

.patient-info-popper {
  font-size: 12px;
  color: #ddd;
  background-color: #2f2f2f;
  border-color: #5a5a5a;
  padding: 8px 10px;
}

.patient-info-popper[x-placement^='right'] .popper__arrow {
  border-right-color: #5a5a5a;
}

.patient-info-popper[x-placement^='right'] .popper__arrow::after {
  border-right-color: #2f2f2f;
}

.patient-info-popper .patient-info-row {
  display: grid;
  grid-template-columns: 100px minmax(0, 1fr);
  column-gap: 12px;
  align-items: center;
  line-height: 18px;
}

.patient-info-popper .patient-info-row+.patient-info-row {
  margin-top: 4px;
}

.patient-info-popper label {
  color: #bbb;
  // font-weight: 600;
  white-space: nowrap;
  // text-align: right;
}

.patient-info-popper span {
  text-align: left;
  min-width: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
<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: normal;
    overflow: visible;
  }

  .study-meta-line {
    // display: grid;
    // grid-template-columns: minmax(0, 1fr) auto;
    // align-items: start;
    // gap: 6px;
    vertical-align: middle;
    width: 100%;
    min-width: 0;
  }

  .study-meta-main {
    display: block;
    min-width: 0;
    white-space: normal;
    overflow-wrap: anywhere;
    flex: 1;
  }

  .study-code,
  .study-modality {
    white-space: normal;
    margin: 0 2px;
  }

  .patient-info {
    display: inline-flex;
    align-items: center;
    line-height: 1;
    flex: 0 0 auto;
  }

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

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

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

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

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

      .el-progress__text {
        display: none;
      }

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

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

      .series-text {
        flex: 1;
        padding-left: 5px;
        color: #ddd;
        position: relative;

        .text-desc {
          width: 100px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          font-size: 12px;
          line-height: 16px;
        }
      }

    }
  }

  ::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: 1px;
      min-height: 40px;
      height: auto;
      line-height: 20px;
      align-items: flex-start;
      padding-top: 6px;
      padding-bottom: 6px;
    }
  }

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

<style lang="scss">
.study-wrapper {
  .instance_frame_wrapper {
    min-width: 120px;
    background-color: #2c2c2c;
    border: 1px solid #2c2c2c;
    padding: 5px;
  }

  .frame_list {
    max-height: 500px;
    overflow-y: auto;
  }

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

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

  .frame_content {
    height: 50px;
    padding: 5px;
    display: flex;
    justify-content: flex-start;
    color: #ddd;
    font-size: 12px;
    border: 1px solid #404040;
  }

  .frame_content:hover {
    /* font-weight: bold; */
    /* box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); */
    cursor: pointer;
    /* color: #428bca; */
    border-color: #213a54 !important;
    background-color: #213a54;
  }

  .frame_content_active {
    border-color: #213a54 !important;
    background-color: #213a54;
  }
}
</style>
