import Vue from 'vue'

/**
 * @author Jensonhui
 * @time 2021-11-06
 * @desc 限制手机号输入长度
 */
Vue.directive('onlyPhone', {
  bind: function (el) {
    el.inputHandler = () => {
      const value = el.value
      if (value.length > 11) {
        el.value = value.slice(0, 11)
      }
    }

    el.addEventListener('keyup', el.inputHandler)
  },

  unbind: function (el) {
    el.removeEventListener('keyup', el.inputHandler)
  }
})

/**
 * @author Jensonhui
 * @time 2021-11-11
 * @desc 限制验证码输入长度
 */
Vue.directive('phoneCodeLength', {
  bind: function (el) {
    el.inputHandler = () => {
      const value = el.value
      if (value.length > 6) {
        el.value = value.slice(0, 6)
      }
    }

    el.addEventListener('keyup', el.inputHandler)
  },

  unbind: function (el) {
    el.removeEventListener('keyup', el.inputHandler)
  }
})

/**
 * @author Jensonhui
 * @time 2021-11-11
 * @desc 时间format, <div>{{data | dateFormat('yyyy-MM-dd hh:mm:ss')}}
 */
Vue.filter('dateFormat', function (value, fmt) {
  const getDate = new Date(value)
  const o = {
    'M+': getDate.getMonth() + 1,
    'd+': getDate.getDate(),
    'h+': getDate.getHours(),
    'm+': getDate.getMinutes(),
    's+': getDate.getSeconds(),
    'q+': Math.floor((getDate.getMonth() + 3) / 3),
    S: getDate.getMilliseconds()
  }

  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (getDate.getFullYear() + '').substr(4 - RegExp.$1.length))
  }

  for (const k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
    }
  }

  return fmt
})