/* eslint-disable vue/this-in-template */
<template>
  <div v-loading="loading" class="viewerContainer">
    <!-- <div class="viewerBanner" /> -->
    <div class="viewerContentWrapper">
      <div class="viewerLeftSidePanel">
        <div id="listWrapper" class="sidePanelBody">
          <div class="sidePanelThumbs">
            <el-tabs v-model="activeName" type="border-card">
              <el-tab-pane :label="$t('trials:dicom-show:nowStudy')" name="first">
                <div class="studyDesc">
                  {{ studyCode }}
                </div>
                <div class="studyDesc">
                  {{ description }}
                </div>
                <div v-if="seriesCount" class="studyDesc">
                  {{ modality }} : {{ seriesCount }} Series
                </div>
                <div class="viewerSidethumbs ps" style="position: relative;">
                  <div class="viewerSidethumbinner">
                    <div
                      v-for="(item, index) in seriesList"
                      :key="index"
                      :class="{'viewerSideActive': index==0}"
                      style="position: relative;margin-bottom:5px;border-radius: 2px;border: 1px solid #404040;"
                      series-type="current"
                      @click="showSeriesImage($event,index,item)"
                    >
                      <div class="viewernavigatorwrapper">
                        <!-- <el-image
                          class="image-preview"
                          style="height:72px;width:72px;"
                          :src="item.previewImageUrl"
                          fit="fill"
                        /> -->
                        <img
                          class="image-preview"
                          :src="item.previewImageUrl"
                          crossorigin="anonymous"
                          alt=""
                          style="width: 72px;height:72px;"
                          fit="fill"
                        >
                        <div class="viewernavitextwrapper">
                          <div style="padding: 1px 5px 1px 1px;display: flex;justify-content: space-between;">
                            <div v-if="item.keySeries" style="color:red">
                              Key Images
                            </div>
                            <div v-else>
                              #{{ item.seriesNumber }}
                            </div>
                            <div v-if="item.isExistMutiFrames && item.instanceCount > 1">
                              <el-popover
                                placement="right"
                                trigger="hover"
                                popper-class="instance_frame_wrapper"
                              >
                                <div class="frame_list">
                                  <div
                                    v-for="(instance, idx) in item.instanceInfoList"
                                    :key="instance.Id"
                                    class="frame_content"
                                    :style="{'margin-bottom':idx<item.instanceInfoList.length-1? '5px':'0px'}"
                                    @click="showMultiFrames(item, index, instance)"
                                  >
                                    <div>
                                      <div>{{ instance.InstanceNumber }}</div>
                                      <div>{{ `${instance.NumberOfFrames > 0 ? instance.NumberOfFrames : 1} frame` }}</div>
                                    </div>
                                  </div>
                                </div>
                                <i slot="reference" class="el-icon-connection" style="font-size: 15px;cursor: pointer;" />
                              </el-popover>
                            </div>
                          </div>
                          <div v-show="item.instanceCount" style="padding: 1px;">
                            {{ item.modality }}: {{ item.instanceCount }} image
                          </div>
                          <div v-show="!item.keySeries && item.sliceThickness" style="padding: 1px;">
                            T: {{ parseFloat(item.sliceThickness).toFixed(2) }}
                          </div>
                          <div v-show="!item.keySeries &&item.description" style="width: 120px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;padding: 1x;">
                            {{ item.description }}
                          </div>
                          <div v-if="!item.keySeries" style="padding: 1px;">
                            {{ item.imageloadedArr.length }}/{{ item.instanceCount }}
                          </div>

                        </div>
                      </div>
                      <div v-if="showDelete" style="display: flex;flex-direction: row;justify-content: space-between;" @click.stop="">

                        <div>
                          <span style="font-size: 12px;margin-right: 5px">{{ $t('trials:audit:table:isReading') }}</span>
                          <el-switch
                            v-model="item.isReading"
                            size="mini"
                            @change="changeReadingStatus($event, item)"
                          />
                        </div>
                        <div>
                          <span style="font-size: 12px;margin-right: 5px">{{ $t('trials:audit:table:isDelete') }}</span>
                          <el-switch
                            v-model="item.isDeleted"
                            size="mini"
                            @change="changeDeleteStatus($event, item)"
                          />
                        </div>
                      </div>
                      <div v-if="item.prefetchInstanceCount>0 && item.prefetchInstanceCount<item.instanceCount * 100">
                        <el-progress :percentage="parseInt((item.prefetchInstanceCount/item.instanceCount).toFixed(2))" />
                      </div>

                    </div>
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </div>
      <div class="viewerContent">
        <dicom-viewer id="dicomViewer" ref="dicomViewer" style="height:100%" />
      </div>
      <!-- <div class="viewerRightSidePanel">
        <dicom-tools />
      </div> -->

    </div>

  </div>
</template>

<script>
import * as dicomParser from 'dicom-parser'
import * as cornerstone from 'cornerstone-core'
import * as cornerstoneWADOImageLoader from 'cornerstone-wado-image-loader'
import dicomViewer from '@/components/Dicom/DicomViewer'
import { getStudyInfo, getSeriesList } from '@/api/reading'
import { getInstanceList, getPatientSeriesList, setSeriesStatus } from '@/api/trials'

import requestPoolManager from '@/utils/request-pool'
import store from '@/store'
import { changeURLStatic } from '@/utils/history.js'
import metaDataProvider from '@/utils/metaDataProvider'
cornerstone.metaData.addProvider(metaDataProvider, { priority: 10 });
var config = {
  maxWebWorkers: 4,
  startWebWorkersOnDemand: true,
  taskConfiguration: {
    decodeTask: {
      initializeCodecsOnStartup: false
    }
  }
}
cornerstoneWADOImageLoader.webWorkerManager.initialize(config)
cornerstoneWADOImageLoader.external.dicomParser = dicomParser
cornerstoneWADOImageLoader.external.cornerstone = cornerstone
const maximumSizeInBytes = 1024 * 1024 * 1024 * 6
cornerstone.imageCache.setMaximumSizeBytes(maximumSizeInBytes)
export default {
  components: {
    'dicom-viewer': dicomViewer
  },

  data: function() {
    return {
      trialId: '',
      studyId: '',
      tpCode: '',
      baseLine: null,
      studyCode: '',
      modality: '',
      description: '',
      seriesCount: 0,
      seriesList: [],
      currentSeriesIndex: -1,
      arr: [],
      activeName: 'first',
      tpList: [],
      visitNum: 0,
      labels: {},
      type: '',
      currentRelationIndex: [],
      cachedImages: [],
      isLoadedAll: false,
      studyList: {},
      currentStudy: '',
      previewImageCount: 0,
      relationStudyList: [],
      isStartLoad: false,
      firstInstanceId: '',
      showDelete: false,
      loading: false,
      imageList: [],
      showSeriesList: [],
      currentLoadIns: [],
      isFromCRCUpload: false
    }
  },
  created: function() {
    requestPoolManager.resetRequestPool()
    this.type = this.$router.currentRoute.query.type ? this.$router.currentRoute.query.type : ''

    this.visitNum = this.$router.currentRoute.query.visitNum ? parseInt(this.$router.currentRoute.query.visitNum) : 0
    // cornerstone.events.addEventListener('cornerstoneimageloaded', this.cornerstoneImageLoaded)
    // cornerstone.events.addEventListener('datasetscachechanged', this.datasetsCacheChanged)
    if (this.$router.currentRoute.query.TokenKey) {
      store.dispatch('user/setToken', this.$router.currentRoute.query.TokenKey)
      changeURLStatic('TokenKey', '')
    }
    this.studyId = this.$router.currentRoute.query.studyId
    this.isFromCRCUpload = !!this.$router.currentRoute.query.isFromCRCUpload
    if (this.type === 'Series') {
      // this.initStudy()
      this.showDelete = parseInt(this.$router.currentRoute.query.showDelete)
      this.initSeries()
    } else if (this.type === 'Study') {
      this.showDelete = parseInt(this.$router.currentRoute.query.showDelete)
      this.loadStudy()
    } else if (this.type === 'Share') {
      this.loadStudy()
    } else if (this.type === 'Patient') {
      this.loadPatientStudy()
    }
    cornerstone.events.addEventListener('cornerstoneimageloadprogress', this.cornerstoneimageloadprogress)
    window.addEventListener('beforeunload', e => {
      cornerstone.imageCache.purgeCache()
      requestPoolManager.resetRequestPool()
    })
  },
  beforeDestroy() {
    requestPoolManager.stopTaskTimer()
    window.removeEventListener('beforeunload', e => {
      cornerstone.imageCache.purgeCache()
      requestPoolManager.resetRequestPool()
    })
  },
  methods: {
    async loadStudy() {
      const data = await getStudyInfo(this.studyId)
      if (data.IsSuccess) {
        if (data.Result) {
          this.studyCode = data.Result.StudyCode
          this.modality = data.Result.Modalities
          this.seriesCount = data.Result.SeriesCount
          this.description = data.Result.Description
        }
        const url = `/series/list/${this.studyId}`
        this.getSeriesList(url)
      }
    },
    async loadPatientStudy() {
      try {
        const data = await getPatientSeriesList(this.studyId)
        if (data.IsSuccess) {
          const { Result } = data
          var seriesList = []
          Result.forEach((item, index) => {
            const imageIds = []
            item.InstanceInfoList.forEach(i => {
              if (i.NumberOfFrames && i.NumberOfFrames > 1) {
                for (let j = 0; j < i.NumberOfFrames; j++) {
                  imageIds.push(`wadouri:${localStorage.getItem('location') !== 'USA' ? this.OSSclientConfig.basePath : this.OSSclientConfig.basePath}${i.Path}?frame=${j}&instanceId=${i.Id}&seriesIndex=${index}`)
                }
                i.ImageId = `wadouri:${localStorage.getItem('location') !== 'USA' ? this.OSSclientConfig.basePath : this.OSSclientConfig.basePath}${i.Path}?frame=0&instanceId=${i.Id}&seriesIndex=${index}`
              } else {
                const imageId = `wadouri:${localStorage.getItem('location') !== 'USA' ? this.OSSclientConfig.basePath : this.OSSclientConfig.basePath}${i.Path}?instanceId=${i.Id}&seriesIndex=${index}`
                imageIds.push(imageId)
                i.ImageId = imageId
              }
            })
            var subjectVisitId = this.$router.currentRoute.query.subjectVisitId
            var studyId = this.$router.currentRoute.query.studyId
            var trialId = this.$router.currentRoute.query.trialId
            seriesList.push({
              trialId,
              subjectVisitId,
              studyId,
              imageIds: imageIds,
              instanceInfoList: item.InstanceInfoList,
              seriesId: item.Id,
              seriesUid: item.SeriesInstanceUid,
              seriesNumber: item.SeriesNumber,
              sliceThickness: item.SliceThickness,
              modality: item.Modality,
              description: item.Description,
              isReading: item.IsReading,
              isDeleted: item.IsDeleted,
              previewImageUrl: item.ImageResizePath ? this.OSSclientConfig.basePath + item.ImageResizePath : `/api/series/preview/${item.Id}`,
              instanceCount: item.InstanceCount,
              prefetchInstanceCount: 0,
              hasLabel: item.HasLabel,
              keySeries: item.KeySeries,
              tpCode: this.tpCode,
              loadStatus: false,
              imageloadedArr: [],
              isExistMutiFrames: item.IsExistMutiFrames
            })
          })
          this.seriesList = seriesList
          if (this.seriesList.length > 0) {
            this.loadAllImages()
            this.$refs.dicomViewer.loadImageStack(this.seriesList[0], this.labels[this.tpCode])
            this.firstInstanceId = this.seriesList[0].imageIds[0]
          }
        }
      } catch (err) {
        console.log(err)
      }
    },
    async getSeriesList(url) {
      try {
        const data = await getSeriesList(url)
        if (data.IsSuccess) {
          const { Result } = data
          var seriesList = []
          Result.forEach((item, index) => {
            const imageIds = []
            item.InstanceInfoList.forEach(i => {
              if (i.NumberOfFrames && i.NumberOfFrames > 1) {
                for (let j = 0; j < i.NumberOfFrames; j++) {
                  imageIds.push(`wadouri:${localStorage.getItem('location') !== 'USA' ? this.OSSclientConfig.basePath : this.OSSclientConfig.basePath}${i.Path}?frame=${j}&instanceId=${i.Id}&seriesIndex=${index}`)
                }
                i.ImageId = `wadouri:${localStorage.getItem('location') !== 'USA' ? this.OSSclientConfig.basePath : this.OSSclientConfig.basePath}${i.Path}?frame=0&instanceId=${i.Id}&seriesIndex=${index}`
              } else {
                const imageId = `wadouri:${localStorage.getItem('location') !== 'USA' ? this.OSSclientConfig.basePath : this.OSSclientConfig.basePath}${i.Path}?instanceId=${i.Id}&seriesIndex=${index}`
                imageIds.push(imageId)
                i.ImageId = imageId
              }
            })
            var subjectVisitId = this.$router.currentRoute.query.subjectVisitId
            var studyId = this.$router.currentRoute.query.studyId
            var trialId = this.$router.currentRoute.query.trialId
            seriesList.push({
              trialId,
              subjectVisitId,
              studyId,
              imageIds: imageIds,
              instanceInfoList: item.InstanceInfoList,
              seriesId: item.Id,
              seriesUid: item.SeriesInstanceUid,
              seriesNumber: item.SeriesNumber,
              sliceThickness: item.SliceThickness,
              modality: item.Modality,
              description: item.Description,
              isReading: item.IsReading,
              isDeleted: item.IsDeleted,
              previewImageUrl: item.ImageResizePath ? this.OSSclientConfig.basePath + item.ImageResizePath : `/api/series/preview/${item.Id}`,
              instanceCount: item.InstanceCount,
              prefetchInstanceCount: 0,
              hasLabel: item.HasLabel,
              keySeries: item.KeySeries,
              tpCode: this.tpCode,
              loadStatus: false,
              imageloadedArr: [],
              isExistMutiFrames: item.IsExistMutiFrames
            })
          })
          this.seriesList = seriesList
          if (this.seriesList.length > 0) {
            this.loadAllImages()
            this.$refs.dicomViewer.loadImageStack(this.seriesList[0], this.labels[this.tpCode])
            this.firstInstanceId = this.seriesList[0].imageIds[0]
          }
        }
      } catch (e) {
        console.log(e)
      }
    },
    async initSeries() {
      try {
        this.studyCode = this.$router.currentRoute.query.studyCode
        this.modality = this.$router.currentRoute.query.modality
        this.seriesCount = 1
        this.description = this.$router.currentRoute.query.description
        var seriesId = this.$router.currentRoute.query.seriesId
        var seriesNumber = this.$router.currentRoute.query.seriesNumber
        var subjectVisitId = this.$router.currentRoute.query.subjectVisitId
        var studyId = this.$router.currentRoute.query.studyId
        var trialId = this.$router.currentRoute.query.trialId
        const res = await getInstanceList(seriesId)
        if (!res.Result || (res.Result && res.Result.length === 0)) return
        var seriesInstanceUid = res.Result[0].SeriesInstanceUid
        var sliceThickness = res.Result[0].SliceThickness
        var isReading = res.Result[0].IsReading
        var isDeleted = res.Result[0].IsDeleted
        var seriesList = []
        var imageIds = []
        let isExistMutiFrames = false
        const instanceInfoList = []
        res.Result.forEach(instance => {
          let imageId = ''
          if (instance.NumberOfFrames > 1) {
            for (let i = 0; i < instance.NumberOfFrames; i++) {
              imageIds.push(`wadouri:${localStorage.getItem('location') !== 'USA' ? this.OSSclientConfig.basePath : this.OSSclientConfig.basePath}${instance.Path}?frame=${i}&instanceId=${instance.Id}&seriesIndex=0`)
            }
            isExistMutiFrames = true
            imageId = `wadouri:${localStorage.getItem('location') !== 'USA' ? this.OSSclientConfig.basePath : this.OSSclientConfig.basePath}${instance.Path}?frame=0&instanceId=${instance.Id}&seriesIndex=0`
          } else {
            const path = `wadouri:${localStorage.getItem('location') !== 'USA' ? this.OSSclientConfig.basePath : this.OSSclientConfig.basePath}${instance.Path}?instanceId=${instance.Id}&seriesIndex=0`
            imageIds.push(path)
            imageId = path
          }
          instanceInfoList.push({ Id: instance.Id, InstanceNumber: instance.InstanceNumber, NumberOfFrames: instance.NumberOfFrames, Path: instance.Path, ImageId: imageId })
        })
        seriesList.push({
          trialId,
          subjectVisitId,
          studyId,
          imageIds: imageIds,
          instanceInfoList,
          seriesId: seriesId,
          seriesUid: seriesInstanceUid,
          seriesNumber: seriesNumber,
          sliceThickness: sliceThickness,
          modality: this.modality,
          description: this.description,
          isReading,
          isDeleted,
          previewImageUrl: res.OtherInfo.ImageResizePath ? this.OSSclientConfig.basePath + res.OtherInfo.ImageResizePath : res.OtherInfo.ImageResizePath,
          instanceCount: res.Result.length,
          prefetchInstanceCount: 0,
          loadStatus: false,
          imageloadedArr: [],
          isExistMutiFrames: isExistMutiFrames
        })
        this.seriesList = seriesList
        if (this.seriesList.length > 0) {
          this.$nextTick(() => {
            this.loadAllImages()
            this.$refs.dicomViewer.loadImageStack(this.seriesList[0])
            this.firstInstanceId = this.seriesList[0].imageIds[0]
          })
        }
      } catch (e) {
        console.log(e)
      }
    },
    showSeriesImage(e, seriesIndex, series) {
      // if (seriesIndex === this.currentSeriesIndex) return
      const element = e.currentTarget
      const elements = document.querySelectorAll('[series-type]')
      Array.from(elements).forEach((e) => {
        e.classList.remove('viewerSideActive')
      })
      element.classList.add('viewerSideActive')
      this.currentSeriesIndex = seriesIndex
      this.$refs.dicomViewer.loadImageStack(this.seriesList[seriesIndex])
      if (!series.loadStatus) {
        series.isLoading = true
        var isAddToTakPool = false
        if (this.showSeriesList.includes(`0_${seriesIndex}`)) {
          isAddToTakPool = true
        } else {
          this.showSeriesList.push(`0_${seriesIndex}`)
        }
        if (!isAddToTakPool) {
          var priority = parseInt(new Date().getTime())
          // var images = []
          // if (series.isExistMutiFrames) {
          //   images = series.imageIds.filter(i => i.includes('?frame=0'))
          // } else {
          //   images = series.imageIds
          // }
          // images.map(imageId => {
          //   this.imageList.push({ imageId: imageId, seriesId: series.seriesId, studyIndex: 0, seriesIndex: seriesIndex, priority })
          // })
          if (series.isExistMutiFrames) {
            series.instanceInfoList.map(image => {
              this.imageList.push({ imageId: image.ImageId, seriesId: series.seriesId, priority })
            })
          } else {
            series.imageIds.map(imageId => {
              this.imageList.push({ imageId: imageId, seriesId: series.seriesId, priority })
            })
          }
          if (this.imageList.length > 0) {
            this.loopLoad()
          }
        } else {
          requestPoolManager.changePriority(series.seriesId)
        }
      }
    },
    showMultiFrames(series, seriesIndex, instanceInfo) {
      this.currentSeriesIndex = seriesIndex
      const imageIds = []
      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}&seriesIndex=${seriesIndex}`)
        }
      } else {
        imageIds.push(`wadouri:${localStorage.getItem('location') !== 'USA' ? this.OSSclientConfig.basePath : this.OSSclientConfig.basePath}${instanceInfo.Path}?instanceId=${instanceInfo.Id}&seriesIndex=${seriesIndex}`)
      }
      const seriesInfo = {
        trialId: series.trialId,
        subjectVisitId: series.subjectVisitId,
        studyId: series.studyId,
        imageIds: imageIds,
        seriesId: series.seriesId,
        seriesUid: series.seriesUid,
        seriesNumber: series.seriesNumber,
        sliceThickness: series.sliceThickness,
        modality: series.modality,
        description: series.description,
        isReading: series.isReading,
        isDeleted: series.isDeleted,
        previewImageUrl: series.previewImageUrl,
        instanceCount: series.instanceCount
      }
      this.$refs.dicomViewer.loadImageStack(seriesInfo)
      if (!series.loadStatus) {
        var isAddToTakPool = false
        if (this.showSeriesList.includes(`0_${seriesIndex}`)) {
          isAddToTakPool = true
        } else {
          this.showSeriesList.push(`0_${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: 0, seriesIndex: seriesIndex, priority })
          //   })
          // } else {
          //   series.imageIds.map((imageId) => {
          //     this.imageList.push({ imageId: imageId, seriesId: series.seriesId, studyIndex: 0, seriesIndex: seriesIndex, priority })
          //   })
          // }
          if (series.isExistMutiFrames) {
            series.instanceInfoList.map(image => {
              this.imageList.push({ imageId: image.ImageId, seriesId: series.seriesId, priority })
            })
          } else {
            series.imageIds.map(imageId => {
              this.imageList.push({ imageId: imageId, seriesId: series.seriesId, priority })
            })
          }

          if (this.imageList.length > 0) {
            this.loopLoad()
          }
        } else {
          requestPoolManager.changePriority(series.seriesId)
        }
      }
    },
    initStudy() {
      this.studyCode = this.$router.currentRoute.query.studyCode
      this.modality = this.$router.currentRoute.query.modality
      this.seriesCount = 1
      this.description = this.$router.currentRoute.query.description
      if (this.$router.currentRoute.query.series) {
        const seriesInfo = JSON.parse(this.$router.currentRoute.query.series)
        var seriesList = []
        const imageIds = []
        seriesInfo.InstancePathList.forEach((path) => {
          imageIds.push(`wadouri:${localStorage.getItem('location') !== 'USA' ? this.OSSclientConfig.basePath : this.OSSclientConfig.basePath}${path}`)
        })
        seriesList.push({
          imageIds: imageIds,
          seriesId: seriesInfo.Id,
          seriesUid: seriesInfo.SeriesInstanceUid,
          seriesNumber: seriesInfo.SeriesNumber,
          sliceThickness: seriesInfo.SliceThickness,
          modality: seriesInfo.Modality,
          description: seriesInfo.Description,
          previewImageUrl: seriesInfo.ImageResizePath ? this.OSSclientConfig.basePath + seriesInfo.ImageResizePath : `/api/series/preview/${seriesInfo.Id}`,
          instanceCount: seriesInfo.InstanceCount,
          prefetchInstanceCount: 0,
          hasLabel: seriesInfo.HasLabel,
          keySeries: seriesInfo.KeySeries,
          loadStatus: false,
          imageloadedArr: []
        })
        this.seriesList = seriesList
        if (this.seriesList.length > 0) {
          this.$nextTick(() => {
            this.loadAllImages()
            this.$refs.dicomViewer.loadImageStack(this.seriesList[0])
            this.firstInstanceId = this.seriesList[0].imageIds[0]
          })
        }
      }
    },
    async deleteSeries() {
      this.loading = true
      var subjectVisitId = this.$router.currentRoute.query.subjectVisitId
      var studyId = this.$router.currentRoute.query.studyId
      var seriesId = this.$router.currentRoute.query.seriesId
      try {
        const res = await setSeriesStatus(this.trialId, subjectVisitId, studyId, seriesId, 5)
        this.loading = false
        if (res.IsSuccess) {
          this.$message.success(this.$t('common:message:savedSuccessfully'))

          window.opener.postMessage({ type: 'refreshSeriesList', data: '' }, window.location)
        }
      } catch (e) {
        console.log(e)
        this.loading = false
      }
    },
    async changeReadingStatus(callback, data) {
      let statusStr = ''
      if (callback) {
        statusStr = this.$t('trials:audit:label:setSeriesReading')
        data.isReading = false
      } else {
        statusStr = this.$t('trials:audit:label:setSeriesNotReading')
        data.isReading = true
      }
      var message = this.$t('trials:audit:message:changeSeriesStatus').replace('xxx', statusStr)
      message = message.replace('yyy', this.$fd('YesOrNo', !data.isReading))
      const confirm = await this.$confirm(
        message,
        {
          type: 'warning',
          distinguishCancelAndClose: true
        }
      )
      if (confirm !== 'confirm') return
      const state = data.isReading ? 1 : 2
      this.loading = true
      try {
        const res = await setSeriesStatus(data.trialId, data.subjectVisitId, data.studyId, data.seriesId, state)
        this.loading = false
        if (res.IsSuccess) {
          data.isReading = !data.isReading
          this.$message.success(this.$t('common:message:savedSuccessfully'))
          window.opener.postMessage({ type: 'refreshSeriesList', data: '' }, window.location)
        }
      } catch (e) {
        console.log(e)
        this.loading = false
      }
    },
    async changeDeleteStatus(callback, data) {
      let statusStr = ''
      if (callback) {
        statusStr = this.$t('trials:audit:label:setSeriesDeleted')
        data.isDeleted = false
      } else {
        statusStr = this.$t('trials:audit:label:setSeriesNotDelete')
        data.isDeleted = true
      }
      var message = this.$t('trials:audit:message:changeSeriesStatus').replace('xxx', statusStr)
      message = message.replace('yyy', this.$fd('YesOrNo', !data.isDeleted))
      const confirm = await this.$confirm(
        message,
        {
          type: 'warning',
          distinguishCancelAndClose: true
        }
      )
      if (confirm !== 'confirm') return
      const state = data.isDeleted ? 5 : 4
      this.loading = true
      try {
        const res = await setSeriesStatus(data.trialId, data.subjectVisitId, data.studyId, data.seriesId, state)
        this.loading = false
        if (res.IsSuccess) {
          data.isDeleted = !data.isDeleted
          this.$message.success(this.$t('common:message:savedSuccessfully'))
          window.opener.postMessage({ type: 'refreshSeriesList', data: '' }, window.location)
        }
      } catch (e) {
        console.log(e)
        this.loading = false
      }
    },
    loadAllImages() {
      const seriesIndex = this.seriesList.findIndex(i => i.loadStatus === false)
      if (seriesIndex === -1) return
      const series = this.seriesList[seriesIndex]
      var priority = new Date().getTime()
      // var images = []
      // if (series.isExistMutiFrames) {
      //   images = series.imageIds.filter(i => i.includes('?frame=0'))
      // } else {
      //   images = series.imageIds
      // }
      // images.map(imageId => {
      //   this.imageList.push({ imageId: imageId, seriesId: series.seriesId, studyIndex: 0, seriesIndex: seriesIndex, priority })
      // })
      if (series.isExistMutiFrames) {
        series.instanceInfoList.map(image => {
          this.imageList.push({ imageId: image.ImageId, seriesId: series.seriesId, priority })
        })
      } else {
        series.imageIds.map(imageId => {
          this.imageList.push({ imageId: imageId, seriesId: series.seriesId, priority })
        })
      }
      if (this.imageList.length > 0) {
        this.loopLoad()
      }
    },
    getInstanceInfo(imageId) {
      const params = {}
      const searchParams = new URLSearchParams(imageId.split('?')[1])
      for (const [key, value] of searchParams.entries()) {
        params[key] = value
      }
      return params
    },
    loopLoad() {
      if (this.imageList.length > 0) {
        requestPoolManager.startTaskTimer()
        console.log('loopLoad')
        this.imageList.map(image => {
          requestPoolManager.loadAndCacheImagePlus(image.imageId, image.seriesId, image.priority)
        })
        requestPoolManager.sortTaskPool()
        this.imageList = []
      }
    },
    datasetsCacheChanged(e) {
      // const uri = e.detail.uri
      const cacheInfo = e.detail.cacheInfo
      const cacheSizeInBytes = cacheInfo.cacheSizeInBytes
      if (cacheSizeInBytes >= maximumSizeInBytes) {
        // this.unload()
      }
    },
    unload() {
      this.cachedImages.sort(this.compare)
      cornerstoneWADOImageLoader.wadouri.dataSetCacheManager.unload(this.cachedImages[0].uri)
      this.cachedImages.splice(0, 1)
    },
    compare(a, b) {
      if (a.timeStamp > b.timeStamp) {
        return -1
      }
      if (a.timeStamp < b.timeStamp) {
        return 1
      }

      return 0
    },
    cornerstoneimageloadprogress(e) {
      const imageId = e.detail.imageId
      const percentComplete = e.detail.percentComplete
      const params = {}
      const searchParams = new URLSearchParams(imageId.split('?')[1])
      for (const [key, value] of searchParams.entries()) {
        params[key] = value
      }
      if (this.visitTaskId === params.visitTaskId) {
        const seriesIndex = params.seriesIndex
        var prefetchInstanceCount = this.seriesList[seriesIndex].prefetchInstanceCount
        var instanceCount = this.seriesList[seriesIndex].instanceCount
        if (this.seriesList[seriesIndex].imageloadedArr.indexOf(imageId) < 0 && this.seriesList[seriesIndex].imageloadedArr.length < this.seriesList[seriesIndex].instanceCount) {
          const i = this.currentLoadIns.findIndex(i => i.imageId === imageId)
          if (i > -1) {
            prefetchInstanceCount = prefetchInstanceCount - this.currentLoadIns[i].percentComplete + percentComplete
            this.currentLoadIns[i].percentComplete = percentComplete
            if (percentComplete === 100) {
              this.currentLoadIns.splice(i, 1)
            }
          } else {
            if (percentComplete !== 100) {
              this.currentLoadIns.push({ imageId, percentComplete })
            }
            prefetchInstanceCount = prefetchInstanceCount + percentComplete
          }
          this.seriesList[seriesIndex].prefetchInstanceCount = prefetchInstanceCount
          if (percentComplete >= 100) {
            this.seriesList[seriesIndex].imageloadedArr.push(imageId)
          }
        }
        if (prefetchInstanceCount >= instanceCount * 100) {
          this.seriesList[seriesIndex].prefetchInstanceCount = instanceCount * 100
          // 设置当前序列状态为已下载完成
          this.seriesList[seriesIndex].loadStatus = true
          if (!this.isFromCRCUpload) {
            this.loadAllImages()
          }
        }
      }
    }
  }

}
</script>

<style>
.viewerContainer .el-tabs--border-card{
  background:none;
  border: none;
}
.viewerContainer .el-tabs__item{
  height: 35px;
  line-height: 35px;
}
.viewerContainer .el-tabs--border-card>.el-tabs__content{
  padding: 5px 0px 0px 0px;
}
.viewerContainer ::-webkit-scrollbar {
    width: 7px;
    height: 7px;
}
.viewerContainer ::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background: #d0d0d0;
}
.viewerContainer .relationVisit{
  line-height: 20px;
  cursor: pointer;
}
  .viewerContainer{
    display: block;
    height: 100%;
    margin-left: auto;
    margin-right: auto;
    background-color: #444;
    overflow: hidden;
  }
.viewerContainer  .viewerBanner {
    background: linear-gradient(0,#444,#222);
    min-height: 28px;
    font-size: 16px;
    margin: 0;
    height: 30px;
    padding-top: 0;
    padding-left: 5px;
    padding-right: 5px;
    font-weight: bold;
}
.viewerContainer .viewerContentWrapper {
  display: flex;
  flex-direction: row;
    width: 100%;
    padding: 5px;
    /* height: 95%; */
    height: 99%;
    overflow: hidden;
    text-overflow: clip;
    white-space: nowrap;
}
.viewerContainer .viewerContentWrapper>div {
    display: inline-block;
    white-space: normal;
}
.viewerContainer .viewerLeftSidePanel {
    width: 215px;
    background-color: #323232;
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    margin-right: 2px;
    color: #D0D0D0;
    overflow-y: auto;
}
.viewerContainer .viewerContentWrapper>div>.sidePanelBody {
    background: rgba(50,50,50,1);
    word-break: break-all;
    display: table;
    width: 100%;
    border: 1px solid #3e3f3a;
}
.viewerContainer .viewerContentWrapper>div>div.sidePanelBody>div {
    width: 100%;
    height: 100%;
}
.viewerContainer .studyDesc{
  font-weight: bold;
  font-size: 13px;
  text-align: center;
  background: rgb(88 84 83);
  color: #d0d0d0;
  padding: 2px;
}
.viewerContainer .ps {
    overflow: hidden !important;
    overflow-anchor: none;
    -ms-overflow-style: none;
    touch-action: auto;
    -ms-touch-action: auto;
}
.viewerContainer .viewerLeftSidePanel .viewernavigatorwrapper {
    display: flex;
    width: 200px;
    height: 84px;
    padding: 1px 2px 1px 8px;
    margin: 6px 0 6px 1px;
    /* border-radius: 2px;
    border: 1px solid #404040; */
}
.viewerContainer .viewernavigatorwrapper .el-progress__text{
  display: none;
}
.viewerContainer .viewernavigatorwrapper .el-progress-bar{
  padding-right:0px;
}
.viewerContainer .ui-draggable-handle {
    -ms-touch-action: none;
    touch-action: none;
}
.viewerContainer .viewerLeftSidePanel .image-preview {
    border: 2px solid #252525;
    cursor: pointer;
}
.viewerContainer .viewerLeftSidePanel .viewernavitextwrapper {
    /* width: 120px;
    height: 80px; */
    flex:1;
    padding: 3px 1px 3px 4px;
    vertical-align: top;
    font-size: 12px;
}
.viewerContainer .viewerLeftSidePanel .viewerlabelwrapper {
    width: 20px;

    font-size: 12px;
}
.viewerContainer .viewerSideActive {
    background: #16477b;
    background: #16477b80;
    border: 1px solid #23527b;
}
.viewerContainer .viewerContent {
    flex: 1;
    height: 100%;
    display: block;
    background-color: black;
    color: #D0D0D0;
    font-size: 13px;
}
.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;
}
/* .viewerRightSidePanel {
    width: 300px;
    height: 100%;
    background-color: #323232;
    margin: 0;
    padding: 0;
    margin-left: 2px;
    border: 1px solid blueviolet;
    color: #D0D0D0;
    font-size: 13px;
} */
</style>
