<template>
  <div id="fileId" v-resize="handleResize" class="container" file-solt-id="fileId">
    <div v-if="fileType == 'PDF' && instanceList.length > 1" style="margin: 2px">
      <el-pagination simple :current-page="curIndex" :total="instanceList.length" defaultPageSize="1"  @current-change="handleCurrentChange" />
    </div>
    <iframe v-if="fileType == 'PDF'" :src="pdfUrl + '#view=FitH,top&pagemode=thumbs'" frameborder="0" style="width: 100%; height: 100%"></iframe>
    <div v-if="fileType == 'DCM'" class="dicom" ref="dicomElement"></div>
    <div v-if="fileType == 'JPG'" style="width: 100%;height: 100%" class="dicom" ref="dicomElement"></div>
<!--    <iframe v-if="curFile.fileType == 'PDF'" :src="curFile.filePath + '#view=FitH,top&pagemode=thumbs'" frameborder="0" style="width: 100%; height: 100%" />-->
<!--    <div v-if="curFile.fileType == 'DCM'" ref="dicomElement" class="dicom" />-->
<!--    <div v-if="curFile.fileType == 'JPG' || curFile.fileType == 'PNG'" ref="imgElement" class="dicom" />-->
  </div>
</template>

<script>

export default {
  directives: { // 使用局部注册指令的方式
    resize: { // 指令的名称
      bind(el, binding) { // el为绑定的元素，binding为绑定给指令的对象
        let width = ''; let height = ''
        function isReize() {
          const style = document.defaultView.getComputedStyle(el)
          if (width !== style.width || height !== style.height) {
            binding.value()
          }
          width = style.width
          height = style.height
        }
        el.__vueSetInterval__ = setInterval(isReize, 300)
      },
      unbind(el) {
        clearInterval(el.__vueSetInterval__)
      }
    }
  },
  props: ['fileObject'],
  data() {
    return {
      curFile: this.fileObject,
      curElement: '',
      fileType: '',
      viewportDefault: '',
      zoomValue: '',
      wwwcValue: '',
      renderTime: '',
      pdfUrl: '',
      curIndex: 1,
      total: 1,
      childrenList: [],
      instanceList: []
    }
  },
  watch: {
    fileObject(val) {
      this.curFile = val
    }
  },
  created() {
    this.instanceList = this.fileObject.instanceList || []
    this.fileType = this.instanceList.length ? this.instanceList[0].imageType : ''
  },
  mounted() {
    this.initData()
  },
  methods: {
    handleCurrentChange (val) {
      console.log(val)
      this.pdfUrl = this.instanceList[val - 1].imageId
    },
    // 加载DICM和图片
    drawCornerStone(imageUrl, type) {
      const self = this
      let element = ''
      let imageId = ''
      if (type === 'DCM') {
        element = this.$refs.dicomElement
        imageId = 'wadouri:' + imageUrl// dicom文件需要加上前缀'wadouri:'
      } else {
        element = this.$refs.dicomElement
        imageId = imageUrl
      }
      this.$cornerstoneTools.init()
      this.$cornerstone.enable(element)
      element.width = document.documentElement.clientWidth
      element.height = document.documentElement.clientHeight
      this.$cornerstone.loadImage(imageId).then(function (image) {
        if (type === 'DCM') {
          const viewport = self.$cornerstone.getDefaultViewportForImage(element, image)
          self.viewportDefault = viewport
          self.$cornerstone.displayImage(element, image, viewport)
        } else {
          self.$cornerstone.displayImage(element, image)
        }
      })
      element.addEventListener('cornerstoneimagerendered', this.getZoomRate)// 监听事件
      // let imageId = ''
      // const self = this
      // if (type === 'DCM') {
      //   imageId = 'wadouri:' + imageUrl // dicom文件需要加上前缀'wadouri:'
      // } else {
      //   imageId = imageUrl
      // }
      // this.$cornerstoneTools.init()
      // this.$cornerstone.enable(this.curElement)
      // this.curElement.width = document.documentElement.clientWidth
      // this.curElement.height = document.documentElement.clientHeight
      // this.$cornerstone.loadImage(imageId).then(function(image) {
      //   // 获取当前图像默认的窗宽窗位
      //   const viewport = self.$cornerstone.getDefaultViewportForImage(self.curElement, image)
      //   self.viewportDefault = viewport
      //   if (type === 'DCM') {
      //     self.$cornerstone.displayImage(self.curElement, image, viewport)
      //   } else {
      //     self.$cornerstone.displayImage(self.curElement, image)
      //   }
      // })
    },
    // 重新渲染
    handleResize() {
      const canvas = document.getElementById('fileId')
      if (this.curElement && canvas) {
        this.curElement.style.width = canvas.offsetWidth + 'px'
        this.curElement.style.height = canvas.offsetHeight + 'px'
        this.$cornerstone.resize(this.curElement)
      }
    },
    // 窗宽窗位
    setWwwl() {
      const WwwcTool = this.$cornerstoneTools.WwwcTool
      this.$cornerstoneTools.addTool(WwwcTool)
      this.$cornerstoneTools.setToolActive('Wwwc', { mouseButtonMask: 1 })
      this.$forceUpdate()
    },
    // 负片
    setInvert() {
      if (!this.curElement) return
      this.viewportDefault.invert = !this.viewportDefault.invert
      this.$cornerstone.setViewport(this.curElement, this.viewportDefault)
    },
    // 缩放
    setZoom() {
      const ZoomTool = this.$cornerstoneTools.ZoomTool
      this.$cornerstoneTools.addTool(ZoomTool, {
        configuration: {
          invert: false,
          preventZoomOutsideImage: false,
          minScale: 0.1,
          maxScale: 20.0
        }
      })
      this.$cornerstoneTools.setToolActive('Zoom', { mouseButtonMask: 1 })
    },
    // 移动
    setMove() {
      const PanTool = this.$cornerstoneTools.PanTool
      this.$cornerstoneTools.addTool(PanTool)
      this.$cornerstoneTools.setToolActive('Pan', { mouseButtonMask: 1 })
    },
    // 放大镜
    setMagnify() {
      const MagnifyTool = this.$cornerstoneTools.MagnifyTool
      this.$cornerstoneTools.addTool(MagnifyTool)
      this.$cornerstoneTools.setToolActive('Magnify', { mouseButtonMask: 1 })
    },
    // 重载
    setReset() {
      if (!this.curElement) return
      this.$cornerstone.reset(this.curElement)
    },
    setScroll() {
      const self = this
      const element = this.$refs.dicomElement
      if (!element) return
      this.$cornerstoneTools.init()
      this.$cornerstone.enable(element)
      const s = document.getElementById('fileId')
      element.width = s.clientWidth
      element.height = s.clientHeight
      const series = this.childrenList
      let imageIds = ''
      if (this.fileType === 'DCM') {
        const scheme = 'wadouri'
        imageIds = series.map(seriesImage => `${scheme}:${seriesImage.imageId}`)
      } else {
        imageIds = series.map(seriesImage => `${seriesImage.imageId}`)
      }
      const StackScrollTool = this.$cornerstoneTools.StackScrollTool
      this.total = imageIds.length
      const stack = {
        currentImageIdIndex: 0,
        imageIds
      }
      // load images and set the stack
      // loadAndCacheImage
      this.$cornerstone.loadImage(imageIds[0]).then((image) => {
        const viewport = this.$cornerstone.getDefaultViewportForImage(element, image)
        self.viewportDefault = viewport
        this.$cornerstone.displayImage(element, image, viewport)
        this.$cornerstoneTools.addStackStateManager(element, ['stack'])
        this.$cornerstoneTools.addToolState(element, 'stack', stack)
      })
      this.$cornerstoneTools.addTool(StackScrollTool)
      this.$cornerstoneTools.setToolActive('StackScroll', { mouseButtonMask: 1 })
      element.addEventListener('cornerstoneimagerendered', this.getZoomRate)// 监听事件
    },
    // 计算缩放/窗宽/窗位/渲染时间
    getZoomRate(e) {
      if (!this.curElement) return
      const contextData = e.detail
      const viewport = this.$cornerstone.getViewport(this.curElement)
      const dcmaxTools = this.$cornerstoneTools.getToolState(this.curElement, 'stack')
      this.zoomValue = viewport.scale.toFixed(2)
      this.wwwcValue = Math.round(viewport.voi.windowWidth) + '/' + Math.round(viewport.voi.windowCenter)
      this.renderTime = contextData.renderTimeInMs.toFixed(2)
      if (dcmaxTools && dcmaxTools.data && dcmaxTools.data.length) {
        this.curIndex = dcmaxTools.data[0].currentImageIdIndex + 1
      }
    },
    initData() {
      if (this.instanceList.length === 1 && this.fileType === 'DCM') {
        this.curElement = this.$refs.imgElement
        const imageUrl = this.instanceList[0].imageId
        this.drawCornerStone(imageUrl, 'DCM')
        this.handleResize()
      } else if (this.instanceList.length === 1 && (this.fileType === 'JPG' || this.fileType === 'PNG')) {
        this.curElement = this.$refs.imgElement
        const imageUrl = this.instanceList[0].imageId
        this.drawCornerStone(imageUrl, 'JPG')
        this.handleResize()
      } else if (this.instanceList.length > 1 && (this.fileType === 'JPG' || this.fileType === 'PNG')) {
        this.curElement = this.$refs.imgElement
        this.childrenList = this.instanceList
        this.setScroll()
        this.handleResize()
      } else if (this.instanceList.length > 1 && this.fileType === 'DCM') {
        console.log('序列', this.instanceList)
        this.curElement = this.$refs.dicomElement
        this.childrenList = this.instanceList
        this.setScroll()
        this.handleResize()
      } else if (this.fileType === 'PDF') {
        console.log('pdf')
        this.pdfUrl = this.instanceList[0].imageId
        this.total = this.instanceList.length
      }
      // if (this.curFile && this.curFile.fileType === 'DCM') {
      //   this.curElement = this.$refs.dicomElement
      //   const imageUrl = this.curFile.filePath
      //   this.drawCornerStone(imageUrl, 'DCM')
      //   // 每当图像被cornerstone重新绘制时，将发出CornerstoneImageRendered事件调用
      //   this.curElement.addEventListener('cornerstoneimagerendered', this.getZoomRate)// 监听事件
      // } else if (this.curFile && (this.curFile.fileType === 'JPG' || this.curFile.fileType === 'PNG')) {
      //   const imageUrl = this.curFile.filePath
      //   this.curElement = this.$refs.imgElement
      //   this.drawCornerStone(imageUrl, 'JPG')
      //   this.curElement.addEventListener('cornerstoneimagerendered', this.getZoomRate)// 监听事件
      // }
    }
  }
}

</script>
<style lang="scss" scoped>
  .container {
    color: #FFFFFF;
    width: 100%;
    height: 100%;
    overflow: hidden;
    text-align: center;

    .dicom{
      width: 100% !important;
      height: 100% !important;
    }
  }
</style>
<style lang="scss">
.container{
  .cornerstone-canvas{
    width: 100%;
  }
}
</style>
