<template>
  <div v-loading="loading" class="study-wrapper">
    <h4 v-if="isReadingShowSubjectInfo" style="color: #ddd;padding: 5px 0px;margin: 0;text-align: center;background-color: #4c4c4c;">
      {{ subjectCode }}
    </h4>
    <h4 v-if="isReadingShowSubjectInfo" style="color: #ddd;padding: 5px 0px;margin: 0;text-align: center;background-color: #4c4c4c;margin-bottom: 5px;">
      {{ taskBlindName }}
    </h4>
    <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">
              <!-- 关键序列 -->
              {{ $t('trials:reading:title:keySeries') }}
            </div>
            <div
              v-else
              class="dicom-desc"
              style="width: 150px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;"
            >
              <div>
                <div style="text-overflow: ellipsis;overflow: hidden;" v-if="!study.StudyName">
                  <span :title="study.StudyCode">{{ study.StudyCode }}</span>
                  <span>{{ study.Modalities }} ({{ study.SeriesCount }})</span>  
                </div>
                <div style="text-overflow: ellipsis;overflow: hidden;" v-else>
                  <span :title="study.StudyCode">{{ study.StudyCode }}</span>
                  <span v-if="taskInfo && taskInfo.IsShowStudyName" :title="study.StudyName">
                    {{study.StudyName}}
                  </span>
                  <div>{{ study.Modalities }} ({{ study.SeriesCount }})</div>
                </div>
                <div style="text-overflow: ellipsis;overflow: hidden;" :title="study.Description">{{ study.Description }}</div>
              </div>

            </div>
          </template>
          <div class="series">
            <div
              v-for="(series, i) in study.SeriesList"
              :key="i"
              style="position:relative;margin-top:5px;"
              series-type="current"
              @click="showSeriesImage(index,i,series)"
            >

              <div
                :class="{'series-active': i==seriesIndex && index === studyIndex}"
                class="series-wrapper"
              >
                <el-image
                  class="image-preview"
                  :src="series.previewImageUrl"
                  fit="fill"
                  crossorigin="anonymous"
                />
                <div class="image-desc">
                  <div class="flex-div">
                    <div style="width: 40px;display: flex;flex-direction: row;justify-content: space-between;">
                      <div v-if="!study.IsCriticalSequence">#{{ series.seriesNumber }}</div>
                      <div v-if="series.isDicom && series.prefetchInstanceCount<series.instanceCount * 100 && series.modality!== 'SR'">
                        <!-- 下载 -->
                        <el-tooltip v-if="!series.isLoading" class="item" effect="dark" :content="$t('trials:reading:button:download')" placement="bottom">
                          <i class="el-icon-video-play" style="font-size: 18px;margin-right: 5px;color: #ffeb3b;cursor: pointer;" @click.stop="loadSeries(series,index,i)" />
                        </el-tooltip>
                      </div>
                      <el-tooltip v-else-if="series.isDicom && series.prefetchInstanceCount === 0 &&series.modality!== 'SR'" class="item" effect="dark" :content="$t('trials:reading:button:download')" placement="bottom">
                        <i class="el-icon-video-play" style="font-size: 18px;margin-right: 5px;color: #ffeb3b;cursor: pointer;" @click.stop="loadSeries(series,index,i)" />
                      </el-tooltip>
                    </div>
                    <div v-if="series.isExistMutiFrames && series.instanceCount > 1">
                      <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>
                                          <img
                                            class="image-preview"
                                            :src="series.previewImageUrl"
                                            crossorigin="anonymous"
                                            alt=""
                                            style="width: 40px;height:40px;"
                                            fit="fill"
                                          >
                                        </div> -->
                            <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>
                  <p v-show="series.description">
                    <el-tooltip class="item" effect="dark" :content="series.description" placement="right">
                      <div style="">{{ series.description }}</div>
                    </el-tooltip>
                  </p>

                  <p v-show="series.sliceThickness && !study.IsCriticalSequence">
                    T: {{ parseFloat(series.sliceThickness).toFixed(digitPlaces) }}
                  </p>
                  <p v-show="series.instanceCount && series.imageloadedArr.length < series.instanceCount">
                    {{ series.modality }}: {{ series.imageloadedArr.length }}/{{ series.instanceCount }} image
                  </p>
                  <p v-show="series.instanceCount && series.imageloadedArr.length >= series.instanceCount">
                    {{ series.modality }}: {{ series.instanceCount }} image
                  </p>
                  <div class="flex-div">
                    <div v-if="measureData && measureData.findIndex(v=>v.SeriesId === series.seriesId && v.MeasureData) > -1">
                      <!-- 有标注 -->
                      <el-tooltip class="item" effect="dark" :content="$t('trials:reading:button:marked')" placement="right">
                        <i class="el-icon-star-on" style="font-size: 16px;color: #ff5722;" />
                      </el-tooltip>

                    </div>
                  </div>
                </div>
              </div>
              <div v-if="series.isDicom && series.prefetchInstanceCount>0 && series.prefetchInstanceCount<series.instanceCount * 100" style="width: 100%;">
                <el-progress
                  :percentage="parseInt((series.prefetchInstanceCount / series.instanceCount).toFixed(2))"
                />
              </div>

            </div>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>

    <div class="sr-wrapper">
      <el-dialog
        :visible.sync="srDialogVisible"
        :custom-class="isSrFullscreen?'sr-full-dialog-container':'sr-dialog-container'"
        :show-close="false"
        :close-on-click-modal="false"
        :fullscreen="isSrFullscreen"
      >
        <span slot="title" class="dialog-footer">
          <div style="position: absolute;right: 20px;top: 10px;">
            <svg-icon :icon-class="isSrFullscreen?'exit-fullscreen':'fullscreen'" style="cursor: pointer;font-size: 20px;color:#000;" @click="isSrFullscreen=!isSrFullscreen" />
            <svg-icon icon-class="dClose" style="cursor: pointer;font-size: 25px;margin-left: 10px;" @click="srDialogVisible = false" />
          </div>
        </span>
        <div style="height: 100%;margin:0;">
          <SrList
            v-if="srDialogVisible"
            :sr-info="srInfo"
          />
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import requestPoolManager from '@/utils/request-pool'
import DicomEvent from './../components/DicomEvent'
import { mapGetters } from 'vuex'
import store from '@/store'
import SrList from './../components/SrList'
export default {
  name: 'StudyList',
  components: { SrList },
  props: {
    trialId: {
      type: String,
      required: true
    },
    subjectVisitId: {
      type: String,
      required: true
    },
    visitTaskId: {
      type: String,
      required: true
    },
    isReading: {
      type: Number,
      default: 0
    },
    taskBlindName: {
      type: String,
      default: ''
    },
    isReadingShowSubjectInfo: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      studyList: [],
      cachedImages: [],
      showSeriesList: [],
      studyIndex: null,
      seriesIndex: null,
      loading: false,
      measureData: [],
      isRender: false,
      subjectCode: '',
      activeNames: [],
      seriesArr: [],
      imageList: [],
      loopLoadStatus: 0, // -1暂停下载 0未下载完成  1下载完成
      isSrFullscreen: false,
      srDialogVisible: false,
      srInfo: {},
      digitPlaces: 2,
      visitTaskIdx: -1,
      taskInfo: null,
      activeInstanceId: null
    }
  },

  computed: {
    ...mapGetters(['visitTaskList', 'currentTaskId', 'activeSeries'])
  },
  watch: {
    visitTaskList: {
      immediate: true,
      handler(val) {
        var idx = this.visitTaskList.findIndex(i => i.VisitTaskId === this.visitTaskId)
        if (idx === -1) return
        this.measureData = this.visitTaskList[idx].MeasureData
      }
    },
    visitTaskId: {
      immediate: true,
      handler(val) {
        var idx = this.visitTaskList.findIndex(i => i.VisitTaskId === this.visitTaskId)
        if (idx === -1) return
        this.visitTaskIdx = idx
      }
    }
    // activeSeries: {
    //   immediate: true,
    //   handler(val) {
    //     console.log('activeSeries', val)
    //     this.studyIndex = val.studyIndex
    //     this.seriesIndex = val.seriesIndex
    //   }
    // }
  },
  mounted() {
    // this.subjectCode = this.$router.currentRoute.query.subjectCode
    this.subjectCode = localStorage.getItem('subjectCode')
    var digitPlaces = Number(localStorage.getItem('digitPlaces'))
    this.digitPlaces = digitPlaces === -1 ? this.digitPlaces : digitPlaces
    this.taskInfo = JSON.parse(localStorage.getItem('taskInfo'))
    DicomEvent.$on('refreshStudyListMeasureData', () => {
      var idx = this.visitTaskList.findIndex(i => i.VisitTaskId === this.visitTaskId)
      this.measureData = this.visitTaskList[idx].MeasureData
    })
    // DicomEvent.$on('setReadingState', readingTaskState => {
    //   var idx = this.visitTaskList.findIndex(i => i.VisitTaskId === this.visitTaskId)
    //   if (idx > -1) {
    //     this.studyList = this.visitTaskList[idx].StudyList
    //   }
    // })

  },
  beforeDestroy() {
  },
  methods: {
    initStudyInfo() {
      const loading = this.$loading({ fullscreen: true })
      // 初始化待渲染序列
      this.getInitSeries().then((res) => {
        requestPoolManager.startTaskTimer()
        res.map(async(item) => {
          let imageId = item.imageIds[item.imageIdIndex]
          const p = parseInt(new Date().getTime())
          // requestPoolManager.loadAndCacheImagePlus(imageId, item.seriesId, p * 100)
          await requestPoolManager.loadAndCacheImagePlus(imageId, item.seriesId, p * 100)
          if (!item.isCurrentTask) {
            store.dispatch('reading/setImageloadedInfo', item)
          }
        })
        var i = -1
        var isReadingTaskViewInOrder = parseInt(this.$router.currentRoute.query.isReadingTaskViewInOrder)
        if (isReadingTaskViewInOrder === 2) {
          // 受试者内随机
          i = res.length === 2 ? 1 : -1
        } else {
          i = res.findIndex(s => s.isCurrentTask)
        }
        if (i > -1) {
          var idx = this.visitTaskList.findIndex(i => i.VisitTaskId === this.visitTaskId)
          if (idx > -1) {
            this.measureData = this.visitTaskList[idx].MeasureData
            this.studyList = this.visitTaskList[idx].StudyList
            var priority = parseInt(new Date().getTime())
            if (res[i].isExistMutiFrames) {
              res[i].instanceInfoList.map(image => {
                priority--
                this.imageList.push({ imageId: image.ImageId, seriesId: res[i].seriesId, studyIndex: res[i].studyIndex, seriesIndex: res[i].seriesIndex, visitTaskId: res[i].visitTaskId, priority })
              })
            } else {
              res[i].imageIds.map(image => {
                priority--
                this.imageList.push({ imageId: image, seriesId: res[i].seriesId, studyIndex: res[i].studyIndex, seriesIndex: res[i].seriesIndex, visitTaskId: res[i].visitTaskId, priority })
              })
            }
            this.loopLoad()
          }
        }
        DicomEvent.$emit('loadImageStacks', res)
        loading.close()
        this.isRender = true
      }).catch(() => {
        loading.close()
      })
    },
    // 获取初始化序列信息
    loadInitialImage(seriesInfo) {
      var p = parseInt(new Date().getTime())
      var imageId = seriesInfo.imageIds[seriesInfo.imageIdIndex]
      requestPoolManager.loadAndCacheImagePlus(imageId, seriesInfo.seriesId, p * 100)
    },
    getStudyList() {
      if (!this.isRender) {
        var idx = this.visitTaskList.findIndex(i => i.VisitTaskId === this.visitTaskId)
        if (idx > -1 && this.visitTaskList[idx].StudyList && this.visitTaskList[idx].StudyList.length > 0) {
          this.measureData = this.visitTaskList[idx].MeasureData
          this.studyList = this.visitTaskList[idx].StudyList
          var sIdx = this.studyList.findIndex(s => s.IsDicom)
          if (sIdx > -1) {
            this.studyIndex = sIdx
            this.seriesIndex = 0
            this.activeNames = [`${this.studyList[sIdx].StudyId}`]
            // 下载关键序列
            const i = this.studyList.findIndex(i => i.IsCriticalSequence)
            if (i > -1 && this.studyList[i].SeriesList[0].length > 0) {
              const series = this.studyList[i].SeriesList[0]
              if (!series.loadStatus) {
                let priority = parseInt(new Date().getTime())
                if (series.isExistMutiFrames) {
                  series.instanceInfoList.map(image => {
                    priority = priority - 1
                    this.imageList.push({ imageId: image.ImageId, seriesId: series.seriesId, studyIndex: i, seriesIndex: 0, visitTaskId: series.visitTaskId, priority })
                  })
                } else {
                  series.imageIds.map(imageId => {
                    priority = priority - 1
                    this.imageList.push({ imageId: imageId, seriesId: series.seriesId, studyIndex: i, seriesIndex: 0, visitTaskId: series.visitTaskId, priority })
                  })
                }
              }
            }
            this.loopLoad()
            // this.loadImages(this.visitTaskList[idx])
          }
        }
        this.isRender = true
      }
    },

    async getInitSeries() {
      var seriesList = []
      var isReadingTaskViewInOrder = JSON.parse(this.$router.currentRoute.query.isReadingTaskViewInOrder)
      var idx = this.visitTaskList.findIndex(i => i.VisitTaskId === this.visitTaskId)
      this.studyList = this.visitTaskList[idx].StudyList
      if (isReadingTaskViewInOrder === 2) {
        // 受试者内随机
        const studyList = this.visitTaskList[idx].StudyList.filter(i => i.IsDicom)
        const seriesArr = studyList.map(s => s.SeriesList).flat()
        if (seriesArr.length === 1) {
          seriesList.push(seriesArr[0], seriesArr[0])
          this.studyIndex = seriesArr[0].studyIndex
          this.seriesIndex = seriesArr[0].seriesIndex
          this.activeNames = [`${seriesArr[0].studyId}`]
        } else if (seriesArr.length > 1) {
          seriesList.push(seriesArr[0], seriesArr[1])
          this.studyIndex = seriesArr[1].studyIndex
          this.seriesIndex = seriesArr[1].seriesIndex
          this.activeNames = [`${seriesArr[1].studyId}`]
        }
      } else if (this.visitTaskList[idx].IsBaseLineTask || isReadingTaskViewInOrder === 0){
        // 基线
        const obj = this.getFirstMarkedSeries(this.visitTaskList[idx].MeasureData, [...this.visitTaskList[idx].StudyList])
        if (Object.keys(obj).length !== 0) {
          this.studyIndex = obj.studyIndex
          this.seriesIndex = obj.seriesIndex
          seriesList.push(obj.series)
          this.activeNames = [`${this.studyList[ this.studyIndex].StudyId}`]
          this.studyList[ obj.studyIndex].SeriesList[obj.seriesIndex].isFirstRender = true
        } else {
          // 初始化问题表单
          if (this.studyList.length > 0) {
            this.activeNames = [`${this.studyList[0].StudyId}`]
          }

          // DicomEvent.$emit('loadMeasurementList', { visitTaskId: this.visitTaskList[idx].VisitTaskId, taskBlindName: this.visitTaskList[idx].TaskBlindName })
        }
      } else {
        // 随访
        var bsIdx = null
        var criterionType = parseInt(localStorage.getItem('CriterionType'))
        if (criterionType === 10) {
          const i = this.visitTaskList.findIndex(i => i.IsCurrentTask)

          bsIdx = i - 1
        } else {
          bsIdx = this.visitTaskList.findIndex(i => i.IsBaseLineTask)
        }

        if (bsIdx > -1) {
          var trialId = this.$router.currentRoute.query.trialId
          await store.dispatch('reading/getCustomizeMeasuredData', this.visitTaskList[bsIdx].VisitTaskId)
          await store.dispatch('reading/getStudyInfo', { trialId: trialId, subjectVisitId: this.visitTaskList[bsIdx].VisitId, visitTaskId: this.visitTaskList[bsIdx].VisitTaskId, taskBlindName: this.visitTaskList[bsIdx].TaskBlindName })

          const firstObj = this.getFirstMarkedSeries(this.visitTaskList[bsIdx].MeasureData, [...this.visitTaskList[bsIdx].StudyList])
          seriesList.push(firstObj.series)
          const secondObj = this.getSecondMarkedSeries(firstObj, { ...this.visitTaskList[idx] })
          this.studyIndex = secondObj.studyIndex
          this.seriesIndex = secondObj.seriesIndex
          seriesList.push(secondObj.series)
          this.studyList[ secondObj.studyIndex].SeriesList[secondObj.seriesIndex].isFirstRender = true
          this.studyIndex = secondObj.studyIndex
          this.seriesIndex = secondObj.seriesIndex

          this.activeNames = [`${this.studyList[secondObj.studyIndex].StudyId}`]
        } else {
          const sIdx = this.studyList.findIndex(s => s.IsDicom)
          const series = this.studyList[sIdx].SeriesList[0]
          const imageIdIndex = Math.floor(series.imageIds.length / 2)
          series.imageIdIndex = imageIdIndex > 0 ? imageIdIndex - 1 : 0
          seriesList.push(series)
          this.studyIndex = sIdx
          this.seriesIndex = 0

          this.activeNames = [`${this.studyList[sIdx].StudyId}`]
        }
      }

      return seriesList
    },
    getSecondMarkedSeries(baseObj, visitTaskInfo) {
      var obj = {}
      var studyList = visitTaskInfo.StudyList
      var measureDatas = visitTaskInfo.MeasureData
      if (baseObj.isMarked) {
        var i = measureDatas.findIndex(i => Object.keys(i.MeasureData).length > 0 && i.OrderMarkName === baseObj.measureData.OrderMarkName)
        if (i !== -1) {
          const sdIndx = studyList.findIndex(sd => sd.StudyId === measureDatas[i].StudyId)
          const seriesList = studyList[sdIndx].SeriesList
          const srIdx = seriesList.findIndex(sr => sr.seriesId === measureDatas[i].SeriesId)
          // const instanceList = seriesList[srIdx].instanceList
          // const isIdx = instanceList.findIndex(is => is.includes(measureDatas[i].InstanceId))
          const imageIds = seriesList[srIdx].imageIds
          // let filterStr = seriesList[srIdx].isExistMutiFrames ? `frame=${measureDatas[i].MeasureData.frame}&instanceId=${measureDatas[i].InstanceId}` : `instanceId=${measureDatas[i].InstanceId}`
          let instanceIndex = seriesList[srIdx].instanceInfoList.findIndex(k=>k.Id === measureDatas[i].InstanceId)
          let filterStr = ''
          if (instanceIndex > -1 && seriesList[srIdx].isExistMutiFrames) {
            if (seriesList[srIdx].instanceInfoList[instanceIndex].NumberOfFrames > 0) {
              filterStr = `frame=${measureDatas[i].MeasureData.frame}&instanceId=${measureDatas[i].InstanceId}`
            } else {
              filterStr = `instanceId=${measureDatas[i].InstanceId}`
            }
          } else {
            filterStr = `instanceId=${measureDatas[i].InstanceId}`
          }
          const isIdx = imageIds.findIndex(is => is.includes(filterStr))
          const series = seriesList[srIdx]
          series.imageIdIndex = isIdx

          obj.studyIndex = sdIndx
          obj.seriesIndex = srIdx
          obj.series = series
          obj.seriesId = series.seriesId
          return obj
        }
      }
      var seriesInfo = null
      var seriesList = studyList.map(s => s.SeriesList).flat()
      var similarArr = seriesList.map((i, index) => {
        return { similar: this.strSimilarity2Percent(i.description, baseObj.series.description), index }
      })
      similarArr = similarArr.sort((a, b) => {
        return b.similar - a.similar
      })
      var idx = similarArr[0] && similarArr[0].similar > 0.85 ? similarArr[0].index : -1
      if (idx > -1) {
        seriesInfo = seriesList[idx]
      }

      // const idx = seriesList.findIndex(series => series.description === baseSeries.description)
      // idx > -1 ? obj = seriesList[idx] : ''
      if (!seriesInfo) {
        // 描述不一致,则筛选层厚一致
        const idx = seriesList.findIndex(series => series.sliceThickness === baseObj.series.sliceThickness)
        idx > -1 ? seriesInfo = seriesList[idx] : ''
      }
      if (!seriesInfo) {
        // 层厚不一致,则筛选图像数量一致
        const idx = seriesList.findIndex(series => series.instanceCount === baseObj.series.instanceCount)
        idx > -1 ? seriesInfo = seriesList[idx] : ''
      }
      if (!seriesInfo) {
        // 都不符合要求， 判断是否存在层厚为5的序列，否则显示第一个检查的第一个序列
        const idx = seriesList.findIndex(series => series.isDicom && parseInt(series.sliceThickness) === 5)
        idx > -1 ? seriesInfo = seriesList[idx] : seriesInfo = seriesList[0]
      }
      if (seriesInfo) {
        const index = Math.floor(seriesInfo.imageIds.length * ((baseObj.series.imageIdIndex + 1) / baseObj.series.imageIds.length))
        seriesInfo.imageIdIndex = index > 0 ? index - 1 : 0
        obj.studyIndex = seriesInfo.studyIndex
        obj.seriesIndex = seriesInfo.seriesIndex
        obj.series = seriesInfo
        obj.seriesId = seriesInfo.seriesId
      }
      return obj
    },
    findSerialNumberClosest(arr, n) {
      var absArr = []
      for (let i = 0; i < arr.length; i++) {
        const m = n - arr[i].seriesNumber
        absArr.push({ index: i, n: Math.abs(m) })
      }
      const num = Math.min.apply(null, absArr.map(item => item.n))
      var mIdx = absArr.findIndex(item => item.n === num)
      return mIdx
    },
    getFirstMarkedSeries(measureDatas, studyList) {
      var obj = {}
      var mIdx = measureDatas.findIndex(m => Object.keys(m.MeasureData).length > 0)
      if (mIdx !== -1) {
        // 有标记时，显示带标记影像所在序列
        const sdIndx = studyList.findIndex(sd => sd.StudyId === measureDatas[mIdx].StudyId && sd.IsDicom)
        if (sdIndx > -1) {
          const seriesList = studyList[sdIndx].SeriesList
          const srIdx = seriesList.findIndex(sr => sr.seriesId === measureDatas[mIdx].SeriesId)
          // const instanceList = seriesList[srIdx].instanceList
          // const isIdx = instanceList.findIndex(is => is.includes(measureDatas[mIdx].InstanceId)) 
          const imageIds = seriesList[srIdx].imageIds
          let instanceIndex = seriesList[srIdx].instanceInfoList.findIndex(i=>i.Id === measureDatas[mIdx].InstanceId)
          let filterStr = ''
          if (instanceIndex > -1 && seriesList[srIdx].isExistMutiFrames) {
            if (seriesList[srIdx].instanceInfoList[instanceIndex].NumberOfFrames > 0) {
              filterStr = `frame=${measureDatas[mIdx].MeasureData.frame}&instanceId=${measureDatas[mIdx].InstanceId}`
            } else {
              filterStr = `instanceId=${measureDatas[mIdx].InstanceId}`
            }
          } else {
            filterStr = `instanceId=${measureDatas[mIdx].InstanceId}`
          }
          // let filterStr = seriesList[srIdx].isExistMutiFrames ? `frame=${measureDatas[mIdx].MeasureData.frame}&instanceId=${measureDatas[mIdx].InstanceId}` : `instanceId=${measureDatas[mIdx].InstanceId}`
          const isIdx = imageIds.findIndex(is => is.includes(filterStr))
          const series = seriesList[srIdx]
          series.imageIdIndex = isIdx

          obj.studyIndex = sdIndx
          obj.seriesIndex = srIdx
          obj.series = series
          obj.seriesId = series.seriesId
          obj.isMarked = true
          obj.measureData = measureDatas[mIdx]
        }
      } else {
        var seriesObj = null
        for (let i = 0; i < studyList.length; i++) {
          const seriesIdx = studyList[i].SeriesList.findIndex(s => s.sliceThickness && parseInt(s.sliceThickness) === 5)
          if (seriesIdx > -1) {
            seriesObj = { studyIndex: i, seriesIdx, series: studyList[i].SeriesList[seriesIdx] }
            break
          }
        }
        if (seriesObj) {
          obj.studyIndex = seriesObj.studyIndex
          obj.seriesIndex = seriesObj.seriesIdx
          const imageIdIndex = Math.floor(seriesObj.series.imageIds.length / 2)

          seriesObj.series.imageIdIndex = imageIdIndex > 0 ? imageIdIndex - 1 : 0
          obj.series = seriesObj.series
          obj.seriesId = seriesObj.series.seriesId
          obj.isMarked = false
        }
      }
      if (Object.keys(obj).length === 0) {
        const sIdx = studyList.findIndex(s => s.IsDicom)
        if (sIdx > -1) {
          obj.studyIndex = sIdx
          obj.seriesIndex = 0
          obj.series = studyList[obj.studyIndex].SeriesList[obj.seriesIndex]
          const imageIdIndex = Math.floor(obj.series.imageIds.length / 2)
          obj.series.imageIdIndex = imageIdIndex >= 0 ? imageIdIndex : 0
          // obj.seriesId = series.seriesId
          obj.isMarked = false
        }
      }

      return obj
    },
    strSimilarity2Number(s, t) {
      var n = s.length; var m = t.length; var d = []
      var i, j, s_i, t_j, cost
      if (n === 0) return m
      if (m === 0) return n
      for (i = 0; i <= n; i++) {
        d[i] = []
        d[i][0] = i
      }
      for (j = 0; j <= m; j++) {
        d[0][j] = j
      }
      for (i = 1; i <= n; i++) {
        s_i = s.charAt(i - 1)
        for (j = 1; j <= m; j++) {
          t_j = t.charAt(j - 1)
          if (s_i === t_j) {
            cost = 0
          } else {
            cost = 1
          }
          d[i][j] = this.Minimum(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost)
        }
      }
      return d[n][m]
    },
    // 两个字符串的相似程度，并返回相似度百分比
    strSimilarity2Percent(s, t) {
      var l = s.length > t.length ? s.length : t.length
      var d = this.strSimilarity2Number(s, t)
      return Number((1 - d / l).toFixed(4))
    },
    Minimum(a, b, c) {
      return a < b ? (a < c ? a : c) : (b < c ? b : c)
    },
    showSeriesImage(studyIndex, seriesIndex, series) {
      if (series.isDicom) {
        this.activeInstanceId = null
        if (series.modality === 'SR') {
          this.studyIndex = studyIndex
          this.seriesIndex = seriesIndex
          this.studyList[studyIndex].SeriesList[seriesIndex].measureData = this.measureData
          this.srDialogVisible = true
          this.srInfo = {
            SubjectCode: series.studyCode,
            TaskBlindName: series.taskBlindName,
            SrList: series.instanceHtmlPathList
          }
        } else {
          this.studyIndex = studyIndex
          this.seriesIndex = seriesIndex
          this.studyList[studyIndex].SeriesList[seriesIndex].measureData = this.measureData
          var dicomStatck = Object.assign({},this.studyList[studyIndex].SeriesList[seriesIndex])

          dicomStatck.imageIdIndex = 0
          this.$emit('loadImageStack', dicomStatck)
          if (!series.loadStatus && series.modality !== 'SR') {
            this.loopLoadStatus = -1
            series.isLoading = true
            var isAddToTakPool = false
            if (this.showSeriesList.includes(`${studyIndex}_${seriesIndex}`)) {
              isAddToTakPool = true
            } else {
              this.showSeriesList.push(`${studyIndex}_${seriesIndex}`)
            }
            if (!isAddToTakPool) {
              var priority = parseInt(new Date().getTime())
              if (series.isExistMutiFrames) {
                series.instanceInfoList.map(image => {
                  this.imageList.push({ imageId: image.ImageId, seriesId: series.seriesId, studyIndex: studyIndex, seriesIndex: seriesIndex, visitTaskId: series.visitTaskId, priority })
                })
              } else {
                series.imageIds.map(imageId => {
                  this.imageList.push({ imageId: imageId, seriesId: series.seriesId, studyIndex: studyIndex, seriesIndex: seriesIndex, visitTaskId: series.visitTaskId, priority })
                })
              }
              if (this.imageList.length > 0) {
                this.loopLoadStatus = 0
                this.loopLoad()
              }
            } else {
              requestPoolManager.changePriority(series.seriesId)
            }
          }

          DicomEvent.$emit('loadMeasurementList', { visitTaskId: this.visitTaskId, taskBlindName: this.taskBlindName })
        }
      } else {
        // 非Dicom预览
        this.$emit('previewNoneDicoms', { visitTaskId: this.visitTaskId })
      }

      store.dispatch('reading/setActiveSeries', series)
    },
    showMultiFrames(studyIndex, series, seriesIndex, instanceInfo) {
      this.currentSeriesIndex = seriesIndex
      this.activeInstanceId = instanceInfo.Id
      var idx = this.visitTaskIdx
      this.studyIndex = studyIndex
      this.seriesIndex = seriesIndex
      this.studyList[studyIndex].SeriesList[seriesIndex].measureData = this.measureData
      var dicomStatck = Object.assign({},this.studyList[studyIndex].SeriesList[seriesIndex])
      const imageIds = []
      if (instanceInfo.KeyFramesList.length > 0) {
        instanceInfo.KeyFramesList.map(i => {
          imageIds.push(`wadouri:${localStorage.getItem('location') !== 'USA' ? this.OSSclientConfig.basePath : this.OSSclientConfig.basePath}${instanceInfo.Path}?frame=${i}&instanceId=${instanceInfo.Id}&visitTaskId=${this.visitTaskId}&idx=${studyIndex}|${seriesIndex}|${idx}`)
        })
      } else if (instanceInfo.NumberOfFrames && instanceInfo.NumberOfFrames > 1) {
        for (let j = 0; j < instanceInfo.NumberOfFrames; j++) {
          imageIds.push(`wadouri:${localStorage.getItem('location') !== 'USA' ? this.OSSclientConfig.basePath : this.OSSclientConfig.basePath}${instanceInfo.Path}?frame=${j}&instanceId=${instanceInfo.Id}&visitTaskId=${this.visitTaskId}&idx=${studyIndex}|${seriesIndex}|${idx}`)
        }
      } else {
        imageIds.push(`wadouri:${localStorage.getItem('location') !== 'USA' ? this.OSSclientConfig.basePath : this.OSSclientConfig.basePath}${instanceInfo.Path}?instanceId=${instanceInfo.Id}&visitTaskId=${this.visitTaskId}&idx=${studyIndex}|${seriesIndex}|${idx}`)
      }
      dicomStatck.imageIds = imageIds
      dicomStatck.imageIdIndex = 0
      this.$emit('loadImageStack', dicomStatck)
      this.loopLoadStatus = -1
      series.isLoading = true
      var isAddToTakPool = false
      if (this.showSeriesList.includes(`${studyIndex}_${seriesIndex}`)) {
        isAddToTakPool = true
      } else {
        this.showSeriesList.push(`${studyIndex}_${seriesIndex}`)
      }
      if (!isAddToTakPool) {
        var priority = parseInt(new Date().getTime())
        if (series.isExistMutiFrames) {
          series.instanceInfoList.map(image => {
            this.imageList.push({ imageId: image.ImageId, seriesId: series.seriesId, studyIndex: studyIndex, seriesIndex: seriesIndex, visitTaskId: series.visitTaskId, priority })
          })
        } else {
          series.imageIds.map((imageId) => {
            this.imageList.push({ imageId: imageId, seriesId: series.seriesId, studyIndex: studyIndex, seriesIndex: seriesIndex, visitTaskId: series.visitTaskId, priority })
          })
        }

        if (this.imageList.length > 0) {
          this.loopLoadStatus = 0
          this.loopLoad()
        }
      } else {
        requestPoolManager.changePriority(series.seriesId)
      }

      DicomEvent.$emit('loadMeasurementList', { visitTaskId: this.visitTaskId, taskBlindName: this.taskBlindName })
    },
    setSeriesActive(obj) {
      var idx = this.visitTaskList.findIndex(i => i.VisitTaskId === this.visitTaskId)
      if (idx === -1) return
      this.studyList = this.visitTaskList[idx].StudyList
      this.studyIndex = obj.studyIndex
      this.seriesIndex = obj.seriesIndex
      var activeNames = `${this.studyList[obj.studyIndex].StudyId}`
      if (this.activeNames.includes(activeNames)) return
      this.activeNames.push(activeNames)
      // this.loadImages(this.visitTaskList[idx])
      this.loadImages(obj)
    },
    selectSeries(obj) {
      var seriseList = this.studyList.map(s => s.SeriesList).flat()
      var i = seriseList.findIndex(i => i.seriesId === obj.seriesId && i.studyId === obj.studyId)
      if (i === -1) return
      var idx = i + obj.offset
      if (idx < 0) {
        idx = 0
      } else if (idx >= seriseList.length) {
        idx = seriseList.length - 1
      }
      if (seriseList[idx].seriesIndex === this.seriesIndex && seriseList[idx].studyIndex === this.studyIndex) return
      this.showSeriesImage(seriseList[idx].studyIndex, seriseList[idx].seriesIndex, seriseList[idx])
      this.handleActiveSeries(seriseList[idx])
    },
    handleActiveSeries(series) {
      this.studyIndex = series.studyIndex
      this.seriesIndex = series.seriesIndex
      var idx = this.visitTaskList.findIndex(i => i.VisitTaskId === series.visitTaskId)
      if (idx === -1) return
      this.studyList = this.visitTaskList[idx].StudyList
      var activeNames = `${this.studyList[series.studyIndex].StudyId}`
      if (this.activeNames.includes(activeNames)) return
      this.activeNames.push(activeNames)
      this.loadImages(series)
      // this.loadImages(this.visitTaskList[idx])
      store.dispatch('reading/setActiveSeries', series)
    },
    loadImages(series) {
      var priority = parseInt(new Date().getTime())
      if (!series.loadStatus && series.isDicom && series.modality !== 'SR') {
        if (series.isExistMutiFrames) {
          series.instanceInfoList.map(image => {
            priority = priority - 1
            this.imageList.push({ imageId: image.ImageId, seriesId: series.seriesId, studyIndex: series.studyIndex, seriesIndex: series.seriesIndex, visitTaskId: series.visitTaskId, priority })
          })
        } else {
          series.imageIds.map(imageId => {
            priority = priority - 1
            this.imageList.push({ imageId: imageId, seriesId: series.seriesId, studyIndex: series.studyIndex, seriesIndex: series.seriesIndex, visitTaskId: series.visitTaskId, priority })
          })
        }
      }
      this.loopLoad()
    },

    loopLoad() {
      if (this.imageList.length > 0) {
        // requestPoolManager.startTaskTimer()
        this.imageList.map(image => {
          requestPoolManager.loadAndCacheImagePlus(image.imageId, image.seriesId, image.priority)
        })
        requestPoolManager.sortTaskPool()

        this.imageList = []
      }
    },
    // 启动下载序列
    loadSeries(series, studyIndex, seriesIndex) {
      console.log('loadSeries')
      this.loopLoadStatus = -1
      this.$set(this.studyList[studyIndex].SeriesList[seriesIndex], 'isLoading', true)
      var isAddToTakPool = false
      if (this.showSeriesList.includes(`${studyIndex}_${seriesIndex}`)) {
        isAddToTakPool = true
      } else {
        this.showSeriesList.push(`${studyIndex}_${seriesIndex}`)
      }
      if (!isAddToTakPool) {
        const priority = parseInt(new Date().getTime())
        if (series.isExistMutiFrames) {
          series.instanceInfoList.map(image => {
            const index = this.cachedImages.findIndex(item => item.uri === image)
            if (index === -1) {
              this.imageList.push({ imageId: image.ImageId, seriesId: series.seriesId, studyIndex: studyIndex, seriesIndex: seriesIndex, visitTaskId: series.visitTaskId, priority })
            }
          })
        } else {
          series.imageIds.map(image => {
            const index = this.cachedImages.findIndex(item => item.uri === image)
            if (index === -1) {
              this.imageList.push({ imageId: image, seriesId: series.seriesId, studyIndex: studyIndex, seriesIndex: seriesIndex, visitTaskId: series.visitTaskId, priority })
            }
          })
        }
        if (this.imageList.length > 0) {
          this.loopLoadStatus = 0
          this.loopLoad()
        }
      } else {
        requestPoolManager.changePriority(series.seriesId)
      }
    },
    // 暂停下载
    stopLoadSeries(series, studyIndex, seriesIndex) {
      console.log('stopLoadSeries')
      requestPoolManager.removeTask(series.seriesId)
      this.$set(this.studyList[studyIndex].SeriesList[seriesIndex], 'isLoading', false)
    },
  }
}
</script>
<style lang="scss" scoped>
.study-wrapper{
  ::v-deep .el-progress-bar__inner{
    transition: width 0s ease;
  }
  width:100%;
  height: 100%;
  overflow-y: auto;
  overflow-x: hidden;
  .dicom-desc{
    font-weight: bold;
    font-size: 13px;
    text-align: left;
    color: #d0d0d0;
    padding: 2px;
  }

  .ps {
    overflow-anchor: none;
    touch-action: auto;
  }
  .series-active {
    background-color: #607d8b!important;
    border: 1px solid #607d8b!important;
  }
  ::v-deep .el-progress__text{
    color: #ccc;
    font-size: 12px;
  }
  .series{
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    .series-wrapper {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      height: 95px;
      // padding: 1px 2px 1px 8px;
      // margin: 10px 0px;
      border-radius: 2px;
      border: 1px solid #404040;
      background-color: #3a3a3a;
      .el-progress__text{
        display: none;
      }
      .el-progress-bar{
        padding-right:0px;
      }

      .image-preview {
        height: 60px;
        width: 60px;
        border: 2px solid #252525;
        cursor: pointer;
      }
      .image-desc {
        vertical-align: top;
        p{
          width: 95px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          font-size: 12px;
          color: #ddd;
          margin: 0px;
          line-height: 1.5;
          div{
            width: 95px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
      }
      .flex-div{
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        padding: 1px;
        width: 100px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        font-size: 12px;
        color: #ddd;
        padding: 1px;
        margin: 0px;
      }
    }
  }
  ::v-deep .el-collapse{
    border: none;
    .el-collapse-item{
      background-color: #000!important;
      color: #ddd;

    }
    .el-collapse-item__content{
      padding-bottom:5px;
      background-color: #000!important;
    }
    .el-collapse-item__header{
      background-color: #000!important;
      color: #ddd;
      border-bottom-color:#5a5a5a;
      padding-left: 5px;
      height: 40px;
      line-height: 20px;
    }
  }
  .sr-wrapper{
    ::v-deep .el-dialog{
      background: #fff !important;
      border: 1px solid #ddd;
      // color: #ddd;
      .el-dialog__title{
        color:#fff;
      }
    }
    ::v-deep .sr-dialog-container{
      margin-top: 50px !important;
      width:75%;
      height:80%;
    }
    ::v-deep .el-dialog__body{
        padding: 10px;
        height: calc(100% - 50px);
    }
    .el-dialog__header{
      position: relative;
    }
    .sr-full-dialog-container{
      ::v-deep .is-fullscreen .el-dialog__body{
        height: calc(100% - 50px);
      }
    }
  }
}

</style>
<style>
.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>
