export default {
  inserted(el, { value, modifiers }, vnode) {
    let lastTime = null;
    let nextTime = null;
    let code = "";
    let setT = "";
    el.focus();
    el.addEventListener("keydown", function(e) {
      if (modifiers.prevent) {
        e.preventDefault();
      }

      const keycode = e.keyCode || e.which || e.charCode;
      nextTime = new Date().getTime();
      if (setT) clearTimeout(setT);
      // 扫码枪输入完毕之后，会自动输入一个回车
      if (keycode === 13) {
        if (lastTime && nextTime - lastTime < 30) {
          if (value && value.inputOver) value.inputOver(code);
        }
        code = "";
        lastTime = null;
        e.preventDefault();
      } else {
        if (!lastTime) {
          code = String.fromCharCode(keycode);
          lastTime = nextTime;
        } else {
          if (nextTime - lastTime < 30) {
            code += String.fromCharCode(keycode);
            lastTime = nextTime;
          } else {
            code = "";
            lastTime = null;
          }
          if (value && value.inputOver) value.inputOver(code);
        }
        // bug:当手动输入之后，再扫描输入时，会首字符缺失
        // fix：设置定时清理上次输入和时间，暂时解决上述bug
        setT = setTimeout(() => {
          code = "";
          lastTime = null;
          if (value && value.inputOver) value.inputOver(code);
        }, 80);
      }
    });
  }
};
