import Vue from 'vue';
export const defineDirective = () => {
  Vue.directive('draggable', {
    bind (el, binding) {
      //是否移动端
      if(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
        return
      }

      document.onselectstart = () => false
      let dom = el

      el.onmousedown = e => {
        e.stopPropagation();
        //e.preventDefault();
        //鼠标按下，计算当前元素距离可视区的距离
        let disX = e.clientX - dom.offsetLeft;
        let disY = e.clientY - dom.offsetTop;
        document.onmousemove = e => {
          binding.value(true)
          e.stopPropagation();
          //通过事件委托，计算移动的距离
          let l = e.clientX - disX;
          let t = e.clientY - disY;
          //移动当前元素
          dom.style.left = l + "px"
          dom.style.top = t + "px"
        }
        document.onmouseup = e => {
          e.stopPropagation();
          document.onmousemove = null;
          document.onmouseup = null;
          let content = dom.getBoundingClientRect()
          let {x,y} = content
          let bkg = { width: window.innerWidth, height: window.innerHeight }
          if(x < 0){
            dom.style.left = 0 + "px"
          }
          if(x > (bkg.width - content.width)){
            dom.style.left = (bkg.width - content.width) + "px"
          }
          if(y < 0){
            dom.style.top = 0 + "px"
          }
          if(y > (bkg.height - content.height)){
            dom.style.top = (bkg.height - content.height) + "px"
          }


          setTimeout(() => {
            binding.value(false)
          },500)
        };
        //return false不加的话可能导致黏连，就是拖到一个地方时div粘在鼠标上不下来，相当于onmouseup失效
        //return false;
      };
    },
  })
}
