<!--图片标记-->
<template>
  <div v-loading="loading" style="width:100%;height:100%;">
    <transition name="viewer-fade">
      <div v-show="urlList.length > 0" ref="image-viewer__wrapper" tabindex="-1" class="image-viewer__wrapper" :style="{ 'z-index':5 }">
        <span class="image-viewer_desc">
          <!-- <span v-if="studyCode">NST00006</span>
          <span v-if="modality">CT</span>
          <span v-if="bodyPart">上/下腹部</span><br> -->
          {{ `${index+1} / ${urlList.length}` }}
        </span>
        <!-- 关闭 -->
        <span class="image-viewer__btn image-viewer__close" @click="hide">
          <i class="el-icon-close" />
        </span>
        <!-- Arrow -->
        <template v-if="!isSingle">
          <span
            class="image-viewer__btn image-viewer__prev"
            :class="{ 'is-disabled': !infinite && isFirst }"
            @click="prev"
          >
            <i class="el-icon-arrow-left" />
          </span>
          <span
            class="el-image-viewer__btn el-image-viewer__next"
            :class="{ 'is-disabled': !infinite && isLast }"
            @click="next"
          >
            <i class="el-icon-arrow-right" />
          </span>
        </template>
        <!-- 工具栏 -->
        <div class="image-viewer__btn image-viewer__actions">
          <div class="image-viewer__actions__inner">
            <i class="el-icon-zoom-out" @click="handleActions('zoomOut')" />
            <i class="el-icon-zoom-in" @click="handleActions('zoomIn')" />
            <i class="el-image-viewer__actions__divider" />
            <i class="el-icon-c-scale-to-original" @click="toggleMode" />
            <i class="el-image-viewer__actions__divider" />
            <i class="el-icon-refresh-left" @click="handleActions('anticlocelise')" />
            <i class="el-icon-refresh-right" @click="handleActions('clocelise')" />
            <i
              class="el-icon-bottom-right"
              :style="{cursor:isToolDisabled || readingTaskState >=2 ?'not-allowed':'pointer'}"
              @click="handleDrawArrow"
            />
          </div>
        </div>
        <!-- 图片 -->
        <div id="image-viewer__canvas" class="image-viewer__canvas">
          <canvas
            v-if="canvasSize.width && canvasPosition.y"
            id="canvas"
            :height="canvasSize.height"
            :width="canvasSize.width"
            :style="imgStyle"
            @mousedown="handleMouseDown"
            @mousemove="handleMouseMove"
            @mouseup="handleMouseUp"
            @contextmenu="handleContextmenu"
          />

        </div>
      </div>
    </transition>

  </div>
</template>
<script>
import { on, off } from 'element-ui/src/utils/dom'
import { rafThrottle, isFirefox } from 'element-ui/src/utils/util'
import store from '@/store'
const mousewheelEventName = isFirefox() ? 'DOMMouseScroll' : 'mousewheel'
var ctx = '' // 画布上下文
export default {
  name: 'CustomizeNoneDicomsCanvas',
  props: {
    readingTaskState: {
      type: Number,
      default: 2
    },
    urlList: {
      type: Array,
      default: () => []
    },
    studyCode: {
      type: String,
      default: ''
    },
    bodyPart: {
      type: String,
      default: ''
    },
    modality: {
      type: String,
      default: ''
    },
    studyId: {
      type: String,
      default: ''
    },
    onSwitch: {
      type: Function,
      default: () => {}
    },
    onClose: {
      type: Function,
      default: () => {}
    },
    initialIndex: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      loading: false,
      index: this.initialIndex,
      isShow: false,
      infinite: true,
      transform: {
        scale: 1,
        deg: 0,
        offsetX: 0,
        offsetY: 0,
        enableTransition: false
      },
      imgUrl: '',
      ctx: null,
      canvasPosition: { x: '', y: '' }, // 画布位置
      canvasSize: { height: '', width: '' }, // 画布尺寸
      canvasMousePosition: { x: '', y: '' }, // 画布中鼠标位置
      mousePosition: { x: '', y: '' }, // 屏幕中鼠标位置
      color: 'rgb(255, 255, 0)',
      lineWidth: 2,
      isMouseDown: false,
      canvasMouseStart: { x: '', y: '' },
      model: '',
      currentImg: '',
      imgId: '',
      currentDrawData: {},
      canvasData: [],
      imgZoom: 1,
      isToolDisabled: false,
      lesionName: '',
      visitTaskId: '',
      isInit: false,
      imgSize: { height: '', width: '' } // 图片原始尺寸
    }
  },
  computed: {
    isSingle() {
      return this.urlList.length <= 1
    },
    isFirst() {
      return this.index === 0
    },
    isLast() {
      return this.index === this.urlList.length - 1
    },

    imgStyle() {
      const { scale, deg, offsetX, offsetY, enableTransition } = this.transform
      const style = {
        transform: `scale(${scale}) rotate(${deg}deg)`,
        transition: enableTransition ? 'transform .3s' : '',
        'margin-left': `${offsetX}px`,
        'margin-top': `${offsetY}px`
      }
      return style
    }
  },
  watch: {
    initialIndex: {
      immediate: true,
      handler(val) {
        this.index = val
      }
    },
    index: {
      immediate: true,
      handler(val) {
        this.reset()
        this.onSwitch(val)

        this.imgUrl = this.urlList[val].Path
        this.imgId = this.urlList[val].Id
        this.loadImage()
      }
    }
  },
  mounted() {
    window.addEventListener('message', this.receiveMsg)
    document.getElementById('image-viewer__canvas').onmousewheel = (event) => {
      if (event.deltaY > 0) {
        // 缩小
        this.handleActions('zoomOut', {
          zoomRate: 0.015,
          enableTransition: false
        })
      } else {
        // 放大
        this.handleActions('zoomIn', {
          zoomRate: 0.015,
          enableTransition: false
        })
      }
      return false
    }
    this.deviceSupportInstall()
  },
  methods: {
    getCanvasData() {
      return new Promise(async resolve => {
        this.visitTaskId = this.$router.currentRoute.query.visitTaskId
        this.canvasData = []
        await store.dispatch('reading/getMeasuredData', this.visitTaskId)
        await store.dispatch('reading/getNoneDicomMeasuredData', this.visitTaskId).then(res => {
          res.forEach(item => {
            if (item && item.MeasureData) {
              this.canvasData.push(item.MeasureData)
            }
          })
          console.log('getCanvasData添加')
          sessionStorage.setItem('measureData', this.canvasData)
        })
        resolve()
      })
    },
    async loadImage() {
      this.loading = true
      if (!this.isInit) {
        await this.getCanvasData()
        this.isInit = true
      }
      const img = new Image() // 创建img标签
      img.src = this.imgUrl // 添加src
      return new Promise(resolve => {
        img.onload = () => {
          this.currentImg = img
          this.loading = false
          this.initCanvas(img)

          resolve(img) // 返回标签
        }
      })
    },
    handleDrawArrow() {
      var data = { type: 'isCanActiveNoneDicomTool', data: '' }
      window.opener.postMessage(data, window.location)
      // this.model = 'ArrowAnnotate'
    },
    async receiveMsg(event) {
      console.log('nonedicoms', event.data.type)
      if (event.data.type === 'isCanActiveNoneDicomTool') {
        if (event.data.data.isCanActiveTool) {
          this.model = 'ArrowAnnotate'
          this.lesionName = event.data.data.lesionName
        } else {
          if (!event.data.data.reason) return

          this.$confirm(event.data.data.reason, {
            type: 'warning',
            distinguishCancelAndClose: true,
            showCancelButton: false
          }).then(() => {

          })
        }
      } else if (event.data.type === 'removeNoneDicomMeasureData') {
        // for (var i = this.canvasData.length - 1; i >= 0; i--) {
        //   if (this.canvasData[i] && this.canvasData[i].data && this.canvasData[i].data.uuid === event.data.data.data.uuid) {
        //     this.canvasData.splice(i, 1)
        //   }
        // }
        // for (var i = 0; i < this.canvasData.length; i++) {
        //   if (this.canvasData[i] && this.canvasData[i].data && this.canvasData[i].data.uuid === event.data.data.data.uuid) {
        //     this.canvasData.splice(i, 1)
        //   }
        // }
        var idx = this.canvasData.findIndex(item => item.data.uuid === event.data.data.data.uuid)
        this.canvasData.splice(idx, 1)

        console.log('移除', event.data.data.data.uuid, this.canvasData)
        ctx.clearRect(0, 0, this.canvasSize.width, this.canvasSize.height) // 清除画布后立刻重新绘制视觉上形成动画
        await ctx.drawImage(
          this.currentImg,
          0,
          0,
          this.canvasSize.width,
          this.canvasSize.height
        )
        this.drawToArr() // 重绘列表数据
        this.isMouseDown = false // 关闭鼠标状态
        this.model = ''
        this.lesionName = ''
      } else if (event.data.type === 'addNoneDicomMeasureData') {
        for (let i = this.canvasData.length - 1; i >= 0; i--) {
          if (this.canvasData[i] && this.canvasData[i].data && this.canvasData[i].data.uuid === event.data.data.data.uuid) {
            this.canvasData[i] = event.data.data
            console.log('添加', event.data.data, event.data.data.data.uuid, this.canvasData)
            break
          }
        }

        ctx.clearRect(0, 0, this.canvasSize.width, this.canvasSize.height) // 清除画布后立刻重新绘制视觉上形成动画
        await ctx.drawImage(
          this.currentImg,
          0,
          0,
          this.canvasSize.width,
          this.canvasSize.height
        )
        this.drawToArr() // 重绘列表数据
        this.isMouseDown = false // 关闭鼠标状态
        this.model = ''
        this.lesionName = ''
      }
    },
    // 初始化画布
    initCanvas(img) {
      this.loading = true
      this.canvasSize.height = img.height
      this.canvasSize.width = img.width

      this.imgSize.height = img.height
      this.imgSize.width = img.width

      const canvasDiv = document.getElementsByClassName('image-viewer__canvas')[0]
      this.canvasPosition = {
        x: canvasDiv.offsetWidth / 2 - img.width / 2,
        y: canvasDiv.offsetHeight / 2 - img.height / 2 - 25
      } // 背景居中

      this.$nextTick(async() => {
        ctx = document.getElementById('canvas').getContext('2d') // 获取上下文
        await ctx.drawImage(img, 0, 0, img.width, img.height) // 在canvas中绘制图片(图片、起始位置、绘图尺寸)
        this.drawToArr()
        this.loading = false
      })
    },

    // 清空画布
    clearCanvas() {
      this.canvasData = [] // 清空图形数据
      this.currentDrawData = {} // 清空当前绘图数据
      ctx.clearRect(0, 0, this.canvasSize.width, this.canvasSize.height) // 清除画布图形
      ctx.drawImage(
        this.currentImg,
        0,
        0,
        this.canvasSize.width,
        this.canvasSize.height
      ) // 重绘背景
    },

    // 阻止默认右键冒泡事件，去除右键菜单
    handleContextmenu(e) {
      e.preventDefault()
    },

    // 鼠标按下事件
    handleMouseDown(e) {
      if (e.button !== 0) {
        return
      }
      this.isMouseDown = true // 打开鼠标状态
      // 获取画布中鼠标开始点击位置
      this.canvasMouseStart = {
        x: e.offsetX,
        y: e.offsetY
      }
    },

    // 鼠标移动事件
    async handleMouseMove(e) {
      // 获取屏幕中鼠标位置(显示实时坐标)
      this.mousePosition = {
        x: e.pageX,
        y: e.pageY
      }
      // 获取画布中鼠标位置
      this.canvasMousePosition = {
        x: e.offsetX,
        y: e.offsetY
      }
      // 判断是否超出边界
      if (e.offsetX < 0 || e.offsetY < 0 || e.offsetX === 0 || e.offsetY === 0) {
        this.isMsg = false
        this.isMouseDown = false // 关闭鼠标状态
      }
      // 判断鼠标状态是否打开
      if (!this.isMouseDown) {
        return
      }
      ctx.clearRect(0, 0, this.canvasSize.width, this.canvasSize.height) // 清除画布后立刻重新绘制视觉上形成动画
      await ctx.drawImage(
        this.currentImg,
        0,
        0,
        this.canvasSize.width,
        this.canvasSize.height
      ) // 在canvas中绘制图片
      await this.drawToArr() // 重绘列表数据
      // 绘制直线
      if (this.model === 'ArrowAnnotate') {
        this.drawArrowAnnotate(e)
      }
    },

    // 通过保存的大列表绘制图形
    async drawToArr() {
      // 遍历大列表开始绘制
      await this.canvasData.forEach((e) => {
        // 绘制直线
        if (e.instanceId === this.imgId && e.type === 'ArrowAnnotate') {
          var headlen = 10// 自定义箭头线的长度
          var theta = 45// 自定义箭头线与直线的夹角
          var arrowX, arrowY// 箭头线终点坐标
          var fromX = e.data.handles.start.x
          var fromY = e.data.handles.start.y
          var toX = e.data.handles.end.x
          var toY = e.data.handles.end.y
          // 计算各角度和对应的箭头终点坐标
          var angle = Math.atan2(fromY - toY, fromX - toX) * 180 / Math.PI
          var angle1 = (angle + theta) * Math.PI / 180
          var angle2 = (angle - theta) * Math.PI / 180
          var topX = headlen * Math.cos(angle1)
          var topY = headlen * Math.sin(angle1)
          var botX = headlen * Math.cos(angle2)
          var botY = headlen * Math.sin(angle2)

          // 画直线
          ctx.lineWidth = this.lineWidth
          ctx.beginPath()
          ctx.moveTo(fromX * this.imgZoom, fromY * this.imgZoom)
          ctx.lineTo(toX * this.imgZoom, toY * this.imgZoom)

          arrowX = toX + topX
          arrowY = toY + topY
          // 画上边箭头线
          ctx.moveTo(arrowX, arrowY)
          ctx.lineTo(toX, toY)

          arrowX = toX + botX
          arrowY = toY + botY
          // 画下边箭头线
          ctx.lineTo(arrowX, arrowY)
          this.drawText(ctx, { x: fromX, y: fromY }, { x: toX, y: toY }, e.data.remark, this.color)
          ctx.strokeStyle = this.color
          ctx.stroke()
        }
      })
    },

    // 鼠标松开事件
    handleMouseUp(e) {
      if (e.button !== 0) {
        return // 非左键松开
      }

      // 左键松开
      if (this.model === 'ArrowAnnotate') {
        for (const key in this.currentDrawData.data.handles) {
          this.currentDrawData.data.handles[key].x = this.currentDrawData.data.handles[key].x / this.imgZoom
          this.currentDrawData.data.handles[key].y = this.currentDrawData.data.handles[key].y / this.imgZoom
        }
        if (this.currentDrawData && this.currentDrawData.data) {
          console.log('handleMouseUp添加')
          this.canvasData.push(this.currentDrawData) // 添加当前绘图数据
        }
      }
      this.isMouseDown = false // 关闭鼠标状态
      this.model = ''
      this.lesionName = ''
      this.canvasMousePosition = {
        x: e.offsetX, // 更新位置
        y: e.offsetY
      }
      // 向主窗体发送测量数据
      var data = { type: 'setMeasurement', data: this.currentDrawData }
      window.opener.postMessage(data, window.location)
    },

    // 画标注
    drawArrowAnnotate(e) {
      var headlen = 10// 自定义箭头线的长度
      var theta = 45// 自定义箭头线与直线的夹角
      var arrowX, arrowY// 箭头线终点坐标
      var fromX = this.canvasMouseStart.x
      var fromY = this.canvasMouseStart.y
      var toX = e.offsetX
      var toY = e.offsetY
      // 计算各角度和对应的箭头终点坐标
      var angle = Math.atan2(fromY - toY, fromX - toX) * 180 / Math.PI
      var angle1 = (angle + theta) * Math.PI / 180
      var angle2 = (angle - theta) * Math.PI / 180
      var topX = headlen * Math.cos(angle1)
      var topY = headlen * Math.sin(angle1)
      var botX = headlen * Math.cos(angle2)
      var botY = headlen * Math.sin(angle2)
      ctx.lineWidth = this.lineWidth
      ctx.beginPath()
      ctx.strokeStyle = this.color
      ctx.moveTo(this.canvasMouseStart.x, this.canvasMouseStart.y) // 画笔移动至(x,y)坐标
      ctx.lineTo(e.offsetX, e.offsetY) // 绘直线至(x,y)坐标
      arrowX = toX + topX
      arrowY = toY + topY
      // 画上边箭头线
      ctx.moveTo(arrowX, arrowY)
      ctx.lineTo(toX, toY)

      arrowX = toX + botX
      arrowY = toY + botY
      // 画下边箭头线
      ctx.lineTo(arrowX, arrowY)
      this.drawText(ctx, { x: fromX, y: fromY }, { x: toX, y: toY }, this.lesionName, this.color)
      ctx.stroke()
      this.currentDrawData = {
        isDicomReading: false,
        studyId: this.studyId,
        seriesId: '',
        instanceId: this.imgId,
        type: 'ArrowAnnotate',
        data: {
          handles: {
            start: { x: this.canvasMouseStart.x, y: this.canvasMouseStart.y },
            end: { x: e.offsetX, y: e.offsetY }
          },
          remark: this.lesionName,
          uuid: `${this.imgId}-${this.lesionName}`,
          toolName: 'ArrowAnnotate',
          toolType: 'ArrowAnnotate'
        }

      }
    },
    drawText(ctx, start, end, text, color) {
      if (text && text !== '') {
        const padding = 5
        const textWidth = this.textBoxWidth(ctx, text, padding)
        const fontSize = 12
        const textHeight = fontSize + 10

        let distance = Math.max(textWidth, textHeight) / 2 + padding

        if (end.x < start.x) {
          distance = -distance
        }
        var textCoords = {
          x: end.x - textWidth / 2 - distance,
          y: end.y - textHeight / 2
        }

        const boundingBox = {
          width: textWidth,
          height: padding + fontSize + padding
        }
        boundingBox.left = textCoords.x
        boundingBox.top = textCoords.y
        ctx.textBaseline = 'top'
        ctx.font = `${fontSize}px Arial`
        ctx.fillStyle = color
        ctx.fillText(
          text,
          boundingBox.left + padding,
          boundingBox.top + padding + fontSize + padding
        )
      }
    },
    textBoxWidth(context, text, padding) {
      const width = context.measureText(text).width

      return width + 2 * padding
    },
    hide() {
      this.deviceSupportUninstall()
      this.onClose()
    },
    deviceSupportInstall() {
      this._keyDownHandler = e => {
        e.stopPropagation()
        const keyCode = e.keyCode
        switch (keyCode) {
          // ESC
          case 27:
            this.hide()
            break
          // SPACE
          case 32:
            this.toggleMode()
            break
          // LEFT_ARROW
          case 37:
            this.prev()
            break
          // UP_ARROW
          case 38:
            this.handleActions('zoomIn')
            break
          // RIGHT_ARROW
          case 39:
            this.next()
            break
          // DOWN_ARROW
          case 40:
            this.handleActions('zoomOut')
            break
        }
      }
      this._mouseWheelHandler = rafThrottle(e => {
        const delta = e.wheelDelta ? e.wheelDelta : -e.detail
        if (delta > 0) {
          this.handleActions('zoomIn', {
            zoomRate: 0.015,
            enableTransition: false
          })
        } else {
          this.handleActions('zoomOut', {
            zoomRate: 0.015,
            enableTransition: false
          })
        }
      })
      on(document, 'keydown', this._keyDownHandler)

      on(document, mousewheelEventName, null)
      // on(document, mousewheelEventName, this._mouseWheelHandler)
    },
    deviceSupportUninstall() {
      off(document, 'keydown', this._keyDownHandler)
      off(document, mousewheelEventName, this._mouseWheelHandler)
      this._keyDownHandler = null
      this._mouseWheelHandler = null
    },
    handleImgLoad(e) {
      this.loading = false
    },
    handleImgError(e) {
      this.loading = false
      e.target.alt = '加载失败'
    },

    reset() {
      this.transform = {
        scale: 1,
        deg: 0,
        offsetX: 0,
        offsetY: 0,
        enableTransition: false
      }
    },
    toggleMode() {
      if (this.loading) return
      this.reset()
    },
    prev() {
      if (this.isFirst && !this.infinite) return
      const len = this.urlList.length
      this.index = (this.index - 1 + len) % len
    },
    next() {
      if (this.isLast && !this.infinite) return
      const len = this.urlList.length
      this.index = (this.index + 1) % len
    },
    handleActions(action, options = {}) {
      if (this.loading) return
      const { zoomRate, rotateDeg, enableTransition } = {
        zoomRate: 0.2,
        rotateDeg: 90,
        enableTransition: true,
        ...options
      }
      const { transform } = this
      switch (action) {
        case 'zoomOut':
          if (transform.scale > 0.2) {
            transform.scale = parseFloat((transform.scale - zoomRate).toFixed(3))
          }
          break
        case 'zoomIn':
          if (transform.scale < 5) {
            transform.scale = parseFloat((transform.scale + zoomRate).toFixed(3))
          }
          break
        case 'clocelise':
          transform.deg += rotateDeg
          break
        case 'anticlocelise':
          transform.deg -= rotateDeg
          break
      }
      transform.enableTransition = enableTransition
    }
  }
}
</script>
<style lang="scss" scoped>

.image-viewer__wrapper{
    position: relative;
    top:0;
    right:0;
    bottom:0;
    left:0;
    width: 100%;
    height: 100%;
}
.image-viewer__btn{
    position:absolute;
    z-index:1;
    display:flex;
    align-items:center;
    justify-content:center;
    border-radius:50%;
    opacity:.8;
    cursor:pointer;
    box-sizing:border-box;
    user-select:none
}

.image-viewer__close{
  display: none;
    top:40px;
    right:40px;
    width:40px;
    height:40px;
    font-size:40px
}
.image-viewer_desc{
  position:absolute;
  top:40px;
  left:40px;
  font-size:15px;
  padding: 5px;
  height: 30px;
  width: 70px;
  line-height: 20px;
  text-align: center;
  color: #fff;
  background-color: #606266;
  border-color: #fff;
  z-index: 1;
  border-radius: 17px;
  // border-radius: 2%;
}
.image-viewer__canvas{
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    width:100%;
    height:100%;
    display:flex;
    justify-content:center;
    align-items:center
}
.image-viewer__actions{
    left:50%;
    bottom:30px;
    transform:translateX(-50%);
    width:282px;
    height:44px;
    padding:0 23px;
    background-color:#606266;
    border-color:#fff;
    border-radius:22px
}
.image-viewer__actions__inner{
    width:100%;
    height:100%;
    text-align:justify;
    cursor:default;
    font-size:23px;
    color:#fff;
    display:flex;
    align-items:center;
    justify-content:space-around
}
.image-viewer__next,.image-viewer__prev{
    top:50%;
    width:44px;
    height:44px;
    font-size:24px;
    color:#fff;
    background-color:#606266;
    border-color:#fff
}
.image-viewer__prev{
    transform:translateY(-50%);
    left:40px
}
.image-viewer__next{
    transform:translateY(-50%);
    right:40px;
    text-indent:2px
}
.image-viewer__mask{
    position:absolute;
    width:100%;
    height:100%;
    top:0;
    left:0;
    opacity:.5;
    // background:#000

}
.viewer-fade-enter-active{
    animation:viewer-fade-in .3s
}
.viewer-fade-leave-active{
    animation:viewer-fade-out .3s
}

@keyframes viewer-fade-in{
    0%{
        transform:translate3d(0,-20px,0);
        opacity:0
    }
    100%{
        transform:translate3d(0,0,0);
        opacity:1
    }
}

@keyframes viewer-fade-out{
    0%{
        transform:translate3d(0,0,0);
        opacity:1
    }
    100%{
        transform:translate3d(0,-20px,0);
        opacity:0
    }
}
</style>
