import Vue from 'vue'

/**
 * dragClass:'.ivu-modal-header' 可以进行点击拖动位置
 * boxClass:'.ivu-modal'" 进行拖动整体外层class
 */

Vue.directive('drag', function(el, binding) {
  Vue.nextTick(() => {
    const dragClass = '.ivu-modal-header'
    const boxClass = '.ivu-modal'

    // let dragHeader = el.querySelector(binding.value.dragClass);
    // let dragDom = el.querySelector(binding.value.boxClass);

    const dragHeader = el.querySelector(dragClass)
    const dragDom = el.querySelector(boxClass)

    const getStyle = (function() {
      if (window.document.currentStyle) {
        return (dom, attr) => dom.currentStyle[attr]
      } else {
        return (dom, attr) => getComputedStyle(dom, false)[attr]
      }
    })()
    if (dragDom) {
      dragHeader.style.cursor = 'move'
      dragHeader.onmousedown = function(e) {
        const disX = e.clientX - dragHeader.offsetLeft
        const disY = e.clientY - dragHeader.offsetTop

        let styleLeft = getStyle(dragDom, 'left')
        let styleTop = getStyle(dragDom, 'top')

        if (styleLeft.includes('%')) {
          styleLeft =
            +document.body.clientWidth * (+styleLeft.replace(/%/g, '') / 100)
          styleTop =
            +document.body.clientHeight * (+styleTop.replace(/%/g, '') / 100)
        } else {
          styleLeft = +styleLeft.replace(/px/g, '')
          styleTop = +styleTop.replace(/px/g, '')
        }
        document.onmousemove = function(e) {
          const left = e.clientX - disX
          const top = e.clientY - disY
          dragDom.style.left = left + styleLeft + 'px'
          dragDom.style.top = top + styleTop + 'px'
        }
        document.onmouseup = function(e) {
          document.onmousemove = null
          document.onmouseup = null
        }
      }
    }
  })
})
