/* eslint-disable no-unused-vars */
<template>
  <div 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')" />
          </div>
        </div>
        <!-- 图片 -->
        <div id="image-viewer__canvas" class="image-viewer__canvas">
          <img
            v-for="(item, i) in urlList"
            v-show="i === index"
            :ref="`img${i}`"
            :key="item.Id"
            crossorigin="anonymous"
            :src="`${OSSclientConfig.basePath}${item.Path}`"
            :style="imgStyle"
            style="max-width:100%;max-height: 100%;"
            @load="handleImgLoad"
            @error="handleImgError"
            @mousedown="handleMouseDown"
          >

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

  </div>

</template>

<script>
import { on, off } from 'element-ui/src/utils/dom'
import { rafThrottle, isFirefox } from 'element-ui/src/utils/util'

const mousewheelEventName = isFirefox() ? 'DOMMouseScroll' : 'mousewheel'

export default {
  name: 'ImageViewer',
  props: {
    urlList: {
      type: Array,
      default: () => []
    },
    studyCode: {
      type: String,
      default: ''
    },
    bodyPart: {
      type: String,
      default: ''
    },
    modality: {
      type: String,
      default: ''
    },
    onSwitch: {
      type: Function,
      default: () => {}
    },
    onClose: {
      type: Function,
      default: () => {}
    },
    initialIndex: {
      type: Number,
      default: 0
    }
  },

  data() {
    return {
      index: this.initialIndex,
      isShow: false,
      infinite: true,
      loading: false,
      transform: {
        scale: 1,
        deg: 0,
        offsetX: 0,
        offsetY: 0,
        enableTransition: false
      }
    }
  },
  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)
      }
    }
  },
  mounted() {
    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: {
    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 = '加载失败'
    },
    handleMouseDown(e) {
      if (this.loading || e.button !== 0) return

      const { offsetX, offsetY } = this.transform
      const startX = e.pageX
      const startY = e.pageY
      this._dragHandler = rafThrottle(ev => {
        this.transform.offsetX = offsetX + ev.pageX - startX
        this.transform.offsetY = offsetY + ev.pageY - startY
      })
      on(document, 'mousemove', this._dragHandler)
      on(document, 'mouseup', ev => {
        off(document, 'mousemove', this._dragHandler)
      })

      e.preventDefault()
    },
    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>
