import "core-js/modules/es6.regexp.replace";
import "core-js/modules/es6.regexp.constructor";
import "core-js/modules/es6.regexp.match";
import "core-js/modules/es6.regexp.split";

/**
 * @desc 输入数字或小数
 * type为number/tel/text，推荐用number/tel
 * 可配置maxlength
 * 初始化不要用v-model,用:value="num"
 * v-number-input/v-number-input:0 为输入整数
 * v-number-input:x x为小数的个数
 * eg： <input type="number"
               maxlength="5"
               :value="num"
               v-number-input:2="num"/>
 * 配置方式：
   1.局部配置
   import numberInput from 'components/utils/directives/numberInput';
   export default {
     directives: { numberInput }
   }
   <input type="tel"
             placeholder="点击输入手机号"
             class="ipt mt20"
             maxlength="11"
             :value="formData.mobile"
             v-number-input="formData.mobile" />

   2.全局配置
   在main.js入口
   import numberInput from 'components/utils/directives/numberInput';
   全局注册指令
   Vue.use(numberInput);

 * @author wzf
 */
var getObjKey = function getObjKey(obj, key) {
  var arr = key && key.split('.');

  for (var i = 0, len = arr.length - 1; i < len; i++) {
    obj = arr[i] && obj[arr[i]];
  }

  return obj;
};

var numberInput = {
  bind: function bind(el, binding, vnode) {
    var arg = binding.arg,
        expression = binding.expression;
    var temp = expression.split('.');
    var prop = temp[temp.length - 1];
    var ml = vnode.elm.maxLength;

    el.handler = function () {
      var val;

      if (arg && arg !== '0') {
        // el.value = el.value.match(/^\d*(\.?\d{0,1})/g)[0] || null;
        el.value = el.value.match(new RegExp("\\d*(\\.?\\d{0,".concat(arg, "})"), 'g'))[0] || null;
        ml > 0 && (el.value = el.value.length > ml ? el.value.slice(0, ml) : el.value);
        val = parseFloat(el.value);
      } else {
        el.value = el.value.replace(/[^\d]/g, '');
        ml > 0 && (el.value = el.value.length > ml ? el.value.slice(0, ml) : el.value);
        val = parseInt(el.value);
      }

      getObjKey(vnode.context, expression)[prop] = val || '';
    };

    el.addEventListener('input', el.handler);
  },
  unbind: function unbind(el) {
    el.removeEventListener('input', el.handler);
  }
};
Object.defineProperty(numberInput, 'install', {
  configurable: false,
  enumerable: false,
  value: function value(Vue, options) {
    Vue.directive('numberInput', numberInput);
  }
});
export default numberInput;