
/**
 * @author pengliang on 2020/05/16 18:49
 */
import Vue from 'vue'

Vue.directive('tableLoadmore', {
  bind(el, binding) {
    const selectWrap = el.querySelector('.el-table__body-wrapper')
    selectWrap.addEventListener('scroll', function() {
      const sign = 0
      const scrollDistance = this.scrollHeight - this.scrollTop - this.clientHeight
      if (scrollDistance <= sign) {
        binding.value()
      }
    })
  }
})

Vue.directive('double', {
  bind: function(el) {
    const input = el.getElementsByTagName('input')[0]
    input.onkeyup = function(e) {
      if (input.value === '..') {
        input.value = ''
      } else if (input.value.endsWith('..')) {
        input.value = parseFloat(input.value)
      } else if (input.value && !input.value.endsWith('.')) {
        if (/^\d+/.test(input.value)) {
          input.value = parseFloat(input.value)
        } else {
          input.value = input.value.replace(/[^\d]/g, '')
        }
      }
      trigger(input, 'input')
    }
    input.onblur = function(e) {
      if (input.value === '..') {
        input.value = ''
      } else if (input.value.endsWith('..')) {
        input.value = parseFloat(input.value)
      } else if (input.value && !input.value.endsWith('.')) {
        if (/^\d+/.test(input.value)) {
          input.value = parseFloat(input.value)
        } else {
          input.value = input.value.replace(/[^\d]/g, '')
        }
      }
      trigger(input, 'input')
    }
  }
  // unbind: function(el) {
  //   el.removeEventListener('input', el.handler)
  // }
})

Vue.directive('number', {
  bind: function(el) {
    const input = el.getElementsByTagName('input')[0]
    input.onkeyup = function(e) {
      input.value = input.value.replace(/[^\d]/g, '')
      // el.addEventListener('input', el.handler)
      trigger(input, 'input')
    }
    input.onblur = function(e) {
      input.value = input.value.replace(/[^\d]/g, '')
      trigger(input, 'input')
    }
  }
  // unbind: function(el) {
  //   el.removeEventListener('input', el.handler)
  // }
})

const trigger = (el, type) => {
  const e = document.createEvent('HTMLEvents')
  e.initEvent(type, true, true)
  el.dispatchEvent(e)
}
