/**
 * 使用v-format-number="{ chunkSizes: [3, 4, 4], separator: '-' }"
 */
function check(el: any, binding: any) {
  const inputEl = el.tagName === 'INPUT' ? el : el.querySelector('input');
  inputEl.addEventListener('input', function () {
    const maxLength = binding.value.maxLength || 11;
    const separator = binding.value.separator || ' ';
    const chunkSizes = binding.value.chunkSizes || [4, 4, 4, 4];
    let trimmed = inputEl.value.replace(/\s+/g, '').slice(0, maxLength);
    let chunks = [];
    let i = 0;
    chunkSizes.forEach(chunkSize => {
      let chunk = trimmed.slice(i, i + chunkSize);
      if (chunk.length > 0) {
        chunks.push(chunk);
      }
      i += chunkSize;
    });
    inputEl.value = chunks.join(separator);
  });
}

export default {
  mounted(el: any, binding: any) {
    check(el, binding);
  },

  updated(el: any, binding: any) {
    check(el, binding);
  }
};
