<template>
  <div class="home">
    <div
      class="image-box dropContainer"
      ref="maskBox"
      @touchmove="touchmove"
      @touchstart="touchstart"
    >
      <!-- @touchend="onmousedownHandle" -->
      <img
        id="Drop"
        :src="src"
        alt=""
        :style="{
          width: imgW + 'px',
          height: 'auto',
          top: top + 'px',
          left: left + 'px',
          transform: scale
        }"
      />
    </div>
    <img class="bgsrc" :src="bgsrc" alt="" />
  </div>
</template>

<script>
export default {
  name: 'HomeView',
  props: {
    src: {
      type: String,
      default: 'https://4dscene.4dage.com/new4dkk/deng/static/img/bg03@2x.png'
    },
    bgsrc: {
      type: String,
      default: 'https://4dscene.4dage.com/new4dkk/deng/static/img/bg03@2x.png'
    }
  },
  data() {
    return {
      imageUrl: 'https://4dscene.4dage.com/new4dkk/deng/static/img/bg03@2x.png',
      imgW: 0,
      imgW: 0,
      imgH: 0,
      deg: 0,
      top: 0,
      left: 0,
      scale: 'scale(1)',
      myscale: 0,
      size: 0,
      // 位置差
      disX: 0,
      disY: 0,
      DropEl: null,
      dropContainer: null,
      mousewheelevt: null
    }
  },
  mounted() {
    // 获取元素
    let that = this
    this.DropEl = document.getElementById('Drop')
    this.dropContainer = document.getElementsByClassName('dropContainer')[0]
    console.log(this.DropEl)
    // this.imageUrl = this.imageUrl1
    //初始化图片
    this.initImage()
    var container = this.DropEl
    var startX, startY, myscale
    var distanceStart, distanceEnd

    container.addEventListener('touchstart', function (e) {
      var touches = e.touches
      if (touches.length == 2) {
        // 双指触摸
        startX = Math.abs(touches[0].pageX - touches[1].pageX)
        startY = Math.abs(touches[0].pageY - touches[1].pageY)
        distanceStart = Math.sqrt(startX * startX + startY * startY) // 计算两个触点之间的距离
      }
    })

    container.addEventListener('touchmove', function (e) {
      var touches = e.touches
      if (touches.length == 2) {
        // 双指触摸
        var endX = Math.abs(touches[0].pageX - touches[1].pageX)
        var endY = Math.abs(touches[0].pageY - touches[1].pageY)
        distanceEnd = Math.sqrt(endX * endX + endY * endY) // 计算两个触点之间的距离
        var distanceDiff = distanceEnd - distanceStart // 计算距离差值
        console.log(distanceDiff, 'distanceDiff')
        var scale = (distanceEnd / distanceStart)// 计算缩放比例
        if(distanceDiff>0){
          scale += that.myscale
        }else{
          // scale -= that.myscale
        }
        // + that.myscale
        // 根据缩放比例来缩放图片或其他内容
        myscale = scale
        that.scale = 'scale(' + scale + ')'
        container.style.transform = 'scale(' +  scale + ')'
        console.log(scale, 'scale', that.myscale)
      }
    })
    // container.addEventListener('touchend', function (e) {
    //   this.myscale = myscale
    //   console.log(myscale, 'mouseout', that.myscale)
    // })
    container.addEventListener('touchend', function (e) {
      startX = null
      startY = null
      distanceStart = null
      distanceEnd = null
      that.myscale = myscale
      console.log(myscale, 'mouseout', that.myscale)
    })
    // 兼容火狐浏览器
    this.mousewheelevt = /Firefox/i.test(navigator.userAgent) ? 'DOMMouseScroll' : 'mousewheel'
    // 为空间区域绑定鼠标滚轮事件 =》 处理函数是wheelHandle
    // 如果你监听了window的scroll或者touchmove事件，你应该把passive设置为true，这样滚动就会流畅很多
    this.$refs.maskBox.addEventListener(this.mousewheelevt, this.wheelHandle, { passive: true })
  },
  beforeDestroy() {
    //取消监听
    this.$refs.maskBox.removeEventListener(this.mousewheelevt, this.wheelHandle, { passive: true })
  },
  methods: {
    // 手指落下时触发
    touchstart(event) {
      // 1，计算位置差 因为clientX和offsetLeft的属性返回的位置不一样 要相减得到拖动元素内实际点击的位置
      // pageX 永远大于等于 offsetLeft pageY也是同理
      this.disX = event.targetTouches[0].pageX - this.DropEl.offsetLeft
      this.disY = event.targetTouches[0].pageY - this.DropEl.offsetTop
    },
    // 手指移动时触发
    touchmove(event) {
      // 2，获取手指移动的实时位置  需要减去位置差
      let moveX = event.targetTouches[0].pageX - this.disX
      let moveY = event.targetTouches[0].pageY - this.disY

      // 3，获取容器的宽高和拖动元素的宽高  每一次移动都会获取一次 ，建议放在外面进行获取
      let dragHeight = this.DropEl.offsetHeight
      let dragWidth = this.DropEl.offsetWidth
      let dragContainerWidth = this.dropContainer.offsetWidth //获取容器的高度和宽度
      let dragContainerHeight = this.dropContainer.offsetHeight

      // 4，控制范围：在元素 被拖拽的过程中 判断 元素的定位值 是否到达边界 如果到了 就不能在走了
      // if (moveX <= 0) {
      //   moveX = 0;
      // }
      // // 上边界
      // if (moveY <= 0) {
      //   moveY = 0;
      // }
      //下边界  容器高度 - 拖动元素高度
      // if (moveY >= dragContainerHeight - dragHeight) {
      // moveY = dragContainerHeight - dragHeight;
      // }
      //右边界   容器宽度 - 拖动元素宽度
      // if (moveX >= dragContainerWidth - dragWidth) {
      // moveX = dragContainerWidth - dragWidth;
      // }
      // 5，开始移动
      console.log(moveX, moveY, 'moveX, moveY')
      this.left = moveX
      this.top = moveY
      // this.style.left = moveX + "px";
      // this.style.top = moveY + "px";
    },
    /**
     * 切换图片
     *  flag: 1竖图 2 横图
     */
    switchImgHandle(flag) {
      if (flag === 1) {
        this.imageUrl = this.imageUrl1
      } else {
        this.imageUrl = this.imageUrl2
      }
      this.handleReset()
    },
    /**
     * 获取图片的url
     * @param {string} url
     */
    getImgSize(url) {
      return new Promise((resolve, reject) => {
        let imgObj = new Image()
        imgObj.src = url
        imgObj.onload = () => {
          resolve({
            width: imgObj.width,
            height: imgObj.height
          })
        }
      })
    },
    /**
     * 初始化图片
     */
    async initImage() {
      if (!this.imageUrl) {
        return
      }
      let { width, height } = await this.getImgSize(this.imageUrl)
      // 设置原始图片的大小
      let realWidth = width
      let realHeight = height

      // 获取高宽比例
      const whRatio = realWidth / realHeight
      const hwRatio = realHeight / realWidth

      //获取盒子的大小
      const boxW = this.$refs.maskBox.clientWidth
      const boxH = this.$refs.maskBox.clientHeight

      if (realWidth >= realHeight) {
        this.imgH = hwRatio * boxW
        const nih = this.imgH
        if (nih > boxH) {
          this.imgH = boxH
          this.imgW = whRatio * boxH
        } else {
          this.imgW = boxW
        }
        this.top = (boxH - this.imgH) / 2
        this.left = (boxW - this.imgW) / 2
      } else {
        this.imgW = (boxH / realHeight) * realWidth
        this.imgH = boxH
        this.left = (boxW - this.imgW) / 2
      }
    },
    /**
     * 旋转
     */
    handleRotate() {
      this.deg += 90
      if (this.deg >= 360) {
        this.deg = 0
      }
      this.size = 0
      this.scale = `${this.scale} rotateZ(${this.deg}deg)`
    },

    /**
     * 图片的缩放
     *    zoom >0 放大
     *    zoom <0 缩小
     */
    imgScaleHandle(zoom) {
      this.size += zoom
      if (this.size < -0.5) {
        this.size = -0.5
      }
      this.scale = `scale(${1 + this.size}) rotateZ(${this.deg}deg)`
    },

    /**
     * 重置
     */
    handleReset() {
      this.imgW = 0
      this.imgH = 0
      this.top = 0
      this.left = 0
      this.deg = 0
      this.scale = 'scale(1)'
      this.size = 0
      this.initImage()
    },

    /**
     * 鼠标滚动 实现放大缩小
     */
    wheelHandle(e) {
      const ev = e || window.event // 兼容性处理 => 火狐浏览器判断滚轮的方向是属性 detail，谷歌和ie浏览器判断滚轮滚动的方向是属性 wheelDelta
      // dir = -dir; // dir > 0 => 表示的滚轮是向上滚动，否则是向下滚动 => 范围 (-120 ~ 120)
      const dir = ev.detail ? ev.detail * -120 : ev.wheelDelta
      //滚动的数值 / 2000 => 表示滚动的比例，用此比例作为图片缩放的比例
      this.imgScaleHandle(dir / 2000)
    },

    /**
     * 处理图片拖动
     */
    onmousedownHandle(e) {
      console.log('onmousedownHandle', e)
      const that = this
      this.$refs.maskBox.onmousemove = function (el) {
        const ev = el || window.event // 阻止默认事件
        ev.preventDefault()
        that.left += ev.movementX
        that.top += ev.movementY
      }
      this.$refs.maskBox.onmouseup = function () {
        // 鼠标抬起时将操作区域的鼠标按下和抬起事件置为null 并初始化
        that.$refs.maskBox.onmousemove = null
        that.$refs.maskBox.onmouseup = null
      }
      if (e.preventDefault) {
        e.preventDefault()
      } else {
        return false
      }
    }
  }
}
</script>

<style scoped>
.home {
  width: 100%;
  margin: 50px auto;
  position: relative;
  height: 100%;
}

.bgsrc {
  width: 100%;
    height: auto;
    object-fit: cover;
    pointer-events: none;
    position: relative;
    z-index: 10;
    left: 0;
    top: 0;
    z-index: 3;
}
.btn-area {
  display: flex;
  justify-content: center;
  width: 100%;
  margin-bottom: 50px;
}
.btn-area button {
  width: 100px;
  height: 40px;
  font-size: 18px;
  margin-right: 10px;
}
.image-box {
  position: relative;
  margin: 0 auto;
  width: 100%;
  height: 100%;
  /* height: calc(100vh - 300px); */
  /* border: 1px solid #333; */
  overflow: hidden;
  position: absolute;

}
.image-box img {
  position: absolute;
  cursor: pointer;
}
</style>

