<template>
  <div class="viewerContainer">
    <div class="viewerContentWrapper">
      <div class="viewerLeftSidePanel">
        <div id="listWrapper" class="sidePanelBody">
          <div class="sidePanelThumbs">
            <el-tabs v-model="activeName" type="border-card" @tab-click="handleTabClick">
              <el-tab-pane :label="$t('trials:dicom-show:currentVisit')" name="current-study">
                <div v-if="visitInfo" class="text-desc" style="background:rgb(55 55 55);">
                  {{ visitInfo }}
                </div>
                <div class="viewerSidethumbs ps" style="position: relative;">
                  <div class="viewerSidethumbinner">
                    <!-- <div
                      v-for="(study, index) in studyList"
                      :key="index"
                    >  -->
                    <el-collapse v-model="activeNames">
                      <el-collapse-item v-for="(study, index) in studyList" :key="`${study.StudyId}`"
                        :name="`${study.StudyId}`">
                        <template slot="title">

                          <div class="text-desc">
                            {{ study.StudyCode }}
                          </div>
                          <!-- <div v-show="study.Description" class="text-desc">
                            {{ study.Description }}
                          </div> -->
                          <el-tooltip v-show="study.Description" class="item" effect="dark" :content="study.Description"
                            placement="bottom">
                            <div v-show="study.Description"
                              style="width: 50px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;padding: 1x;">
                              {{ study.Description }}
                            </div>
                          </el-tooltip>
                          <div v-show="study.SeriesCount" class="text-desc">
                            {{ study.Modalities }} : {{ study.SeriesCount }} Series
                          </div>
                        </template>
                        <div v-show="study.Description" class="text-desc" style="background-color: #1f1f1f;">
                          {{ study.Description }}
                        </div>
                        <div v-for="(series, i) in study.SeriesList" :key="i"
                          :class="{ 'viewerSideActive': i == 0 && index === 0 }"
                          style="position: relative;margin-bottom:5px;border-radius: 2px;border: 1px solid #404040;"
                          series-type="current" @click="showSeriesImage($event, index, i, series)">
                          <div class="viewernavigatorwrapper">
                            <img class="image-preview" :src="series.previewImageUrl" crossorigin="anonymous" alt=""
                              style="width: 85px;height:85px;" fit="fill">
                            <div class="viewernavitextwrapper">
                              <div style="padding: 1px 5px 1px 1px;display: flex;justify-content: space-between;">
                                <div>#{{ series.seriesNumber }}</div>
                                <div v-if="series.isExistMutiFrames && series.instanceCount > 1">
                                  <el-popover v-model="series.isShowPopper" placement="right-start" trigger="manual"
                                    popper-class="instance_frame_wrapper">
                                    <div style="text-align: right;">
                                      <i class="el-icon-circle-close"
                                        style="font-size: 20px;cursor: pointer;color:#ddd;"
                                        @click="series.isShowPopper = false" />
                                    </div>
                                    <div class="frame_list">
                                      <div v-for="(instance, idx) in series.instanceInfoList" :key="instance.Id"
                                        class="frame_content"
                                        :style="{ 'margin-bottom': idx < series.instanceInfoList.length - 1 ? '5px' : '0px' }"
                                        @click="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.NumberOfFrames : 1} frame` }}
                                          </div>
                                          <div v-if="showDelete">
                                            <span>{{ $t('trials:audit:table:isDelete') }}</span>
                                            <el-switch v-model="instance.IsDeleted" size="mini"
                                              @change="changeInstanceDeleteStatus($event, series, instance)" />
                                            <span style="margin-left:10px;">{{ $t('trials:audit:table:isReading')
                                            }}</span>
                                            <el-switch v-model="instance.IsReading" size="mini"
                                              @change="changeInstanceReadingStatus($event, series, instance)" />
                                          </div>
                                        </div>

                                      </div>
                                    </div>
                                    <i slot="reference" class="el-icon-connection"
                                      style="font-size: 15px;cursor: pointer;"
                                      @click="popperClick(studyList, series)" />
                                  </el-popover>
                                </div>

                              </div>
                              <div v-show="series.InstanceCount" style="padding: 1px;">
                                {{ series.modality }}: {{ series.instanceCount }} image
                              </div>
                              <div v-show="series.sliceThickness" style="padding: 1px;">
                                T: {{ series.sliceThickness }}
                              </div>

                              <el-tooltip v-show="series.description" class="item" effect="dark"
                                :content="series.description" placement="bottom">
                                <div v-show="series.description"
                                  style="width: 120px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;padding: 1x;">
                                  {{ series.description }}
                                </div>
                              </el-tooltip>
                              <div style="padding: 1px;">
                                {{ series.imageloadedArr.length <= series.instanceCount ? series.imageloadedArr.length :
                                  series.instanceCount }}/{{ series.instanceCount }} </div>
                                  <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;">{{ $t('trials:audit:table:isReading') }}</span>
                                <el-switch v-model="series.isReading" size="mini"
                                  @change="changeReadingStatus($event, series)" />
                              </div>
                              <div>
                                <span style="font-size: 12px;">{{ $t('trials:audit:table:isDelete') }}</span>
                                <el-switch v-model="series.isDeleted" size="mini"
                                  @change="changeDeleteStatus($event, series)" />
                              </div>
                            </div>
                            <!-- <div style="position: absolute;bottom: -10px;left: 0;width: 100%;">
                          <el-progress v-if="series.prefetchInstanceCount>0 && series.prefetchInstanceCount<series.instanceCount" :percentage="Number(series.prefetchInstanceCount/series.instanceCount)*100" />
                        </div> -->
                            <div
                              v-if="series.prefetchInstanceCount > 0 && series.prefetchInstanceCount < series.instanceCount * 100">
                              <el-progress
                                :percentage="parseInt((series.prefetchInstanceCount / series.instanceCount).toFixed(2))" />
                            </div>

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

                    </el-collapse>

                  </div>
                </div>
              </el-tab-pane>
              <el-tab-pane v-show="!visitTaskId" :label="$t('trials:dicom-show:relatedVisit')" name="relation-study"
                class="pane-relation-wrapper">
                <div class="viewerSidethumbinner">

                  <el-collapse v-model="relationActiveName" @change="handelRelationActiveChange">
                    <template v-for="item in relationStudyListByVisitName">
                      <div :key="`${item.VisitName}`">
                        <div v-show="item.VisitName" class="text-desc" style="background-color: #1f1f1f;">
                          {{ item.VisitName }}
                        </div>
                        <template v-for="(study, studyIndex) in relationStudyList">
                          <el-collapse-item :key="`${study.StudyId}`" :name="`${study.StudyId}`"
                            v-if="study.VisitName === item.VisitName">
                            <template slot="title">

                              <div class="text-desc">
                                {{ study.StudyCode }}
                              </div>
                              <!-- <div v-show="study.Description" class="text-desc">
                          {{ study.Description }}
                        </div> -->

                              <div v-show="study.SeriesCount" class="text-desc">
                                {{ study.Modalities }} : {{ study.SeriesCount }} Series
                              </div>
                            </template>
                            <div v-show="study.Description" class="text-desc" style="background-color: #1f1f1f;">
                              {{ study.Description }}
                            </div>
                            <div class="viewerSidethumbs ps" style="position: relative;">
                              <div class="viewerSidethumbinner">
                                <div v-for="(seriesItem, index) in study.seriesList" :key="seriesItem.seriesId">
                                  <div class="viewernavigatorwrapper"
                                    style="position: relative;border:1px solid #434343;" series-type="relation"
                                    @click="showRelationSeriesImage($event, seriesItem, studyIndex, index)">
                                    <img class="image-preview" :src="seriesItem.previewImageUrl" crossorigin="anonymous"
                                      alt="" style="width: 85px;height:85px;" fit="fill">

                                    <div class="viewernavitextwrapper">
                                      <div
                                        style="padding: 1px 5px 1px 1px;display: flex;justify-content: space-between;">
                                        <div v-if="seriesItem.keySeries" style="color:red">
                                          Key Images
                                        </div>
                                        <div v-else>#{{ seriesItem.seriesNumber }}</div>
                                        <div v-if="seriesItem.isExistMutiFrames && seriesItem.instanceCount > 1">
                                          <el-popover placement="right-start" trigger="click"
                                            popper-class="instance_frame_wrapper">
                                            <div class="frame_list">
                                              <div v-for="(instance, idx) in seriesItem.instanceInfoList"
                                                :key="instance.Id" class="frame_content"
                                                :style="{ 'margin-bottom': idx < seriesItem.instanceInfoList.length - 1 ? '5px' : '0px' }"
                                                @click="showMultiFrames(studyIndex, seriesItem, 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="seriesItem.instanceCount" style="padding: 1px;">
                                        {{ seriesItem.modality }}: {{ seriesItem.instanceCount }} image
                                      </div>
                                      <div v-show="seriesItem.sliceThickness" style="padding: 1px;">
                                        T: {{ seriesItem.sliceThickness }}
                                      </div>
                                      <el-tooltip v-show="seriesItem.description" class="item" effect="dark"
                                        :content="seriesItem.description" placement="bottom">
                                        <div v-show="seriesItem.description"
                                          style="width: 120px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;padding: 1x;">
                                          {{ seriesItem.description }}
                                        </div>
                                      </el-tooltip>
                                    </div>
                                  </div>
                                  <!-- <el-image
                            class="image-preview"
                            style="height:72px;width:72px;"
                            :src="seriesItem.previewImageUrl"
                            fit="fill"
                          /> -->
                                  <div
                                    v-if="seriesItem.prefetchInstanceCount > 0 && seriesItem.prefetchInstanceCount < seriesItem.instanceCount * 100">
                                    <el-progress
                                      :percentage="parseInt((seriesItem.prefetchInstanceCount / seriesItem.instanceCount).toFixed(2))" />
                                  </div>
                                </div>
                              </div>
                            </div>
                          </el-collapse-item>
                        </template>

                      </div>
                    </template>

                  </el-collapse>

                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </div>
      <div class="viewerContent">
        <dicom-viewer id="dicomViewer" ref="dicomViewer" style="height:100%" />
      </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 { getVisitStudyList, getAllRelationStudyList, getSeriesList } from '@/api/reading'
import { setSeriesStatus, setInstanceStatus } from '@/api/trials'
import { getTaskUploadedDicomStudyList } from '@/api/reading'
import requestPoolManager from '@/utils/request-pool'
import store from '@/store'
import { changeURLStatic } from '@/utils/history.js'
import { getNetWorkSpeed, setNetWorkSpeedSize, workSpeedclose } from "@/utils"
import metaDataProvider from '@/utils/metaDataProvider'
cornerstone.metaData.addProvider(metaDataProvider, { priority: 10 })
// import * as cornerstoneTools from 'cornerstone-tools'
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 {
  name: 'DicomsOfVisit',
  components: {
    'dicom-viewer': dicomViewer
  },
  data() {
    return {
      studyList: [],
      visitInfo: '',
      activeName: 'current-study',
      relationStudyList: [],
      relationStudyListByVisitName: [],
      cachedImages: [],
      isReading: null,
      isStartLoad: false,
      firstInstanceId: '',
      firstSeriesId: '',
      showDelete: 0,
      imageList: [],
      activeNames: [],
      relationActiveName: [],
      showSeriesList: [],
      currentLoadIns: [],
      isFromCRCUpload: false,
      visitTaskId: null,
      page: '',
      activeSeriesId: null
    }
  },
  mounted() {
    requestPoolManager.resetRequestPool()
    document.documentElement.style.userSelect = 'none'
    if (this.$router.currentRoute.query.TokenKey) {
      store.dispatch('user/setToken', this.$router.currentRoute.query.TokenKey)
      changeURLStatic('TokenKey', '')
    }

    this.trialId = this.$router.currentRoute.query.trialId
    this.subjectVisitId = this.$router.currentRoute.query.subjectVisitId
    this.visitInfo = this.$router.currentRoute.query.visitInfo
    this.isReading = this.$router.currentRoute.query.isReading ? this.$router.currentRoute.query.isReading * 1 : 0
    this.showDelete = parseInt(this.$router.currentRoute.query.showDelete)
    this.isFromCRCUpload = !!this.$router.currentRoute.query.isFromCRCUpload
    this.visitTaskId = this.$router.currentRoute.query.visitTaskId
    this.page = this.$route.query.page
    // cornerstone.events.addEventListener('cornerstoneimageloaded', this.cornerstoneImageLoaded)
    this.getStudiesInfo()
    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()
    })
    workSpeedclose(true)
  },
  methods: {
    // 获取某个访视下所有的检查信息
    async getStudiesInfo() {
      this.studyList = []
      try {
        let res = null
        if (this.page === 'upload') {
          res = await getTaskUploadedDicomStudyList({ visitTaskId: this.visitTaskId })
        } else if (this.page === 'download') {
          res = await getVisitStudyList(this.trialId, this.subjectVisitId, this.isReading, this.visitTaskId)
        } else {
          res = await getVisitStudyList(this.trialId, this.subjectVisitId, this.isReading)
        }
        if (res.IsSuccess) {
          res.Result.forEach((study, studyIndex) => {
            const data = {}
            data.StudyId = study.StudyId
            data.StudyCode = study.StudyCode
            data.Modalities = study.Modalities
            data.SeriesCount = study.SeriesCount
            data.InstanceCount = study.InstanceCount
            data.InstanceCount = study.InstanceCount
            data.PreviewImageCount = 0
            var seriesList = []
            study.SeriesList.forEach((series, seriesIndex) => {
              const imageIds = []
              series.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}&idx=${studyIndex}|${seriesIndex}`)
                  }
                  i.ImageId = `wadouri:${localStorage.getItem('location') !== 'USA' ? this.OSSclientConfig.basePath : this.OSSclientConfig.basePath}${i.Path}?frame=0&instanceId=${i.Id}&idx=${studyIndex}|${seriesIndex}`
                  // imageIds.push(`${localStorage.getItem('location') !== 'USA' ? this.OSSclientConfig.basePath : this.OSSclientConfig.basePath}${i.Path}`)
                } else {
                  const imageId = `wadouri:${localStorage.getItem('location') !== 'USA' ? this.OSSclientConfig.basePath : this.OSSclientConfig.basePath}${i.Path}?instanceId=${i.Id}&idx=${studyIndex}|${seriesIndex}`
                  imageIds.push(imageId)
                  i.ImageId = imageId
                  // imageIds.push(`${localStorage.getItem('location') !== 'USA' ? this.OSSclientConfig.basePath : this.OSSclientConfig.basePath}${i.Path}`)
                }
              })
              seriesList.push({
                trialId: this.trialId,
                subjectVisitId: this.subjectVisitId,
                studyId: study.StudyId,
                imageIds: imageIds,
                instanceInfoList: series.InstanceInfoList,
                seriesId: series.Id,
                seriesUid: series.SeriesInstanceUid,
                seriesNumber: series.SeriesNumber,
                sliceThickness: series.SliceThickness,
                modality: series.Modality,
                description: series.Description,
                isReading: series.IsReading,
                isDeleted: series.IsDeleted,
                previewImageUrl: series.ImageResizePath ? this.OSSclientConfig.basePath + series.ImageResizePath : `/api/series/preview/${series.Id}`,
                instanceCount: series.InstanceCount,
                prefetchInstanceCount: 0,
                loadStatus: false,
                imageloadedArr: [],
                isExistMutiFrames: series.IsExistMutiFrames,
                isShowPopper: false,
                subjectCode: series.SubjectCode,
                visitName: series.VisitName
              })
            })
            data.SeriesList = seriesList
            this.studyList.push(data)
          })
          if (this.studyList.length > 0) {
            this.$refs.dicomViewer.loadImageStack(this.studyList[0].SeriesList[0])
            const imageId = this.studyList[0].SeriesList[0].imageIds[0]
            let instanceId = imageId.split('/')[imageId.split('/').length - 1]
            instanceId = instanceId.split('.')[0]
            this.firstInstanceId = instanceId
            this.activeNames = [this.studyList[0].StudyId]
            this.loadImages(this.studyList[0].SeriesList[0], 0)
          }
        }
      } catch (e) {
        console.log(e)
      }
    },

    loadImages(series, seriesIndex) {
      var priority = parseInt(new Date().getTime())
      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()
      }
    },
    showSeriesImage(e, studyIndex, seriesIndex, series) {
      this.activeSeriesId = series.seriesId
      workSpeedclose(true)
      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.studyList[studyIndex].SeriesList[seriesIndex])
      // if (!series.loadStatus) {
      //   requestPoolManager.changePriority(series.seriesId)
      // }
      if (!series.loadStatus) {
        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, 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(studyIndex, 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}&idx=${studyIndex}|${seriesIndex}`)
        }
      } else {
        imageIds.push(`wadouri:${localStorage.getItem('location') !== 'USA' ? this.OSSclientConfig.basePath : this.OSSclientConfig.basePath}${instanceInfo.Path}?instanceId=${instanceInfo.Id}&idx=${studyIndex}|${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,
        subjectCode: series.SubjectCode,
        visitName: series.VisitName
      }
      this.$refs.dicomViewer.loadImageStack(seriesInfo)
      if (!series.loadStatus) {
        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, 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)
        }
      }
    },
    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) {
        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) {
        this.loading = false
      }
    },
    async changeInstanceReadingStatus(callback, series, instance) {
      let statusStr = ''
      if (callback) {
        statusStr = this.$t('trials:audit:label:setSeriesReading')
        instance.IsReading = false
      } else {
        statusStr = this.$t('trials:audit:label:setSeriesNotReading')
        instance.IsReading = true
      }
      var message = this.$t('trials:audit:message:changeSeriesStatus').replace('xxx', statusStr)
      message = message.replace('yyy', this.$fd('YesOrNo', !instance.IsReading))
      const confirm = await this.$confirm(
        message,
        {
          type: 'warning',
          distinguishCancelAndClose: true
        }
      )
      if (confirm !== 'confirm') return
      const state = instance.IsReading ? 1 : 2
      this.loading = true
      try {
        const res = await setInstanceStatus(series.trialId, series.subjectVisitId, series.seriesId, instance.Id, state)
        this.loading = false
        if (res.IsSuccess) {
          instance.IsReading = !instance.IsReading
          this.$message.success(this.$t('common:message:savedSuccessfully'))
          window.opener.postMessage({ type: 'refreshSeriesList', data: '' }, window.location)
        }
      } catch (e) {
        this.loading = false
      }
    },
    async changeInstanceDeleteStatus(callback, series, instance) {
      let statusStr = ''
      if (callback) {
        statusStr = this.$t('trials:audit:label:setSeriesDeleted')
        instance.IsDeleted = false
      } else {
        statusStr = this.$t('trials:audit:label:setSeriesNotDelete')
        instance.IsDeleted = true
      }
      var message = this.$t('trials:audit:message:changeSeriesStatus').replace('xxx', statusStr)
      message = message.replace('yyy', this.$fd('YesOrNo', !instance.IsDeleted))
      const confirm = await this.$confirm(
        message,
        {
          type: 'warning',
          distinguishCancelAndClose: true
        }
      )
      if (confirm !== 'confirm') return

      const state = instance.IsDeleted ? 5 : 4
      this.loading = true
      try {
        const res = await setInstanceStatus(series.trialId, series.subjectVisitId, series.seriesId, instance.Id, state)
        this.loading = false
        if (res.IsSuccess) {
          instance.IsDeleted = !instance.IsDeleted
          this.$message.success(this.$t('common:message:savedSuccessfully'))
          window.opener.postMessage({ type: 'refreshSeriesList', data: '' }, window.location)
        }
      } catch (e) {
        this.loading = false
      }
    },
    popperClick(studyList, series) {
      for (let i = 0; i < studyList.length; i++) {
        for (let j = 0; j < studyList[i].SeriesList.length; j++) {
          if (studyList[i].SeriesList[j].isShowPopper) {
            studyList[i].SeriesList[j].isShowPopper = false
          }
        }
      }
      series.isShowPopper = !series.isShowPopper
    },
    // 切换关联检查Tab时获取关联检查信息
    async handleTabClick(tab, event) {
      if (tab.name === 'relation-study' && this.relationStudyList.length <= 0) {
        const loading = this.$loading({
          target: document.querySelector('.pane-relation-wrapper'),
          fullscreen: false,
          lock: true,
          text: 'Loading',
          background: 'rgb(49 49 49 / 50%)',
          spinner: 'el-icon-loading'
        })
        try {
          let params = {
            IsReading: !!this.isReading
          }
          const res = await getAllRelationStudyList(this.subjectVisitId, params)
          loading.close()
          this.relationStudyList = res.Result
          this.relationStudyListByVisitName = []
          res.Result.forEach(item => {
            let index = this.relationStudyListByVisitName.findIndex(d => d.VisitName === item.VisitName)
            if (index < 0) {
              this.relationStudyListByVisitName.push({
                VisitName: item.VisitName,
                series: [item]
              })
            } else {
              this.relationStudyListByVisitName[index].series.push(item)
            }
          })
        } catch (e) {
          console.log(e)
          loading.close()
        }
      }
    },
    handelRelationActiveChange(v) {
      var selectedId = v.length > 0 ? v[v.length - 1] : ''
      if (!selectedId) return
      var sIdx = this.relationStudyList.findIndex(study => study.StudyId === selectedId)
      if (sIdx > -1) {
        this.getRelationSeriesByStudy(selectedId, sIdx)
      }
    },
    // 根据关联检查获取序列信息
    async getRelationSeriesByStudy(studyId, index) {
      if (this.relationStudyList[index].seriesCount) {
        this.relationStudyList[index].showSeries = !this.relationStudyList[index].showSeries
        this.$forceUpdate()
      } else {
        const scope = this
        const loading = this.$loading({
          target: document.querySelector(`.relation-study-wrapper-${index}`),
          fullscreen: false,
          lock: true,
          text: 'Loading',
          background: 'rgb(49 49 49 / 50%)',
          spinner: 'el-icon-loading'
        })
        try {
          let isReading = !!this.isReading ? `?IsReading=true` : ''
          const data = await getSeriesList(`/series/list/${studyId}${isReading}`)
          loading.close()
          if (data.Result != null && data.Result.length > 0) {
            var seriesList = []
            const res = data.Result
            res.forEach((item, seriesIndex) => {
              const imageIds = []
              item.InstanceInfoList.forEach(i => {
                if (i.NumberOfFrames && i.NumberOfFrames > 1) {
                  for (let j = 0; j < i.NumberOfFrames; j++) {
                    if (!i.ImageId) {
                      i.ImageId = `wadouri:${localStorage.getItem('location') !== 'USA' ? scope.OSSclientConfig.basePath : scope.OSSclientConfig.basePath}${i.Path}?frame=${j}&instanceId=${i.Id}&idx=${index}|${seriesIndex}&isRelation=1`
                    }
                    imageIds.push(`wadouri:${localStorage.getItem('location') !== 'USA' ? scope.OSSclientConfig.basePath : scope.OSSclientConfig.basePath}${i.Path}?frame=${j}&instanceId=${i.Id}&idx=${index}|${seriesIndex}&isRelation=1`)
                  }
                } else {
                  if (!i.ImageId) {
                    i.ImageId = `wadouri:${localStorage.getItem('location') !== 'USA' ? scope.OSSclientConfig.basePath : scope.OSSclientConfig.basePath}${i.Path}?instanceId=${i.Id}&idx=${index}|${seriesIndex}&isRelation=1`
                  }
                  imageIds.push(`wadouri:${localStorage.getItem('location') !== 'USA' ? scope.OSSclientConfig.basePath : scope.OSSclientConfig.basePath}${i.Path}?instanceId=${i.Id}&idx=${index}|${seriesIndex}&isRelation=1`)
                }
              })
              seriesList.push({
                imageIds: imageIds,
                instanceInfoList: item.InstanceInfoList,
                seriesId: item.Id,
                seriesUid: item.SeriesInstanceUid,
                seriesNumber: item.SeriesNumber,
                sliceThickness: item.SliceThickness,
                modality: item.Modality,
                description: item.Description,
                previewImageUrl: item.ImageResizePath ? scope.OSSclientConfig.basePath + item.ImageResizePath : `/api/series/preview/${item.Id}`,
                instanceCount: item.InstanceCount,
                prefetchInstanceCount: 0,
                hasLabel: item.HasLabel,
                keySeries: item.KeySeries,
                loadStatus: false,
                imageloadedArr: [],
                isExistMutiFrames: item.IsExistMutiFrames,
                isShowPopper: false,
                subjectCode: item.SubjectCode,
                visitName: item.VisitName
              })
            })
            // scope.relationStudyList[index].seriesCount = seriesList.length
            // scope.relationStudyList[index].seriesList = seriesList
            // scope.relationStudyList[index].showSeries = true
            scope.$set(scope.relationStudyList[index], 'seriesCount', seriesList.length)
            scope.$set(scope.relationStudyList[index], 'seriesList', seriesList)
            scope.$set(scope.relationStudyList[index], 'showSeries', true)
            scope.$forceUpdate()
          }
        } catch (e) {
          loading.close()
        }
      }
    },
    showRelationSeriesImage(e, series, studyIndex, index) {
      this.activeSeriesId = series.seriesId
      workSpeedclose(true)
      this.currentRelationIndex = index
      const element = e.currentTarget
      const elements = document.querySelectorAll('[series-type]')
      Array.from(elements).forEach((e) => {
        e.classList.remove('viewerSideActive')
      })
      element.classList.add('viewerSideActive')
      this.$refs.dicomViewer.loadImageStack(series)
      if (!series.loadStatus) {
        var priority = parseInt(new Date().getTime())
        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()
        }
      }
    },
    loadAllImages() {
      var seriesList = this.studyList.map(s => s.SeriesList).flat()
      const seriesIndex = seriesList.findIndex(i => i.loadStatus === false)
      if (seriesIndex === -1) return
      const series = seriesList[seriesIndex]
      var priority = parseInt(new Date().getTime())
      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()
      }
      // requestPoolManager.setPendingList(imageIds)
    },
    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()
        this.imageList.map(image => {
          requestPoolManager.loadAndCacheImagePlus(image.imageId, image.seriesId, image.priority)
        })
        requestPoolManager.sortTaskPool()
        this.imageList = []
      }
    },
    datasetsCacheChanged(e) {
      const cacheInfo = e.detail.cacheInfo
      const cacheSizeInBytes = cacheInfo.cacheSizeInBytes
      if (cacheSizeInBytes >= maximumSizeInBytes) {
        // 清理缓存的影像
      }
    },
    cornerstoneimageloadprogress(e) {
      const imageId = e.detail.imageId
      if (!imageId) return
      const percentComplete = e.detail.percentComplete
      const params = {}
      const searchParams = new URLSearchParams(imageId.split('?')[1])
      if (!searchParams) return
      for (const [key, value] of searchParams.entries()) {
        params[key] = value
      }
      const studyIndex = params.idx.split('|')[0]
      const seriesIndex = params.idx.split('|')[1]
      var series = !params.isRelation ? this.studyList[studyIndex].SeriesList[seriesIndex] : this.relationStudyList[studyIndex].seriesList[seriesIndex]
      if (!series) return
      if (!this.activeSeriesId) {
        this.activeSeriesId = series.seriesId
      }
      var prefetchInstanceCount = series.prefetchInstanceCount
      var instanceCount = series.instanceCount
      if (series.imageloadedArr.indexOf(imageId) < 0) {
        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
        }
        series.prefetchInstanceCount = prefetchInstanceCount
        if (percentComplete >= 100) {
          series.imageloadedArr.push(imageId)
        }
      }
      let file = series.instanceInfoList.find(item => item.ImageId === imageId)
      if (file && this.activeSeriesId === series.seriesId) {
        getNetWorkSpeed()
        setNetWorkSpeedSize(percentComplete, e.detail.total, imageId)
      }
      if (prefetchInstanceCount >= instanceCount * 100) {
        series.prefetchInstanceCount = instanceCount * 100
        // 设置当前序列状态为已下载完成
        series.loadStatus = true
        if (!this.isFromCRCUpload) {
          this.loadAllImages()
        }
        workSpeedclose()
        localStorage.setItem("QCRiskControl", 1)
      }
    }
  }
}
</script>

<style>
.viewerContainer .el-tabs--border-card {
  background: none;
  border: none;
}

.viewerContainer .el-tabs__item {
  height: 35px;
  line-height: 35px;
  width: 100px;
  padding: 0 !important;
  text-align: center;
  transform: scale(.8);
}

.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: 220px;
  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 .text-desc {
  font-weight: bold;
  font-size: 13px;
  text-align: center;
  background: #585453;
  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: 220px;
  /* height: 84px; */
  padding: 1px 2px 1px 2px;
  margin: 2px 0 1px 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;
}

.viewerContainer .pane-relation-wrapper {
  min-height: 500px;
}

.viewerContainer .el-collapse {
  border: none;
}

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

}

.viewerContainer .el-collapse-item__content {
  padding-bottom: 5px;
  background-color: #2c2c2c !important;
  color: #ddd;
}

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

.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: 10px;
  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>
