<template>
  <div
    id="canvas"
    ref="canvas"
    v-loading="loading"
    element-loading-text="Loading..."
    element-loading-background="rgba(0, 0, 0, 0.8)"
    style="position:relative;"
    class="cornerstone-element"
    @mouseup="sliderMouseup"
    @contextmenu.prevent="onContextmenu"
  >
    <!-- 临床数据 -->
    <div v-if="stack.isExistsClinicalData" class="info-cd" @click.stop="handleViewCD($event)">
      <el-tooltip class="item" effect="dark" :content="$t('trials:reading:button:clinicalData')" placement="bottom">
        <svg-icon icon-class="documentation" class="svg-icon" />
      </el-tooltip>

    </div>
    <!-- 切换访视 -->
    <div
      v-if="stack.imageRendered && isReadingTaskViewInOrder === 1"
      class="info-visit"
      @dblclick.stop="preventDefault($event)"
    >
      <div
        class="arrw_div_wrapper"
        :style="{cursor:stack.visitTaskNum <= minVistNum?'not-allowed':'pointer',color:stack.visitTaskNum <= minVistNum?'#888':'#fff'}"
        @click.stop.prevent="toggleSeries($event,-1)"
        @dblclick.stop="preventDefault($event)"
      >
        <i class="el-icon-caret-left" />
      </div>
      <div class="blind_name_wrapper">
        {{ stack.taskBlindName }}
      </div>
      <div
        class="arrw_div_wrapper"
        :style="{cursor:stack.visitTaskNum >= maxVistNum?'not-allowed':'pointer',color:stack.visitTaskNum >= maxVistNum?'#888':'#fff'}"
        @click.stop.prevent="toggleSeries($event,1)"
        @dblclick.stop="preventDefault($event)"
      >
        <i class="el-icon-caret-right" />
      </div>
    </div>
    <div class="info-series">
      <h2 v-if="isReadingShowSubjectInfo" style="color:#f44336;padding: 5px 0px;margin: 0;">{{ subjectCode }} {{ stack.taskBlindName }}</h2>
      <div v-show="dicomInfo.series">Series: #{{ dicomInfo.series }}</div>
      <div>Image: #{{ dicomInfo.frame }}</div>
      <div>{{ dicomInfo.modality }}</div>
    </div>
    <div class="info-image">
      <div v-show="mousePosition.mo">
        Pos: {{ mousePosition.x?mousePosition.x.toFixed(0):'' }}, {{ mousePosition.y?mousePosition.y.toFixed(0):'' }}
      </div>
      <div v-if="(dicomInfo.modality === 'CT' || dicomInfo.modality === 'DR' || dicomInfo.modality === 'CR') && mousePosition.mo">
        HU: {{ mousePosition.mo }}
      </div>
      <div v-else-if="(dicomInfo.modality === 'PT' && mousePosition.suv)">
        SUVbw(g/ml): {{ digitPlaces === -1 ?mousePosition.suv.toFixed(3) :mousePosition.suv.toFixed(digitPlaces) }}
      </div>
      <div v-else-if="mousePosition.mo">
        Density: {{ mousePosition.mo }}
      </div>
      <div>
        W*H: {{ dicomInfo.size }}
        <!-- <span v-show="dicomInfo.pixel">{{ dicomInfo.pixel }}mm</span> -->
      </div>

      <div>Zoom: {{ dicomInfo.zoom }}</div>

      <!-- <div v-show="toolState.clipPlaying">FPS {{ dicomInfo.fps }}</div> -->
    </div>

    <div class="info-subject">
      <div>{{ stack.description }}</div>
      <!-- <div>{{ dicomInfo.hospital }}</div> -->
      <!-- <div v-show="dicomInfo.pid">{{ dicomInfo.pid }}</div> -->
      <!-- <div>{{ subjectCode }}</div> -->
      <!-- <div>{{ dicomInfo.sex }} {{ dicomInfo.age }}</div> -->
      <!-- <div v-show="dicomInfo.acc">ACC {{ dicomInfo.acc }}</div> -->
      <!-- <div>{{ dicomInfo.time }}</div> -->
    </div>
    <div ref="sliderBox" class="my_slider_box" style="position: absolute;right: 1px;height: calc(100% - 140px);transform: translateY(-50%);top: calc(50% - 30px);width: 10px;background: #333;cursor: pointer" @click.stop="goViewer($event)">
      <div :style="{top: height + '%'}" style="z-index:10;background: #9e9e9e;height: 20px;width: 100%;position: absolute;top: 0;cursor: move" @click.stop.prevent="() => {return}" @mousedown.stop="sliderMousedown($event)" />
    </div>
    <div style="position: absolute;left: 50%;top: 30px;color: #f44336;transform: translateX(-50%);">
      {{ markers.top }}
    </div>
    <div style="position: absolute;top: 50%;right: 15px;color: #f44336;transform: translateY(-50%);">
      {{ markers.right }}
    </div>

    <div style="position: absolute;left: 50%;bottom: 15px;color: #f44336;transform: translateX(-50%);">
      {{ markers.bottom }}
    </div>
    <div style="position: absolute;top: 50%;left: 15px;color: #f44336;transform: translateY(-50%);">
      {{ markers.left }}
    </div>

    <div class="info-instance">
      <div v-if="dicomInfo.location">Location: {{ `${Number(dicomInfo.location).toFixed(digitPlaces)} mm` }}</div>
      <div v-show="dicomInfo.thick">Slice Thickness: {{ `${dicomInfo.thick} mm` }}</div>
      <div v-show="dicomInfo.wwwc">WW/WL: {{ dicomInfo.wwwc }}</div>
    </div>

    <!-- <div
      v-show="mousePosition.mo"
      class="msg-div"
      :style="{
        top: mousePosition.y+ 'px',
        left: mousePosition.x+ 'px',
      }"
    >
      <span>{{ mousePosition.mo }} ({{ parseInt(mousePosition.x) }},{{ parseInt(mousePosition.y) }})</span>
    </div> -->
  </div>
</template>
<style>
.my_slider_box:after{
  content: '';
  position: absolute;
  bottom: -20px;
  left: 0;
  height: 20px;
  width: 100%;
  background: #333;
}
</style>
<script>
// import { splitLesion } from '@/api/trials'
// import requestPoolManager from '@/utils/request-pool'
import DicomEvent from './DicomEvent'
import Vue from 'vue'
import { mapGetters } from 'vuex'
import Contextmenu from 'vue-contextmenujs'
Vue.use(Contextmenu)
import * as cornerstone from 'cornerstone-core'
import metaDataProvider from '@/utils/metaDataProvider'
cornerstone.metaData.addProvider(metaDataProvider, { priority: 10 });
import * as cornerstoneMath from 'cornerstone-math'
import * as cornerstoneTools from 'cornerstone-tools'
const scroll = cornerstoneTools.import('util/scrollToIndex')
const getHandleNearImagePoint = cornerstoneTools.import('manipulators/getHandleNearImagePoint')
// import getHandleNearImagePoint from './../../../manipulators/getHandleNearImagePoint.js';
import Hammer from 'hammerjs'
import LengthTool from '@/views/trials/trials-panel/reading/dicoms/tools/Length/LengthTool'
import BidirectionalTool from '@/views/trials/trials-panel/reading/dicoms/tools/Bidirectional/BidirectionalTool'
import ArrowAnnotateTool from '@/views/trials/trials-panel/reading/dicoms/tools/ArrowAnnotate/ArrowAnnotateTool'
import RectangleRoiTool from '@/views/trials/trials-panel/reading/dicoms/tools/RectangleRoi/RectangleRoiTool'
import ProbeTool from '@/views/trials/trials-panel/reading/dicoms/tools/Probe/ProbeTool'
// import OrientationMarkersTool from '@/views/trials/trials-panel/reading/dicoms/tools/OrientationMarkers/OrientationMarkersTool'
import ScaleOverlayTool from '@/views/trials/trials-panel/reading/dicoms/tools/ScaleOverlay/ScaleOverlayTool'
import getOrientationString from '@/views/trials/trials-panel/reading/dicoms/tools/OrientationMarkers/getOrientationString'
import invertOrientationString from '@/views/trials/trials-panel/reading/dicoms/tools/OrientationMarkers/invertOrientationString'
// import calculateLongestAndShortestDiameters from '@/views/trials/trials-panel/reading/dicoms/tools/Bidirectional/calculateLongestAndShortestDiameters'
import calculateSUV from '@/views/trials/trials-panel/reading/dicoms/tools/calculateSUV'
// import { ProbeTool } from '@cornerstonejs/tools'
cornerstoneTools.external.cornerstone = cornerstone
cornerstoneTools.external.Hammer = Hammer
cornerstoneTools.external.cornerstoneMath = cornerstoneMath
cornerstoneTools.toolStyle.setToolWidth(1)
cornerstoneTools.toolColors.setToolColor('rgb(255, 0, 0)')
cornerstoneTools.toolColors.setActiveColor('rgb(0, 255, 0)')
cornerstoneTools.store.state.deleteIfHandleOutsideImage = false
// cornerstoneTools.init({ globalToolSyncEnabled: true })
cornerstoneTools.init()
export default {
  name: 'DicomCanvas',
  props: {
    isScrollSync: {
      type: Boolean,
      required: true
    },
    canvasIndex: {
      type: Number,
      required: true
    },
    currentDicomCanvasIndex: {
      type: Number,
      required: true
    },
    isReadingShowSubjectInfo: {
      type: Boolean,
      required: true
    },
    isReadingTaskViewInOrder: {
      type: Number,
      required: true
    },
    customWwcTpl: {
      type: Array,
      default() {
        return []
      }
    }
    // isCurrentTask: {
    //   type: Boolean,
    //   required: true
    // },
    // isBaseline: {
    //   type: Boolean,
    //   required: true
    // },
    // readingTaskState: {
    //   type: Number,
    //   required: true
    // }
  },
  data() {
    return {
      loading: false,
      canvas: {},
      index: 0,
      height: 0,
      cornerstoneStyle: {},
      stack: {
        studyId: '',
        seriesId: '',
        instanceId: '',
        seriesNumber: '',
        imageIds: [],
        currentImageIdIndex: 0,
        firstImageLoading: false,
        visitTaskId: '',
        taskBlindName: '',
        frame: null,
        imageRendered: false,
        isExistsClinicalData: false,
        isExistMutiFrames: false
        // preventCache: true
      },
      dicomInfo: {
        hospital: '',
        pid: '',
        name: '',
        sex: '',
        age: '',
        acc: '',
        modality: '',
        time: '',
        series: '',
        frame: '',
        size: '',
        pixel: 0,
        thick: 0,
        wwwc: '',
        zoom: 0,
        location: '',
        fps: 5
      },
      toolState: {
        initialized: false,
        activeTool: 'none',
        dicomInfoVisible: false,
        clipPlaying: false,
        viewportInvert: false
      },
      loadImagePromise: null,
      AnnotationSync: null,
      allROIToolData: {},
      type: '',
      series: '',
      ToolStateManager: null,
      renderedMeasured: [],
      measuredTools: ['Length', 'Bidirectional', 'ArrowAnnotate', 'RectangleRoi'],
      measureData: [],
      selectedLesion: null,
      activeTool: 0, // 0:enable  1:passive  2:active
      activeToolName: '',
      isCurrentTask: false,
      isBaseline: false,
      readingTaskState: 2,
      image: null,
      CriterionType: 0,
      digitPlaces: 2,
      sliderInfo: {
        oldB: null,
        oldM: null,
        isMove: false
      },
      oldPosition: {},
      subjectCode: '',
      isMsg: false,
      mousePosition: { x: '', y: '', mo: '' },
      orientationMarkers: [],
      originalMarkers: [],
      imageId: '',
      markers: { top: '', right: '', bottom: '', left: '' },
      maxVistNum: 0,
      minVistNum: 0,
      isFirstLoadIns: false,
      isFirstChangeTask: false,
      disabledMarks: [],
      wwwcArrIdx: 0,
      wwwcArr: [],
      defaultWwwc: [
        { label: 'CT Brain', wc: 40, ww: 80 },
        { label: 'CT Lungs', wc: -400, ww: 1500 },
        { label: 'CT Abdomen', wc: 60, ww: 400 },
        { label: 'CT Liver', wc: 40, ww: 400 },
        { label: 'CT Bone', wc: 300, ww: 1500 }

      ],
      scrollSyncInfo: { offset: 0 },
      hideMeasureArr: []

    }
  },
  computed: {
    ...mapGetters(['visitTaskList', 'currentReadingTaskState'])
  },
  watch: {
    currentReadingTaskState: {
      immediate: true,
      handler(val) {
        if (val === 2) {
          this.activeTool = 0
        }
        this.readingTaskState = val
        var canvas = this.$refs.canvas
        var enabledElement = null
        if (canvas) {
          enabledElement = cornerstone.getEnabledElement(canvas)
        }
        if (canvas && enabledElement) {
          cornerstone.updateImage(canvas, true)
        }
      }
    },
    customWwcTpl: {
      immediate: true,
      handler(val) {
        this.wwwcArr = [...this.defaultWwwc, ...val]
      }
    }
  },

  mounted() {
    console.log(cornerstoneTools)
    // this.subjectCode = this.$router.currentRoute.query.subjectCode
    this.subjectCode = localStorage.getItem('subjectCode')
    document.addEventListener('mouseup', () => {
      this.sliderMouseup()
    })
    document.addEventListener('mousemove', (e) => {
      this.sliderMousemove(e)
    })
    var digitPlaces = Number(localStorage.getItem('digitPlaces'))
    this.digitPlaces = digitPlaces === -1 ? this.digitPlaces : digitPlaces
    this.type = this.$router.currentRoute.query.type ? this.$router.currentRoute.query.type : ''
    this.CriterionType = parseInt(localStorage.getItem('CriterionType'))
    this.canvas = this.$refs.canvas
    this.canvas.addEventListener('dblclick', e => {
      this.dbclick(e)
    })
    this.canvas.addEventListener('cornerstonenewimage', this.onNewImage)
    this.canvas.addEventListener(
      'cornerstoneimagerendered',
      this.onImageRendered
    )
    this.canvas.addEventListener(
      'cornerstoneimageloaded',
      this.onImageLoaded
    )

    this.canvas.addEventListener(
      'cornerstonetoolsclipstopped',
      this.onClipStopped
    )
    this.canvas.addEventListener(
      'cornerstonetoolsmeasurementcompleted',
      this.onMeasurementcompleted
    )
    const debouncedCallback = this.debounce((evt) => {
      this.onMeasurementmodified(evt)
    }, 100)
    this.canvas.addEventListener(
      'cornerstonetoolsmeasurementmodified',
      (evt) => {
        debouncedCallback(evt)
      }
    )

    this.canvas.addEventListener(
      'cornerstonetoolsmeasurementremoved',
      this.onMeasurementremoved
    )
    // EVENTS.MOUSE_UP
    this.canvas.addEventListener('cornerstonetoolsmouseup', this.mouseUp)
    this.canvas.addEventListener('cornerstonetoolsmousedown', this.mouseDown)
    this.canvas.addEventListener('cornerstonetoolsmouseclick', this.mouseClick)
    // this.canvas.addEventListener('click', this.cotextMenuClick)
    this.canvas.addEventListener('cornerstonetoolsstackscroll', this.stackScrollCallback)
    this.canvas.addEventListener('cornerstonetoolsmousemove', this.mouseMove)
    this.canvas.addEventListener('mouseleave', () => {
      this.mousePosition.mo = ''
    })
    DicomEvent.$on('setReadingState', readingTaskState => {
      if (readingTaskState === 2) {
        this.activeTool = 0
      }
      this.readingTaskState = readingTaskState
      cornerstone.updateImage(this.canvas, true)
    })

    // this.canvas.addEventListener('keydown', event => {
    //   event.preventDefault()
    //   if (this.canvasIndex !== this.currentDicomCanvasIndex) return
    //   var idx = this.hotKeyList.findIndex(i => i.code === event.code && i.ctrlKey === event.ctrlKey && i.shiftKey === event.shiftKey && i.altKey === event.altKey)
    //   if (idx === -1) return

    //   var shortcutKeyEnum = this.hotKeyList[idx].shortcutKeyEnum
    //   if (shortcutKeyEnum === 1) {
    //     // 前一图像视口
    //     this.$parent.selectViewCanvas(-1)
    //   } else if (shortcutKeyEnum === 2) {
    //     // 后一图像视口
    //     this.$parent.selectViewCanvas(1)
    //   } else if (shortcutKeyEnum === 3) {
    //     // 上一个序列
    //     const series = this.series
    //     DicomEvent.$emit('selectSeries', { seriesId: series.seriesId, studyId: series.studyId, offset: -1 })
    //   } else if (shortcutKeyEnum === 4) {
    //     // 下一个序列
    //     const series = this.series
    //     DicomEvent.$emit('selectSeries', { seriesId: series.seriesId, studyId: series.studyId, offset: 1 })
    //   } else if (shortcutKeyEnum === 5) {
    //     // 上一张图像
    //     this.scrollPage(-1)
    //   } else if (shortcutKeyEnum === 6) {
    //     // 下一张图像
    //     this.scrollPage(1)
    //   } else if (shortcutKeyEnum === 7) {
    //     // 向左旋转
    //     this.setRotate(false, false, -90, 4)
    //   } else if (shortcutKeyEnum === 8) {
    //     // 向右旋转
    //     this.setRotate(false, false, 90, 5)
    //   } else if (shortcutKeyEnum === 9) {
    //     // 水平翻转
    //     this.setRotate(false, true, 0, 3)
    //   } else if (shortcutKeyEnum === 10) {
    //     // 垂直翻转
    //     this.setRotate(true, false, 0, 2)
    //   } else if (shortcutKeyEnum === 11) {
    //     // 放大
    //     this.setZoomScale(1)
    //   } else if (shortcutKeyEnum === 12) {
    //     // 缩小
    //     this.setZoomScale(0)
    //   } else if (shortcutKeyEnum === 13) {
    //     // 适应图像
    //     this.fitToImage()
    //   } else if (shortcutKeyEnum === 14) {
    //     // 适应窗口
    //     this.fitToWindow()
    //   } else if (shortcutKeyEnum === 15) {
    //     // 截图
    //     this.saveImage()
    //   } else if (shortcutKeyEnum === 16) {
    //     // 反色
    //     this.toggleInvert()
    //   } else if (shortcutKeyEnum === 17) {
    //     // 窗宽/窗位
    //     var wwwcArrIdx = this.wwwcArrIdx
    //     var wwwcArr = this.wwwcArr
    //     if (wwwcArrIdx + 1 === wwwcArr.length) {
    //       this.wwwcArrIdx = 0
    //     } else {
    //       ++this.wwwcArrIdx
    //     }
    //     this.setWwwc(this.wwwcArr[wwwcArrIdx].ww, this.wwwcArr[wwwcArrIdx].wc)
    //   } else if (shortcutKeyEnum === 18) {
    //     // 重置
    //     this.resetViewport()
    //   }
    // })
  },
  beforeDestroy() {
    // Store.$off('getMeasureData')
    DicomEvent.$off('setReadingState')
  },
  methods: {
    goViewer(e) {
      // console.log(this.$refs['sliderBox'].clientHeight)
      var height = e.offsetY * 100 / this.$refs['sliderBox'].clientHeight
      this.height = height
      var index = Math.trunc(this.stack.imageIds.length * this.height / 100)
      scroll(this.canvas, index)
    },
    dbclick(e) {
      this.$emit('setCornerstoneStyle')
      this.preventDefault(e)
    },
    setZoomScale(type) {
      const viewport = cornerstone.getViewport(this.canvas)
      const pow = 1.7
      const oldFactor = Math.log(viewport.scale) / Math.log(pow)
      const factor = type > 0 ? oldFactor + 1 : oldFactor - 1
      const scale = Math.pow(pow, factor)
      var minScale = 0.25
      var maxScale = 20.0
      if (maxScale && scale > maxScale) {
        viewport.scale = maxScale
      } else if (minScale && scale < minScale) {
        viewport.scale = minScale
      } else {
        viewport.scale = scale
      }
      cornerstone.setViewport(this.canvas, viewport)
    },
    reloadCanvas() {
      cornerstone.resize(this.canvas)
    },
    mouseMove(e) {
      const { element, image, currentPoints } = e.detail
      const x = Math.round(currentPoints.image.x)
      const y = Math.round(currentPoints.image.y)

      const stats = {}

      if (x >= 0 && y >= 0 && x < image.columns && y < image.rows) {
        stats.x = x
        stats.y = y

        if (image.color) {
          stats.storedPixels = this.getRGBPixels(element, x, y, 1, 1)
        } else {
          stats.storedPixels = cornerstone.getStoredPixels(
            element,
            x,
            y,
            1,
            1
          )
          stats.sp = stats.storedPixels[0]
          stats.mo = stats.sp * image.slope + image.intercept
          stats.suv = calculateSUV(image, stats.sp)
        }
      }

      this.mousePosition.x = currentPoints.image.x + 1
      this.mousePosition.y = currentPoints.image.y + 1
      this.mousePosition.mo = stats.mo
      this.mousePosition.suv = stats.suv
      if ((this.isFirstChangeTask || this.disabledMarks.length > 0) && this.pointNearTool(e)) {
        e.stopImmediatePropagation()
        e.stopPropagation()
        e.preventDefault()
      }
    },

    mouseUp(e) {
      // console.log('mouseUp')
      if (this.readingTaskState >= 2) return
      this.image = e.detail.image
      this.getToolStateInfo(e)
    },
    mouseDown(e) {
      this.image = e.detail.image
      var pointNearTool = this.pointNearTool(e)
      if ((this.isFirstChangeTask || this.disabledMarks.length > 0) && pointNearTool) {
        e.stopImmediatePropagation()
        e.stopPropagation()
        e.preventDefault()
      } else if (this.activeToolName === 'Length' || this.activeToolName === 'Bidirectional' && this.readingTaskState < 2) {
        console.log(e.detail.image)
        if (!e.detail.image.columnPixelSpacing || !e.detail.image.rowPixelSpacing) {
          // '该影像不具备测量长度所需的必要数据，不能进行长度测量。请选择其他工具进行标注。'
          this.$confirm(this.$t('trials:reading:warnning:msg56'), '', {
            showCancelButton: false,
            type: 'warning'
          }).then(() => {

          }).catch(() => {})
          e.stopImmediatePropagation()
          e.stopPropagation()
          e.preventDefault()
        }
      }
    },
    pointNearTool(e) {
      const { element, image, currentPoints } = e.detail
      const ToolStateManager = cornerstoneTools.globalImageIdSpecificToolStateManager
      for (var m = 0; m < this.measuredTools.length; m++) {
        var toolType = this.measuredTools[m]
        const toolState = ToolStateManager.getImageIdToolState(image.imageId, toolType)
        if (toolState) {
          var toolObj = new cornerstoneTools[`${toolType}Tool`]()
          var i = toolState.data.findIndex(data => toolObj.pointNearTool(element, data, currentPoints.canvas, 'mouse'))
          if (i > -1 && this.disabledMarks.length > 0 && this.disabledMarks.indexOf(toolState.data[i].remark) > -1) {
            return true
          } else {
            i = toolState.data.findIndex(data => getHandleNearImagePoint(element, data.handles, currentPoints.canvas))
            if (i > -1 && this.disabledMarks.length > 0 && this.disabledMarks.indexOf(toolState.data[i].remark) > -1) {
              return true
            }
          }
        }
      }
      return false
    },
    getDisabledMarks(measureDatas) {
      var arr = []
      measureDatas.map(i => {
        if ((i.LesionType === 0 || i.LesionType === 1 || i.LesionType === 7) && i.IsFirstChangeTask) {
          arr.push(i.OrderMarkName)
        }
      })
      return arr
    },
    getMergeMarks(measureDatas) {
      var arr = []
      measureDatas.map(i => {
        if ((i.LesionType === 0) && i.SplitOrMergeType === 1) {
          arr.push(i.OrderMarkName)
        }
      })
      return arr
    },
    getRGBPixels(element, x, y, width, height) {
      if (!element) {
        return
      }
      x = Math.round(x)
      y = Math.round(y)
      const enabledElement = cornerstone.getEnabledElement(element)
      const storedPixelData = []
      let index = 0
      const pixelData = enabledElement.image.getPixelData()
      let spIndex, row, column

      if (enabledElement.image.color) {
        for (row = 0; row < height; row++) {
          for (column = 0; column < width; column++) {
            spIndex = ((row + y) * enabledElement.image.columns + (column + x)) * 4
            const red = pixelData[spIndex]
            const green = pixelData[spIndex + 1]
            const blue = pixelData[spIndex + 2]
            const alpha = pixelData[spIndex + 3]

            storedPixelData[index++] = red
            storedPixelData[index++] = green
            storedPixelData[index++] = blue
            storedPixelData[index++] = alpha
          }
        }
      }

      return storedPixelData
    },
    sliderMousedown(e) {
      var boxHeight = this.$refs['sliderBox'].clientHeight
      this.sliderInfo.oldB = parseInt(e.srcElement.style.top) * boxHeight / 100
      this.sliderInfo.oldM = e.clientY
      this.sliderInfo.isMove = true
      e.stopImmediatePropagation()
      e.stopPropagation()
      e.preventDefault()
    },
    sliderMousemove(e) {
      if (!this.sliderInfo.isMove) return
      console.log('sliderMousemove')
      var PX = this.sliderInfo.oldB - (this.sliderInfo.oldM - e.clientY)
      var boxHeight = this.$refs['sliderBox'].clientHeight
      if (PX < 0) return
      if (PX > boxHeight) return
      var height = PX * 100 / boxHeight
      var index = Math.trunc(this.stack.imageIds.length * height / 100)
      index = index > this.stack.imageIds.length ? this.stack.imageIds.length : index < 0 ? 0 : index
      // if (!cornerstone.imageCache.getImageLoadObject(this.stack.imageIds[index])) return
      this.height = height
      if (this.stack.currentImageIdIndex !== index) {
        scroll(this.canvas, index)
      }
    },
    sliderMouseup(e) {
      this.sliderInfo.isMove = false
    },
    getMeasureData() {
      // console.log('getMeasureData')
      var idx = this.visitTaskList.findIndex(i => i.VisitTaskId === this.stack.visitTaskId)
      this.measureData = this.visitTaskList[idx].MeasureData
      const ToolStateManager = cornerstoneTools.globalImageIdSpecificToolStateManager
      const imageId = this.stack.imageIds[this.stack.currentImageIdIndex]
      ToolStateManager.clearImageIdToolState(imageId)
      cornerstone.updateImage(this.canvas, true)
      var criterionType = parseInt(localStorage.getItem('CriterionType'))
      if (this.isFirstChangeTask) {
        this.disabledMarks = this.getDisabledMarks(this.visitTaskList[idx].MeasureData)
      } else if (criterionType === 2) {
        this.disabledMarks = this.getMergeMarks(this.visitTaskList[idx].MeasureData)
      } else {
        this.disabledMarks = []
      }
      return true
    },
    onContextmenu(event) {
      event.preventDefault()
      // if (this.isBaseline || this.readingTaskState >= 2 || this.CriterionType === 10) return false
      // const x = event.offsetX
      // const y = event.offsetY
      // const ToolStateManager = cornerstoneTools.globalImageIdSpecificToolStateManager

      // var element = cornerstone.getEnabledElement(this.canvas)
      // var { imageId } = element.image
      // this.measuredTools.map(toolType => {
      //   const toolState = ToolStateManager.getImageIdToolState(imageId, toolType)
      //   if (!toolState) return
      //   var toolObj = new cornerstoneTools[`${toolType}Tool`]()

      //   var i = toolState.data.findIndex(data => toolObj.pointNearTool(this.canvas, data, { x, y }, 'mouse'))
      //   if (i === -1) return false
      //   var idx = this.measureData.findIndex(item => item.MeasureData && item.MeasureData.data && item.MeasureData.data.uuid === toolState.data[i].uuid)
      //   var rowId = null
      //   if (idx > -1) {
      //     rowId = this.measureData[idx].RowId
      //   }
      //   if (rowId) {
      //     this.selectedLesion = toolState.data[i]
      //     this.$contextmenu({
      //       items: [
      //         // {
      //         //   label: 'Split',
      //         //   divided: true,
      //         //   onClick: () => {
      //         //     this.handleSplit()
      //         //   }
      //         // }
      //       ],
      //       event,
      //       x: event.clientX,
      //       y: event.clientY,
      //       customClass: 'class-a',
      //       zIndex: 3,
      //       minWidth: 100
      //     })
      //     return false
      //   } else {
      //     return false
      //   }
      // })
    },
    handleSplit() {
      var idx = this.measureData.findIndex(item => item.MeasureData && item.MeasureData.data && item.MeasureData.data.uuid === this.selectedLesion.uuid)
      if (idx > -1) {
        // const loading = this.$loading({ fullscreen: true })
        // var params = {
        //   visitTaskId: this.stack.visitTaskId,
        //   questionId: this.measureData[idx].QuestionId,
        //   rowId: this.measureData[idx].RowId
        // }
        DicomEvent.$emit('split', this.measureData[idx])
        // splitLesion(params).then(res => {
        //   loading.close()
        //   DicomEvent.$emit('refreshVisitList')
        // })
      }
    },
    getToolStateInfo(e) {
      const { element, currentPoints, image, viewport } = e.detail
      var imageId = image.imageId
      const imageInfo = this.getInstanceInfo(imageId)
      var instanceId = imageInfo.instanceId
      var frame = imageInfo.frame
      this.stack.frame = this.stack.isExistMutiFrames ? parseInt(frame) : null
      const ToolStateManager = cornerstoneTools.globalImageIdSpecificToolStateManager
      for (var m = 0; m < this.measuredTools.length; m++) {
        var toolType = this.measuredTools[m]
        const toolState = ToolStateManager.getImageIdToolState(e.detail.image.imageId, toolType)
        if (toolState) {
          var toolObj = new cornerstoneTools[`${toolType}Tool`]()

          var i = toolState.data.findIndex(data => toolObj.pointNearTool(element, data, currentPoints.canvas, 'mouse'))
          if (i > -1) {
            const measureData = {}
            if (toolType === 'Bidirectional') {
              // const {
              //   longestDiameter,
              //   shortestDiameter
              // } = calculateLongestAndShortestDiameters(toolState.data[i], image, this.digitPlaces)
              // toolState.data[i].longestDiameter = longestDiameter
              // toolState.data[i].shortestDiameter = shortestDiameter
            } else if (toolType === 'Length') {
              // toolState.data[i].length = this.calculateLenth(toolState.data[i])
            }
            measureData.studyId = this.stack.studyId
            measureData.seriesId = this.stack.seriesId
            measureData.instanceId = instanceId
            measureData.frame = this.stack.frame ? this.stack.frame : 0
            measureData.data = toolState.data[i]
            measureData.type = toolType
            measureData.thick = this.dicomInfo.thick
            measureData.location = this.dicomInfo.location
            var uuid = toolState.data[i].uuid
            var idx = this.measureData.findIndex(item => item.MeasureData && item.MeasureData.data && item.MeasureData.data.uuid === uuid)
            if (idx > -1) {
              var markName = this.measureData[idx].OrderMarkName
              if (this.disabledMarks.indexOf(markName) === -1 || !this.disabledMarks) {
                measureData.ww = Math.round(viewport.voi.windowWidth)
                measureData.wc = Math.round(viewport.voi.windowCenter)
                var questionInfo = this.measureData[idx]
                // const canvas = this.canvas.querySelector('canvas')
                // measureData.pictureBaseStr = canvas.toDataURL('image/png', 1)
                measureData.data.active = false
                this.$emit('modifyMeasureData', { measureData, questionInfo })
                // e.stopImmediatePropagation()
                // e.stopPropagation()
                // e.preventDefault()
                return
              } else {
                // e.stopImmediatePropagation()
                // e.stopPropagation()
                // e.preventDefault()
                return
              }
            }
          }
        }
      }
    },
    stackScrollCallback(e) {
      // console.log('stackScrollCallback')
      const { detail } = e
      if (this.isScrollSync && this.currentDicomCanvasIndex === this.canvasIndex) {
        this.scrollSyncInfo.canvasIndex = this.canvasIndex
        this.scrollSyncInfo.offset = this.scrollSyncInfo.offset + detail.direction
      }
      this.stack.currentImageIdIndex = e.detail.newImageIdIndex
      this.stack.imageIdIndex = e.detail.newImageIdIndex
      this.series.imageIdIndex = e.detail.newImageIdIndex
      this.height = (this.stack.currentImageIdIndex) * 100 / (this.stack.imageIds.length - 1)
      // this.height = (this.stack.currentImageIdIndex) * 100 / (this.stack.imageIds.length - 1)
      // var priority = new Date(new Date().setHours(23, 59, 59, 999)).getTime()

      // requestPoolManager.loadAndCacheImagePlus(this.stack.imageIds[this.stack.currentImageIdIndex], this.stack.seriesId, priority)
      //   .then(image => {

      //     // 判断该序列是否下载完成
      //     // var isLoaded = this.getSeriesLoadStatus()
      //     // if (isLoaded === 0 || isLoaded === 1) {
      //     //   var maxStep = 5
      //     //   var index = e.detail.newImageIdIndex

      //     //   var frontLoadImage = this.stack.imageIds.slice(index <= maxStep ? 0 : index - maxStep, index <= maxStep ? index : maxStep)
      //     //   var rearLoadImage = this.stack.imageIds.slice(index + 1, index + maxStep)

      //     //   const priority = new Date(new Date().setHours(23, 59, 59, 999)).getTime()
      //     //   if (detail.direction === -1) {
      //     //     // 往前滚动
      //     //     console.log('往前滚动')
      //     //     for (let i = frontLoadImage - 1; i >= 0; i--) {
      //     //       requestPoolManager.loadAndCacheImagePlus(frontLoadImage[i], this.stack.seriesId, priority - 1)
      //     //     }
      //     //     for (let i = 0; i < rearLoadImage.length; i++) {
      //     //       requestPoolManager.loadAndCacheImagePlus(rearLoadImage[i], this.stack.seriesId, priority - 1)
      //     //     }
      //     //   }
      //     //   if (detail.direction === 1) {
      //     //     // 往后滚动
      //     //     console.log('往后滚动')
      //     //     for (let i = rearLoadImage - 1; i >= 0; i--) {
      //     //       requestPoolManager.loadAndCacheImagePlus(rearLoadImage[i], this.stack.seriesId, priority - 1)
      //     //     }
      //     //     for (let i = frontLoadImage - 1; i >= 0; i--) {
      //     //       requestPoolManager.loadAndCacheImagePlus(frontLoadImage[i], this.stack.seriesId, priority - 1)
      //     //     }
      //     //   }
      //     // }
      //   })
      //   .catch((error) => {
      //     console.log(error)
      //   })
    },
    getSeriesLoadStatus() {
      var status = -1
      var idx = this.visitTaskList.findIndex(i => i.VisitTaskId === this.stack.visitTaskId)
      if (idx === -1) return status
      var studyList = this.visitTaskList[idx].StudyList
      var studyIdx = studyList.findIndex(study => study.StudyId === this.stack.studyId)
      if (studyIdx === -1) return status
      var seriesList = studyList[studyIdx].SeriesList
      var seriesIdx = seriesList.findIndex(series => series.seriesId === this.stack.seriesId)
      if (seriesIdx === -1) return status
      return seriesList[seriesIdx].loadStatus ? 1 : 0
    },
    renderMeasuredData(e) {
      var idx = this.visitTaskList.findIndex(i => i.VisitTaskId === this.stack.visitTaskId)
      if (idx === -1) return
      this.measureData = this.visitTaskList[idx].MeasureData
      const { element } = e.detail
      const ToolStateManager = cornerstoneTools.globalImageIdSpecificToolStateManager
      this.measureData.forEach(data => {
        if (data.MeasureData) {
          if (this.activeTool === 2 && this.readingTaskState < 2) {
            if (data.MeasureData && this.activeToolName === data.MeasureData.type) {
              cornerstoneTools.setToolActiveForElement(element, data.MeasureData.type, { mouseButtonMask: 1 })
            } else {
              cornerstoneTools.setToolPassiveForElement(element, data.MeasureData.type, { mouseButtonMask: 1 })
            }
          } else if (this.activeTool === 1 && this.readingTaskState < 2) {
            cornerstoneTools.setToolPassiveForElement(element, data.MeasureData.type, { mouseButtonMask: 1 })
          } else {
            cornerstoneTools.setToolEnabledForElement(element, data.MeasureData.type, { mouseButtonMask: 1 })
          }
          if (this.stack.instanceId.includes(data.InstanceId) && ((this.stack.isExistMutiFrames && data.MeasureData.frame === this.stack.frame && data.MeasureData) || (!this.stack.isExistMutiFrames && data.MeasureData))) {
            const toolState = ToolStateManager.getImageIdToolState(e.detail.image.imageId, data.MeasureData.type)
            if (toolState && toolState.data.length > 0) {
              var idx = toolState.data.findIndex(item => item.uuid === data.MeasureData.data.uuid)
              if (idx === -1) {
                data.MeasureData.data.active = false
                ToolStateManager.addImageIdToolState(e.detail.image.imageId, data.MeasureData.type, data.MeasureData.data)
              }
            } else {
              data.MeasureData.data.active = false
              ToolStateManager.addImageIdToolState(e.detail.image.imageId, data.MeasureData.type, data.MeasureData.data)
            }
          }
        }
      })
    },
    setMeasureDataVisible() {
      if (this.readingTaskState >= 2) return
      var element = cornerstone.getEnabledElement(this.canvas)
      var { imageId } = element.image
      const imageInfo = this.getInstanceInfo(imageId)
      var instanceId = imageInfo.instanceId
      var idx = this.visitTaskList.findIndex(i => i.VisitTaskId === this.stack.visitTaskId && i.IsCurrentTask && i.ReadingTaskState < 2)
      if (idx === -1) return
      this.measureData = this.visitTaskList[idx].MeasureData
      if (this.hideMeasureArr.length === 0) {
        this.measureData.map(i => {
          if (i.InstanceId === instanceId && i.MeasureData) {
            i.MeasureData.data.visible = false
            this.hideMeasureArr.push(i.MeasureData.data.uuid)
          }
        })
      } else {
        this.measureData.map(i => {
          if (i.InstanceId === instanceId && i.MeasureData) {
            i.MeasureData.data.visible = true
          }
        })
        this.hideMeasureArr = []
      }

      cornerstone.updateImage(element.element, true)
    },
    resetHideMeasureArr() {
      var idx = this.visitTaskList.findIndex(i => i.VisitTaskId === this.stack.visitTaskId && i.IsCurrentTask && i.ReadingTaskState < 2)
      if (idx === -1) return
      this.measureData = this.visitTaskList[idx].MeasureData
      this.measureData.map(i => {
        if (i.MeasureData) {
          i.MeasureData.data.visible = true
        }
      })
      this.hideMeasureArr = []
    },
    initWwc() {
      // 初次加载时，如果该影像存在标记，则以标记的窗宽窗位为初始化默认值，否则以序列的窗宽窗位为初始化默认值

      if (!this.isFirstLoadIns) {
        var n = 0
        for (let i = 0; i < this.measureData.length; i++) {
          if (this.stack.instanceId.includes(this.measureData[i].InstanceId) && this.measureData[i].MeasureData) {
            const data = this.measureData[i].MeasureData
            this.setWwwc(data.ww, data.wc)
            ++n
            break
          }
        }
        if (n === 0) {
          if (this.series.ww && this.series.wc) { this.setWwwc(this.series.ww, this.series.wc) }
        }
        this.isFirstLoadIns = true
      } else {
        for (let i = 0; i < this.measureData.length; i++) {
          if (this.stack.instanceId.includes(this.measureData[i].InstanceId) && this.measureData[i].MeasureData) {
            const data = this.measureData[i].MeasureData
            this.setWwwc(data.ww, data.wc)
            break
          }
        }
      }
    },
    mouseClick(e) {
      const { element, currentPoints, image, viewport } = e.detail
      var imageId = image.imageId
      const imageInfo = this.getInstanceInfo(imageId)
      var instanceId = imageInfo.instanceId
      var frame = imageInfo.frame
      this.stack.frame = this.stack.isExistMutiFrames ? parseInt(frame) : null
      const ToolStateManager = cornerstoneTools.globalImageIdSpecificToolStateManager
      for (let t = 0; t < this.measuredTools.length; t++) {
        var toolType = this.measuredTools[t]
        const toolState = ToolStateManager.getImageIdToolState(e.detail.image.imageId, toolType)
        if (!toolState) continue
        var toolObj = new cornerstoneTools[`${toolType}Tool`]()
        var i = toolState.data.findIndex(data => toolObj.pointNearTool(element, data, currentPoints.canvas, 'mouse'))
        if (i > -1) {
          var idx = this.measureData.findIndex(item => item.MeasureData && item.MeasureData.data && item.MeasureData.data.uuid === toolState.data[i].uuid)
          if (idx > -1) {
            DicomEvent.$emit('setCollapseActive', this.measureData[idx])
            if (this.readingTaskState < 2) {
              const measureData = {}
              var markName = this.measureData[idx].OrderMarkName
              if (this.disabledMarks.indexOf(markName) === -1 || !this.disabledMarks) {
                var questionInfo = this.measureData[idx]
                // const canvas = this.canvas.querySelector('canvas')
                // measureData.pictureBaseStr = canvas.toDataURL('image/png', 1)
                measureData.studyId = this.stack.studyId
                measureData.seriesId = this.stack.seriesId
                measureData.instanceId = instanceId
                measureData.frame = this.stack.frame ? this.stack.frame : 0
                measureData.data = toolState.data[i]
                measureData.type = toolType
                measureData.thick = this.dicomInfo.thick
                measureData.location = this.dicomInfo.location
                measureData.ww = Math.round(viewport.voi.windowWidth)
                measureData.wc = Math.round(viewport.voi.windowCenter)
                measureData.data.active = false
                var criterionType = parseInt(localStorage.getItem('CriterionType'))
                if (criterionType === 21) {
                  measureData.tableQuestionId = this.measureData[idx].TableQuestionId
                }
                this.$emit('modifyMeasureData', { measureData, questionInfo })
              }
            }
            break
          }
        }
      }
    },
    loadImageStack(dicomSeries) {
      return new Promise(resolve => {
        this.isCurrentTask = dicomSeries.isCurrentTask
        this.isBaseline = dicomSeries.isBaseLineTask
        this.readingTaskState = dicomSeries.readingTaskState
        if (this.isCurrentTask && this.readingTaskState < 2) {
          this.activeTool = 1
          this.resetHideMeasureArr()
        } else {
          this.activeTool = 0
        }
        this.series = Object.assign(this.series ? this.series : {}, dicomSeries)
        this.stack = Object.assign(this.stack, dicomSeries)

        this.stack.seriesId = dicomSeries.seriesId
        this.stack.studyId = dicomSeries.studyId
        this.stack.seriesNumber = dicomSeries.seriesNumber
        this.stack.imageIds = dicomSeries.imageIds
        this.stack.currentImageIdIndex = dicomSeries.imageIdIndex && dicomSeries.imageIdIndex < dicomSeries.imageIds.length ? dicomSeries.imageIdIndex : 0
        this.stack.imageIdIndex = dicomSeries.imageIdIndex
        this.stack.firstImageLoading = true
        this.stack.visitTaskId = dicomSeries.visitTaskId
        this.stack.taskBlindName = dicomSeries.taskBlindName
        this.stack.description = dicomSeries.description
        this.stack.studyIndex = dicomSeries.studyIndex
        this.stack.seriesIndex = dicomSeries.seriesIndex
        this.stack.sliceThickness = dicomSeries.sliceThickness
        this.stack.instanceCount = dicomSeries.instanceCount
        this.stack.isExistsClinicalData = dicomSeries.isExistsClinicalData
        this.stack.isExistMutiFrames = dicomSeries.isExistMutiFrames
        // this.measuredData = dicomSeries.measuredData
        var idx = this.visitTaskList.findIndex(i => i.VisitTaskId === dicomSeries.visitTaskId)
        this.stack.visitTaskNum = this.visitTaskList[idx].VisitTaskNum
        this.isFirstChangeTask = this.visitTaskList[idx].IsFirstChangeTask
        var criterionType = parseInt(localStorage.getItem('CriterionType'))
        if (this.isFirstChangeTask) {
          this.disabledMarks = this.getDisabledMarks(this.visitTaskList[idx].MeasureData)
        } else if (criterionType === 2) {
          this.disabledMarks = this.getMergeMarks(this.visitTaskList[idx].MeasureData)
        } else {
          this.disabledMarks = []
        }

        this.maxVistNum = this.visitTaskList[this.visitTaskList.length - 1].VisitTaskNum
        this.minVistNum = this.visitTaskList[0].VisitTaskNum
        this.measureData = this.visitTaskList[idx].MeasureData
        const imageId = this.stack.imageIds[this.stack.currentImageIdIndex]
        const imageInfo = this.getInstanceInfo(imageId)
        var instanceId = imageInfo.instanceId
        var frame = imageInfo.frame
        this.stack.frame = this.stack.isExistMutiFrames ? parseInt(frame) : null
        this.stack.instanceId = instanceId
        
        const element = this.$refs.canvas
        cornerstone.enable(element)
        element.tabIndex = 0
        element.focus()
        const ToolStateManager = cornerstoneTools.globalImageIdSpecificToolStateManager
        ToolStateManager.clearImageIdToolState(dicomSeries.imageIds)
        this.toggleClipPlay(false)
        this.toolState.viewportInvert = false
        this.toolState.dicomInfoVisible = false
        var scope = this
        // var p = parseInt(new Date().getTime())
        // requestPoolManager.loadAndCacheImagePlus(this.stack.imageIds[this.stack.currentImageIdIndex], this.stack.seriesId, p*100).then(image=>{
        //   scope.onFirstImageLoaded(image)
        //   resolve()
        // })
        // .catch((error) => {
        //   if (error.error && error.error.message) {
        //     this.$alert(error.error.message)
        //   }
        //   resolve()
        // })
        this.loading = true
        cornerstone.loadAndCacheImage(this.stack.imageIds[this.stack.currentImageIdIndex])
          .then(async image => {
            if (this.stack.imageIds.indexOf(image.imageId) !== -1) {
              await scope.onFirstImageLoaded(image)
            }
            scope.loading = false
            resolve()
          })
          .catch((error) => {
            if (error.error && error.error.message) {
              this.$alert(error.error.message)
            }
            scope.loading = false
            resolve()
          })
      })
    },
    onFirstImageLoaded(image) {
      // console.log('onFirstImageLoaded')
      return new Promise(async resolve => {
        const element = this.$refs.canvas
        var viewport = cornerstone.getDefaultViewportForImage(this.canvas, image)
        cornerstone.displayImage(this.canvas, image, viewport)

        if (!this.toolState.initialized) {
          this.toolState.initialized = true
          const toolButtons = document.querySelectorAll('[data-tool]')

          // const scope = this
          Array.from(toolButtons).forEach((toolBtn) => {
          // Add the tool
            const toolName = toolBtn.getAttribute('data-tool')
            const apiTool = cornerstoneTools[`${toolName}Tool`]
            if (apiTool) {
              const toolAlreadyAddedToElement = cornerstoneTools.getToolForElement(element, apiTool)

              if (!toolAlreadyAddedToElement) {
                if (toolName === 'Length') {
                  cornerstoneTools.addToolForElement(element, LengthTool, { configuration: { handleRadius: false, drawHandlesOnHover: true, hideHandlesIfMoving: true, digits: this.digitPlaces, drawHandles: true }})
                } else if (toolName === 'Bidirectional') {
                // cornerstoneTools.addToolForElement(element, BidirectionalTool, { digits: this.digitPlaces })
                // , handleRadius: false, drawHandlesOnHover: true, hideHandlesIfMoving: true
                  cornerstoneTools.addToolForElement(element, BidirectionalTool, { configuration: { digits: this.digitPlaces, hideHandlesIfMoving: true }})
                } else if (toolName === 'ArrowAnnotate') {
                  cornerstoneTools.addToolForElement(element, ArrowAnnotateTool, { configuration: { allowEmptyLabel: true, handleRadius: false, drawHandlesOnHover: true, hideHandlesIfMoving: true }})
                } else if (toolName === 'RectangleRoi') {
                  cornerstoneTools.addToolForElement(element, RectangleRoiTool, { configuration: { allowEmptyLabel: true, handleRadius: false, drawHandlesOnHover: true, hideHandlesIfMoving: true }})
                } else if (toolName === 'Probe' && parseInt(localStorage.getItem('CriterionType')) === 21) {
                   cornerstoneTools.addToolForElement(element, ProbeTool, { configuration: { fixedRadius: 5, handleRadius: true, drawHandlesOnHover: true, hideHandlesIfMoving: true, digits: this.digitPlaces }})
                } else {
                  cornerstoneTools.addToolForElement(element, apiTool)
                }
              }
            }
          })
          if (!cornerstoneTools.getToolForElement(element, cornerstoneTools.WwwcRegionTool)) {
            cornerstoneTools.addToolForElement(element, cornerstoneTools.WwwcRegionTool)
          }
          if (!cornerstoneTools.getToolForElement(element, cornerstoneTools.StackScrollMouseWheelTool)) {
            cornerstoneTools.addToolForElement(element, cornerstoneTools.StackScrollMouseWheelTool)
          }
          cornerstoneTools.setToolActiveForElement(element, 'StackScrollMouseWheel', {})

          if (!cornerstoneTools.getToolForElement(element, ScaleOverlayTool)) {
            cornerstoneTools.addToolForElement(element, ScaleOverlayTool)
          }
          cornerstoneTools.setToolActiveForElement(element, 'ScaleOverlay', {})
          cornerstoneTools.setToolActiveForElement(this.canvas, 'Zoom', {
            mouseButtonMask: 2
          })
          cornerstoneTools.setToolActiveForElement(this.canvas, 'Pan', {
            mouseButtonMask: 4
          })

        // if (!cornerstoneTools.getToolForElement(element, OrientationMarkersTool)) {
        //   cornerstoneTools.addToolForElement(element, OrientationMarkersTool)
        // }
        // cornerstoneTools.setToolActiveForElement(element, 'OrientationMarkers', { })
        }

        // cornerstoneTools.addStackStateManager(this.canvas, ['stack', 'stackPrefetch', 'playClip'])
        cornerstoneTools.addStackStateManager(this.canvas, ['stack', 'playClip'])
        cornerstoneTools.addToolState(this.canvas, 'stack', this.stack)
        // cornerstoneTools.stackPrefetch.enable(this.canvas)
        cornerstone.updateImage(element, true)

        this.stack.firstImageLoading = false
        this.toolState.dicomInfoVisible = true
        const imageInfo = this.getInstanceInfo(image.imageId)
        var instanceId = imageInfo.instanceId
        var frame = imageInfo.frame
        this.stack.frame = this.stack.isExistMutiFrames ? parseInt(frame) : null
        this.stack.instanceId = instanceId
        this.height = (this.stack.currentImageIdIndex) * 100 / (this.stack.imageIds.length - 1)
        // this.resetWwwc()
        resolve()
      })
    },
    onNewImage(e) {
      // console.log('cornerstonenewimage')
      if (this.isCurrentTask && this.readingTaskState < 2) {
        this.resetHideMeasureArr()
      }
      const { image } = e.detail
      const ToolStateManager = cornerstoneTools.globalImageIdSpecificToolStateManager
      const imageId = image.imageId
      ToolStateManager.clearImageIdToolState(imageId)
      e.detail.enabledElement.options = {}
      var data = e.detail.image.data
      this.dicomInfo.hospital = data.string('x00080080')
      // this.dicomInfo.pid = data.string('x00100020')
      this.dicomInfo.pid = data.string('x00120040')
      this.dicomInfo.name = data.string('x00100010')
      this.dicomInfo.age = data.string('x00101010')
      this.dicomInfo.sex = data.string('x00100040')
      this.dicomInfo.acc = data.string('x00080050') // 登记号
      this.dicomInfo.modality = data.string('x00080060')
      this.dicomInfo.time = this.formatDicomDateTime(
        data.string('x00080020'),
        data.string('x00080030')
      )
      this.dicomInfo.series = data.string('x00200011')
      this.dicomInfo.frame = `${this.stack.currentImageIdIndex + 1}/${
        this.stack.imageIds.length
      }`
      this.dicomInfo.size = `${data.uint16('x00280011')}*${data.uint16(
        'x00280010'
      )}`
      var pixel = data.floatString('x00280030')
      if (pixel) {
        this.dicomInfo.pixel = pixel.toFixed(2)
      }
      this.dicomInfo.thick = data.floatString('x00180050') // 切片厚度
      if (this.dicomInfo.thick) {
        this.dicomInfo.thick = this.dicomInfo.thick.toFixed(2)
      }
      const newImageIdIndex = this.stack.imageIds.findIndex(i => i === imageId)
      if (newImageIdIndex === -1) return
      this.stack.currentImageIdIndex = newImageIdIndex
      this.stack.imageIdIndex = newImageIdIndex
      this.series.imageIdIndex = newImageIdIndex
      this.height = (this.stack.currentImageIdIndex) * 100 / (this.stack.imageIds.length - 1)
    },
    getScreenshots() {
      const canvas = this.canvas.querySelector('canvas')
      var pictureBaseStr = canvas.toDataURL('image/png', 1)
      return pictureBaseStr
    },
    formatDicomDateTime(date, time) {
      if (date) {
        date = `${date.substr(0, 4)}-${date.substr(4, 2)}-${date.substr(6, 2)}`
      }
      if (time) { time = `${time.substr(0, 2)}:${time.substr(2, 2)}:${time.substr(4, 2)}` }
      return time ? `${date} ${time}` : `${date} 00:00:00`
    },
    onImageLoaded(e) {
      // console.log('onImageLoaded')
    },
    onImageRendered(e) {
      // console.log('onImageRendered')
      this.stack.imageRendered = true
      // const { element } = e.detail
      var imageId = e.detail.image.imageId
      const imageInfo = this.getInstanceInfo(imageId)
      var instanceId = imageInfo.instanceId
      var frame = imageInfo.frame
      this.stack.frame = this.stack.isExistMutiFrames ? parseInt(frame) : null
      if (this.imageId !== instanceId) {
        this.getOrientationMarker(e.detail.element)
        // 初次加载时，如果该影像存在标记，则以标记的窗宽窗位为初始化默认值，否则以序列的窗宽窗位为初始化默认值
        this.isFirstLoadIns = false
        // this.initWwc()
        this.imageId = instanceId
      }

      this.stack.instanceId = instanceId
      var viewport = e.detail.viewport
      this.dicomInfo.wwwc = `${Math.round(
        viewport.voi.windowWidth
      )}/${Math.round(viewport.voi.windowCenter)}` // 窗位
      // this.dicomInfo.zoom = viewport.scale.toFixed(2)
      this.dicomInfo.zoom = viewport.scale.toFixed(4)
      var data = e.detail.image.data
      const position = data.string('x00201041')
      this.dicomInfo.location = position
      // this.reloadCanvas(e)
      if (this.isScrollSync && this.currentDicomCanvasIndex === this.canvasIndex) {
        const obj = Object.assign({}, this.scrollSyncInfo)
        this.$emit('scrollSync', obj)
        this.scrollSyncInfo.offset = 0
      }
      this.renderMeasuredData(e)
    },
    getOrientationMarker(element) {
      const enabledElement = cornerstone.getEnabledElement(element)
      const imagePlane = cornerstone.metaData.get(
        'imagePlaneModule',
        enabledElement.image.imageId
      )

      if (!imagePlane || !imagePlane.rowCosines || !imagePlane.columnCosines) {
        return
      }
      const row = getOrientationString(imagePlane.rowCosines)
      const column = getOrientationString(imagePlane.columnCosines)
      const oppositeRow = invertOrientationString(row)
      const oppositeColumn = invertOrientationString(column)

      this.orientationMarkers = [oppositeColumn, row, column, oppositeRow]
      this.originalMarkers = [oppositeColumn, row, column, oppositeRow]
      this.setMarkers()
    },
    onMeasurementcompleted(e) {
      if (this.readingTaskState >= 2) return

      var element = cornerstone.getEnabledElement(this.canvas)
      var viewport = element.viewport
      // 测量完成
      // console.log('completed')
      this.activeTool = 1
      this.activeToolName = ''
      var { imageId } = element.image
      const imageInfo = this.getInstanceInfo(imageId)
      var instanceId = imageInfo.instanceId
      var frame = imageInfo.frame
      this.stack.frame = this.stack.isExistMutiFrames ? parseInt(frame) : null
      if (e.detail.toolName === 'Length' || e.detail.toolName === 'ArrowAnnotate' || e.detail.toolName === 'RectangleRoi') {
        const measureData = {}
        measureData.studyId = this.stack.studyId
        measureData.seriesId = this.stack.seriesId
        measureData.instanceId = instanceId
        measureData.frame = this.stack.frame
        measureData.data = e.detail.measurementData
        measureData.type = e.detail.toolName
        measureData.thick = this.dicomInfo.thick
        measureData.location = this.dicomInfo.location
        measureData.ww = Math.round(viewport.voi.windowWidth)
        measureData.wc = Math.round(viewport.voi.windowCenter)

        // const canvas = this.canvas.querySelector('canvas')
        // measureData.pictureBaseStr = canvas.toDataURL('image/png', 1)
        this.$emit('setMeasureData', measureData)
        cornerstoneTools.setToolPassiveForElement(this.canvas, e.detail.toolName)
      } else if (e.detail.toolName === 'Bidirectional') {
        const measureData = {}
        measureData.studyId = this.stack.studyId
        measureData.seriesId = this.stack.seriesId
        measureData.instanceId = instanceId
        measureData.frame = this.stack.frame ? this.stack.frame : 0
        measureData.data = e.detail.measurementData
        measureData.type = e.detail.toolName
        measureData.thick = this.dicomInfo.thick
        measureData.location = this.dicomInfo.location
        measureData.ww = Math.round(viewport.voi.windowWidth)
        measureData.wc = Math.round(viewport.voi.windowCenter)
        // const canvas = this.canvas.querySelector('canvas')
        // measureData.pictureBaseStr = canvas.toDataURL('image/png', 1)
        this.$emit('setMeasureData', measureData)
        cornerstoneTools.setToolPassiveForElement(this.canvas, e.detail.toolName)
      } else if (e.detail.toolName === 'Probe') {
        const measureData = {}
        measureData.studyId = this.stack.studyId
        measureData.seriesId = this.stack.seriesId
        measureData.instanceId = instanceId
        measureData.frame = this.stack.frame ? this.stack.frame : 0
        measureData.data = e.detail.measurementData
        measureData.type = e.detail.toolName
        measureData.thick = this.dicomInfo.thick
        measureData.location = this.dicomInfo.location
        measureData.ww = Math.round(viewport.voi.windowWidth)
        measureData.wc = Math.round(viewport.voi.windowCenter)
        this.$emit('setMeasureData', measureData)
        cornerstoneTools.setToolPassiveForElement(this.canvas, e.detail.toolName)
      } else if (!e.detail.toolName) {
        // 更新
        // var measurementData = e.detail.measurementData
        // var uuid = measurementData ? e.detail.measurementData.uuid : ''
        // var idx = this.measureData.findIndex(item => item.MeasureData && item.MeasureData.data && item.MeasureData.data.uuid === uuid)
        // if (idx > -1) {
        //   const measureData = {}
        //   var markName = this.measureData[idx].OrderMarkName
        //   if (this.disabledMarks.indexOf(markName) === -1 || !this.disabledMarks) {
        //     var toolType = this.measureData[idx].MeasureData.type
        //     if (toolType === 'Bidirectional') {
        //       // const {
        //       //   longestDiameter,
        //       //   shortestDiameter
        //       // } = calculateLongestAndShortestDiameters(measurementData, element.image, this.digitPlaces)
        //       // measurementData.longestDiameter = longestDiameter
        //       // measurementData.shortestDiameter = shortestDiameter
        //     }
        //     // if (toolType === 'Length') {
        //     //   console.log(e.detail.measurementData.length)
        //     //   measurementData.length = this.calculateLenth(measurementData)
        //     // }
        //     var questionInfo = this.measureData[idx]
        //     const canvas = this.canvas.querySelector('canvas')
        //     measureData.pictureBaseStr = canvas.toDataURL('image/png', 1)
        //     measureData.studyId = this.stack.studyId
        //     measureData.seriesId = this.stack.seriesId
        //     measureData.instanceId = instanceId
        //     measureData.frame = this.stack.frame ? this.stack.frame : 0
        //     measureData.data = measurementData
        //     measureData.type = toolType
        //     measureData.thick = this.dicomInfo.thick
        //     measureData.ww = Math.round(viewport.voi.windowWidth)
        //     measureData.wc = Math.round(viewport.voi.windowCenter)
        //     measureData.data.active = false
        //     console.log(measureData === e.detail.measurementData)
        //     this.$emit('modifyMeasureData', { measureData, questionInfo })
        //   }
        // }
      }
    },
    calculateLenth(data) {
      var element = cornerstone.getEnabledElement(this.canvas)
      const { rowPixelSpacing, colPixelSpacing } = this.getPixelSpacing(element.image)
      const dx =
      (data.handles.end.x - data.handles.start.x) * (colPixelSpacing || 1)
      const dy =
      (data.handles.end.y - data.handles.start.y) * (rowPixelSpacing || 1)
      const length = Math.sqrt(dx * dx + dy * dy)

      return length.toFixed(this.digitPlaces)
    },
    getPixelSpacing(image) {
      const imagePlane = cornerstone.metaData.get(
        'imagePlaneModule',
        image.imageId
      )

      if (imagePlane) {
        return {
          rowPixelSpacing:
        imagePlane.rowPixelSpacing || imagePlane.rowImagePixelSpacing,
          colPixelSpacing:
        imagePlane.columnPixelSpacing || imagePlane.colImagePixelSpacing
        }
      }

      return {
        rowPixelSpacing: image.rowPixelSpacing,
        colPixelSpacing: image.columnPixelSpacing
      }
    },
    onMeasurementremoved(e) {
      console.log('================移除病灶=================', e)
    },
    onMeasurementmodified(e) {
      // 移动
      console.log('modified')
      if (this.readingTaskState >= 2) return
      const { measurementData, toolType } = e.detail
      var element = cornerstone.getEnabledElement(this.canvas)
      var viewport = element.viewport
      var { imageId } = element.image
      const imageInfo = this.getInstanceInfo(imageId)
      var instanceId = imageInfo.instanceId
      var frame = imageInfo.frame
      this.stack.frame = this.stack.isExistMutiFrames ? parseInt(frame) : null

      var uuid = measurementData.uuid
      var idx = this.measureData.findIndex(item => item.MeasureData && item.MeasureData.data && item.MeasureData.data.uuid === uuid)
      if (idx > -1) {
        const measureData = {}
        var markName = this.measureData[idx].OrderMarkName
        if (this.disabledMarks.indexOf(markName) === -1 || !this.disabledMarks) {
          var questionInfo = this.measureData[idx]
          // const canvas = this.canvas.querySelector('canvas')
          // measureData.pictureBaseStr = canvas.toDataURL('image/png', 1)
          measureData.studyId = this.stack.studyId
          measureData.seriesId = this.stack.seriesId
          measureData.instanceId = instanceId
          measureData.frame = this.stack.frame ? this.stack.frame : 0
          measureData.data = measurementData
          measureData.type = toolType
          measureData.thick = this.dicomInfo.thick
          measureData.location = this.dicomInfo.location
          measureData.ww = Math.round(viewport.voi.windowWidth)
          measureData.wc = Math.round(viewport.voi.windowCenter)
          measureData.data.active = false
          var criterionType = parseInt(localStorage.getItem('CriterionType'))
          if (criterionType === 21) {
            measureData.tableQuestionId = this.measureData[idx].TableQuestionId
          }
          this.$emit('modifyMeasureData', { measureData, questionInfo })
        }
      }
    },
    debounce(callback, delay) {
      let timerId
      return function() {
        clearTimeout(timerId)
        timerId = setTimeout(() => {
          callback.apply(this, arguments)
        }, delay)
      }
    },
    updateImage(instanceId) {
      var i = this.visitTaskList.findIndex(i => i.VisitTaskId === this.stack.visitTaskId)
      this.measureData = this.visitTaskList[i].MeasureData

      const ToolStateManager = cornerstoneTools.globalImageIdSpecificToolStateManager

      var element = cornerstone.getEnabledElement(this.canvas)
      var { imageId } = element.image
      ToolStateManager.clearImageIdToolState(imageId)
      cornerstone.updateImage(element, true)
    },
    toggleSeries(evt, type) {
      evt.stopImmediatePropagation()
      evt.stopPropagation()
      evt.preventDefault()
      this.measuredTools.forEach(toolName => {
        cornerstoneTools.setToolEnabledForElement(this.canvas, toolName)
      })
      var num = this.stack.visitTaskNum + type
      if (num < this.minVistNum || num > this.maxVistNum) return
      // 判断有没有标记  获取第一个标记
      var element = cornerstone.getEnabledElement(this.canvas)
      var { imageId } = element.image
      const imageInfo = this.getInstanceInfo(imageId)
      var instanceId = imageInfo.instanceId
      var idx = this.measureData.findIndex(item => item.InstanceId === instanceId)
      var measureData = null
      if (idx > -1) {
        measureData = this.measureData[idx]
      }
      this.series.imageIdIndex = this.stack.currentImageIdIndex
      DicomEvent.$emit('toggleSeries', { series: this.series, type: type, canvasIndex: this.canvasIndex, measureData })
    },
    removeToolState(measureData) {
      var i = this.visitTaskList.findIndex(i => i.VisitTaskId === this.stack.visitTaskId)
      this.measureData = this.visitTaskList[i].MeasureData
      var idx = this.measureData.findIndex(item => item.MeasureData && item.MeasureData.data.uuid === measureData.data.uuid)
      if (idx > -1) {
        this.measureData.splice(idx, 1)
        var element = cornerstone.getEnabledElement(this.canvas)
        const ToolStateManager = cornerstoneTools.globalImageIdSpecificToolStateManager

        var { imageId } = element.image
        ToolStateManager.clearImageIdToolState(imageId)
        cornerstone.updateImage(element, true)
      }
    },
    getToolForElement(toolName) {
      var isExist = false
      for (var i = 0; i < cornerstoneTools.store.state.tools.length; i++) {
        if (cornerstoneTools.store.state.tools[i].name === toolName) {
          isExist = true
          break
        }
      }
      return isExist
    },
    onClipStopped() {
      this.toolState.clipPlaying = false
    },

    onKeyPress(e) {
      var key = e.detail.keyCode
      var keys = { PageUp: 33, PageDown: 34, End: 35, Home: 36 } // Left: 37, Up: 38, Right: 39, Down: 40
      if (key < keys.PageUp || key > keys.Home) return
      if (key === keys.Home) this.scrollPage(-9999)
      else if (key === keys.PageUp) this.scrollPage(-1)
      else if (key === keys.PageDown) this.scrollPage(1)
      else if (key === keys.End) this.scrollPage(9999)
    },

    resizeCanvas() {
      cornerstone.resize(this.canvas, true)
    },

    activateCanvas() {
      this.canvas.tabIndex = 0
      this.canvas.focus()
    },

    resetViewport() {
      this.toolState.viewportInvert = false
      if (this.originalMarkers.length > 0) {
        this.orientationMarkers = [...this.originalMarkers]
        this.setMarkers()
      }
      var image = cornerstone.getImage(this.canvas)
      cornerstone.setViewport(
        this.canvas,
        cornerstone.getDefaultViewportForImage(this.canvas, image)
      )
    },

    toggleDicomInfo() {
      this.toolState.dicomInfoVisible = !this.toolState.dicomInfoVisible
      if (this.toolState.dicomInfoVisible) {
        cornerstoneTools.orientationMarkers.enable(this.canvas)
      } else cornerstoneTools.orientationMarkers.disable(this.canvas)
      cornerstone.updateImage(this.canvas)
    },
    setColormap(colormap) {
      const viewport = cornerstone.getViewport(this.canvas)
      viewport.colormap = colormap
      cornerstone.setViewport(this.canvas, viewport)
      cornerstone.updateImage(this.canvas, true)
      if (!colormap) {
        this.resetRenderCanvase(this.canvas)
      }
    },
    resetRenderCanvase(element) {
      const enabledElement = cornerstone.getEnabledElement(element)

      enabledElement.renderingTools.colormapId = undefined
      enabledElement.renderingTools.colorLut = undefined

      const renderCanvas = enabledElement.renderingTools.renderCanvas
      const canvasContext = renderCanvas.getContext('2d')
      canvasContext.fillStyle = 'white'
      canvasContext.fillRect(0, 0, renderCanvas.width, renderCanvas.height)

      const renderCanvasData = canvasContext.getImageData(
        0,
        0,
        renderCanvas.width,
        renderCanvas.height
      )

      enabledElement.renderingTools.renderCanvasContext = canvasContext
      enabledElement.renderingTools.renderCanvasData = renderCanvasData
    },
    scrollPage(offset) {
      if (offset === 0) return
      var index = this.stack.currentImageIdIndex + offset
      this.index = this.stack.currentImageIdIndex + offset
      if (index < 0) {
        index = 0
      } else if (index >= this.stack.imageIds.length) {
        index = this.stack.imageIds.length - 1
      }
      if (index !== this.stack.currentImageIdIndex) {
        scroll(this.canvas, index)
      }
    },

    toggleClipPlay(isPlay) {
      if (isPlay) {
        this.toolState.clipPlaying = true
        cornerstoneTools.playClip(this.canvas, this.dicomInfo.fps)
        cornerstoneTools.getToolState(
          this.canvas,
          'playClip'
        ).data[0].loop = false
      } else {
        cornerstoneTools.stopClip(this.canvas)
        this.toolState.clipPlaying = false
        return
      }
    },
    setFps(fps) {
      this.dicomInfo.fps = fps
    },

    resetWwwc() {
      this.toolState.viewportInvert = false
      var viewport = cornerstone.getViewport(this.canvas)
      // viewport.invert = false
      var image = cornerstone.getImage(this.canvas)
      viewport.voi.windowWidth = image.windowWidth
      viewport.voi.windowCenter = image.windowCenter
      cornerstone.setViewport(this.canvas, viewport)
    },

    setWwwc(ww, wc) {
      // console.log('setWwwc', ww, wc)
      var viewport = cornerstone.getViewport(this.canvas)
      viewport.voi.windowWidth = ww
      viewport.voi.windowCenter = wc
      cornerstone.setViewport(this.canvas, viewport)
    },

    toggleInvert() {
      this.toolState.viewportInvert = !this.toolState.viewportInvert
      var viewport = cornerstone.getViewport(this.canvas)
      viewport.invert = this.toolState.viewportInvert
      cornerstone.setViewport(this.canvas, viewport)
    },

    activateZoom() {
      cornerstoneTools.addTool(cornerstoneTools.ZoomTool, {
        configuration: {
          invert: false,
          preventZoomOutsideImage: false,
          minScale: 0.1,
          maxScale: 20.0
        }
      })
      cornerstoneTools.setToolActive('Zoom', { mouseButtonMask: 1 })
      this.toolState.activeTool = 'zoom'
    },

    resetRotate() {
      if (this.originalMarkers.length > 0) {
        this.orientationMarkers = [...this.originalMarkers]
        this.setMarkers()
      }
      var viewport = cornerstone.getViewport(this.canvas)
      viewport.hflip = false
      viewport.vflip = false
      viewport.rotation = 0
      cornerstone.setViewport(this.canvas, viewport)
    },
    setMarkers() {
      var markers = [...this.orientationMarkers]
      for (const key in this.markers) {
        var v = markers.shift(0)
        this.markers[key] = v
      }
    },
    setRotate(hflip, vflip, angle, type) {
      if (this.orientationMarkers.length > 0) {
        var markers = [...this.orientationMarkers]
        if (type === 2) {
          // 垂直翻转
          this.orientationMarkers[0] = markers[2]
          this.orientationMarkers[2] = markers[0]
        } else if (type === 3) {
          // 水平翻转
          this.orientationMarkers[1] = markers[3]
          this.orientationMarkers[3] = markers[1]
        } else if (type === 4) {
          // 左转90度
          this.orientationMarkers = markers.slice(1, 4).concat(markers[0])
        } else if (type === 5) {
          // 右转90度
          this.orientationMarkers = [markers[3]].concat(markers.slice(0, 3))
        }
        this.setMarkers()
      }
      var viewport = cornerstone.getViewport(this.canvas)
      if (hflip) viewport.hflip = !viewport.hflip
      if (vflip) viewport.vflip = !viewport.vflip
      if (angle !== 0) viewport.rotation += angle
      cornerstone.setViewport(this.canvas, viewport)
    },

    saveImage() {
      var uid = cornerstone.getImage(this.canvas).data.string('x00080018')
      cornerstoneTools.SaveAs(this.canvas, `${uid}.png`)
    },
    fitToWindow() {
      if (this.stack.seriesNumber) {
        cornerstone.fitToWindow(this.canvas)
      }
    },
    fitToImage() {
      if (this.stack.seriesNumber) {
        const enabledElement = cornerstone.getEnabledElement(this.canvas)
        enabledElement.viewport.scale = 1
        cornerstone.updateImage(this.canvas)
      }
    },

    removeLabel(item) {
      const promise = scroll(this.canvas, item.data.imageIdIndex)
      const scope = this
      Promise.all([promise]).then(res => {
        cornerstoneTools.removeToolState(scope.canvas, item.type, item.data)
        cornerstone.updateImage(scope.canvas)
      })
    },
    setToolPassive(toolName) {
      // 它们的数据可以被操作，但不能创建。

      cornerstoneTools.setToolPassiveForElement(this.canvas, toolName)

      this.activeTool = 1
      this.activeToolName = ''
      if (toolName === 'Zoom') {
        cornerstoneTools.setToolActiveForElement(this.canvas, 'Zoom', {
          mouseButtonMask: [2]
        })
      } else if (toolName === 'Pan') {
        cornerstoneTools.setToolActiveForElement(this.canvas, 'Pan', {
          mouseButtonMask: [4]
        })
      }
    },
    setToolActive(toolName) {
      this.activeTool = 2
      // cornerstoneTools.setToolPassiveForElement(this.canvas, 'Bidirectional')
      // this.measuredTools.forEach(toolName => {
      //   console.log(toolName)
      //   cornerstoneTools.setToolPassiveForElement(this.canvas, toolName)
      // })
      this.activeToolName = toolName
      this.$nextTick(() => {
        // console.log(cornerstoneTools.isToolActiveForElement(this.canvas, 'Bidirectional'))
        if (!cornerstoneTools.isToolActiveForElement(this.canvas, toolName)) {
          cornerstoneTools.setToolActiveForElement(this.canvas, toolName, {
            mouseButtonMask: 1
          })
        }
        if (toolName === 'Zoom') {
          cornerstoneTools.setToolActiveForElement(this.canvas, 'Zoom', {
            mouseButtonMask: [1, 2]
          })
        }
        if (toolName === 'Pan') {
          cornerstoneTools.setToolActiveForElement(this.canvas, 'Pan', {
            mouseButtonMask: [1, 4]
          })
        }
      })
    },
    setToolEnabled(toolName) {
      this.activeToolName = ''
      // 工具将呈现，但不会对输入作出反应

      cornerstoneTools.setToolEnabledForElement(this.canvas, toolName)

      this.activeTool = 0
      // this.readingTaskState = 2
      if (toolName === 'Zoom') {
        cornerstoneTools.setToolActiveForElement(this.canvas, 'Zoom', {
          mouseButtonMask: 2
        })
      } else if (toolName === 'Pan') {
        cornerstoneTools.setToolActiveForElement(this.canvas, 'Pan', {
          mouseButtonMask: 4
        })
      }
    },
    setAllToolsPassive() {
      cornerstoneTools.store.state.tools.forEach((tool) => {
        cornerstoneTools.setToolPassiveForElement(this.canvas, tool.name)
      })
    },

    addTargetElement(synchronizer) {
      synchronizer.addTarget(this.$refs.canvas)
    },
    removeTarget(synchronizer) {
      synchronizer.removeTarget(this.$refs.canvas)
    },
    addSourceElement(synchronizer) {
      synchronizer.addSource(this.$refs.canvas)
    },
    removeSource(synchronizer) {
      synchronizer.removeSource(this.$refs.canvas)
    },
    activeReferenceLine(synchronizer) {
      if (
        !cornerstoneTools.getToolForElement(
          this.canvas,
          cornerstoneTools.ReferenceLinesTool
        )
      ) {
        cornerstoneTools.addToolForElement(
          this.canvas,
          cornerstoneTools.ReferenceLinesTool
        )
      }
      cornerstoneTools.setToolEnabledForElement(this.canvas, 'ReferenceLines', {
        synchronizationContext: synchronizer
      })

      // cornerstoneTools.addTool(cornerstoneTools.CrosshairsTool)
      // cornerstoneTools.setToolActive('Crosshairs', {
      //   mouseButtonMask: 1,
      //   synchronizationContext: synchronizer
      // })
    },
    disabledReferenceLine(synchronizer) {
      synchronizer.enabled = false
      synchronizer.remove(this.canvas)
      cornerstoneTools.setToolDisabledForElement(this.canvas, 'ReferenceLines')
      // cornerstoneTools.setToolDisabledForElement(this.canvas, 'Crosshairs')
    },
    activeViewPortToolSync(synchronizer, toolName) {
      synchronizer.add(this.canvas)
      synchronizer.enabled = true
      if (
        !cornerstoneTools.getToolForElement(
          this.canvas,
          cornerstoneTools[`${toolName}Tool`]
        )
      ) {
        cornerstoneTools.addToolForElement(
          this.canvas,
          cornerstoneTools[`${toolName}Tool`]
        )
      }
      cornerstoneTools.setToolActiveForElement(this.canvas, toolName, {
        mouseButtonMask: 1,
        synchronizationContext: synchronizer
      })
    },
    disabledViewPortToolSync(synchronizer, toolName) {
      synchronizer.enabled = false
      synchronizer.remove(this.canvas)
      cornerstoneTools.setToolDisabledForElement(this.canvas, toolName)
    },
    activeImageSync(synchronizer) {
      synchronizer.add(this.$refs.canvas)
      synchronizer.enabled = true
      return false
    },
    disabledImageSync(synchronizer) {
      synchronizer.remove(this.$refs.canvas)
      synchronizer.enabled = false
      return false
    },
    activeAnnotationSync(synchronizer) {
      this.AnnotationSync = synchronizer
      synchronizer.add(this.$refs.canvas)
      synchronizer.enabled = true
    },
    disabledAnnotationSync(synchronizer) {
      this.AnnotationSync = null
      synchronizer.enabled = false
      synchronizer.remove(this.$refs.canvas)
      this.setAllToolsPassive()
    },
    getToolSate() {
      const toolROITypes = [
        'Probe',
        'EllipticalRoi',
        'RectangleRoi',
        'ArrowAnnotate',
        'Length',
        'CobbAngle',
        'Angle',
        'Bidirectional',
        'FreehandRoi'
      ]
      for (let i = 0; i < toolROITypes.length; i++) {
        const toolROIType = toolROITypes[i]
        const toolROIData = JSON.stringify(
          cornerstoneTools.getToolState(this.canvas, toolROIType)
        )

        if (toolROIData !== undefined) {
          this.allROIToolData[toolROITypes[i]] = JSON.parse(toolROIData)
        }
      }
    },
    getInstanceInfo(imageId) {
      const params = {}
      const searchParams = new URLSearchParams(imageId.split('?')[1])
      for (const [key, value] of searchParams.entries()) {
        params[key] = value
      }
      if (isNaN(params.frame)) {
        params.frame = 0
      }
      return params
    },
    preventDefault(e) {
      e.stopImmediatePropagation()
      e.stopPropagation()
      e.preventDefault()
    },
    handleViewCD(e) {
      DicomEvent.$emit('previewCD', this.stack.visitTaskId)
      e.stopImmediatePropagation()
      e.stopPropagation()
      e.preventDefault()
    }

  }
}
</script>

<style lang="scss" scoped>
  .context-menu-wrapper{
    position: absolute;
    ul{
      list-style: none;
      margin: 0px;
      padding: 0px;
      background: #343333;
      color: #fff;
      margin: 0;
      border: 1px solid #2a2a2a;
      border-radius: 3px;
      height: auto;
      min-height: 50px;
      line-height: 1.5em;
      width:80px;
      box-sizing: border-box;
    }
    .menu{
      li {
        padding: 2px 5px;
        position: relative;
        border-bottom: 1px solid #666;
        div{
          padding: 5px;
        }
      }
      .submenu{
        position: absolute;
        left: 77px;
        top: -1px;
        background: #343333;
        color: #fff;
        display: none;
        li {
          padding: 2px 5px;
          border-bottom: 1px solid #666;
          div{
            padding: 5px;
          }
        }
      }

    }
    .menu li:hover{
      background-color: #ff5722;
      .submenu{
        display:block;
      }
    }
    .menu_active{
      cursor: pointer;
    }
    .menu_disabled{
      cursor: not-allowed;
    }

  }
  .info-visit{
    position: absolute;
    left:50%;
    top: 5px;
    transform: translateX(-50%);
    display: flex;
    flex-direction: row;
    .arrw_div_wrapper{
      width: 20px;
      height: 20px;
      background-color: #3f3f3f;
      text-align: center;
      line-height: 20px;
      border-radius: 10%;
    }
    .blind_name_wrapper{
      height: 20px;
      line-height: 20px;
      background-color: #00000057;
      color: #fff;
      padding:0 10px;
      font-size: 14px;
    }
  }
.info-cd{
  position: absolute;
  left: 10px;
  top: 5px;
  text-align: left;
  color: #ddd;
  font-size: 18px;
  cursor: pointer;
}
.info-series {
  position: absolute;
  left: 10px;
  top: 30px;
  text-align: left;
  color: #ddd;
  font-size: 12px;
  /* z-index: 1; */
}
.info-image {
  position: absolute;
  left: 10px;
  bottom: 10px;
  text-align: left;
  color: #ddd;
  font-size: 12px;
  /* z-index: 1; */
}

.info-subject {
  position: absolute;
  right: 15px;
  top: 30px;
  text-align: right;
  color: #ddd;
  font-size: 12px;
  /* z-index: 1; */
}
.info-instance {
  position: absolute;
  right: 15px;
  bottom: 10px;
  text-align: right;
  color: #ddd;
  font-size: 12px;
  /* z-index: 1; */
}

.load-indicator {
  position: absolute;
  left: 10px;
  top: 10px;
  text-align: left;
  /* z-index: 1; */
}

.magnifyTool {
  border: 2px solid #ffffff;
  border-radius: 50%;
  display: none;
  cursor: none;
}

.menu__item {
  display: block;
  line-height: 20px;
  text-align: center;
  margin: 10px;
  cursor: default;
}
.menu__item:hover {
  color: #ff0000;
}

.menu {
  height: auto;
  width: auto;
  position: absolute;
  font-size: 14px;
  text-align: left;
  border-radius: 10px;
  border: 1px solid #c21111;
  background-color: #ffffff;
}

li:hover {
  background-color: #e0e0e2;
  color: white;
}
.msg-div {
    position: absolute;
    z-index: 10;
    background-color: rgba(255, 255, 255, 0.5);
    color: #000;
    padding: 5px 20px;
  }
</style>
