<template>
  <div>
    <div class="kole-code" @paste="onPaste">
      <div
        v-for="(c, i) in cells"
        :key="i"
        class="kole-code-cell"
        :class="{ 'is-focus': focusedIndex === i, 'is-filled': !!cells[i], 'is-masked': masked }"
      >
        <input
          ref="inputs"
          class="kole-code-input"
          :value="cells[i]"
          maxlength="1"
          inputmode="numeric"
          :aria-label="'验证码第 ' + (i + 1) + ' 位'"
          @focus="focusedIndex = i"
          @input="onInput($event, i)"
          @keydown="onKeydown($event, i)"
        />
      </div>
    </div>
    <div class="kole-code-tip" :class="{ error: hasError }">{{ tip }}</div>
  </div>
</template>

<script>
export default {
  name: 'KoleCodeInput',
  props: {
    value: { type: String, default: '' },
    length: { type: Number, default: 6 },
    masked: { type: Boolean, default: false },
    tip: { type: String, default: '' },
    hasError: { type: Boolean, default: false }
  },
  data() {
    return {
      cells: this.value.split('').slice(0, this.length).concat(Array(Math.max(0, this.length - this.value.length)).fill('')).slice(0, this.length),
      focusedIndex: -1
    };
  },
  watch: {
    value(v) {
      const arr = v.split('').slice(0, this.length);
      while (arr.length < this.length) arr.push('');
      this.cells = arr;
    },
    length() {
      const arr = this.cells.slice(0, this.length);
      while (arr.length < this.length) arr.push('');
      this.cells = arr;
    }
  },
  methods: {
    emit() {
      const code = this.cells.join('');
      this.$emit('input', code);
      this.$emit('change', code);
    },
    onInput(e, i) {
      const ch = (e.target.value || '').slice(-1);
      this.$set(this.cells, i, ch);
      e.target.value = ch;
      if (ch && i < this.length - 1) this.focus(i + 1);
      this.emit();
    },
    onKeydown(e, i) {
      if (e.key === 'Backspace') {
        e.preventDefault();
        if (this.cells[i]) {
          this.$set(this.cells, i, '');
        } else if (i > 0) {
          this.$set(this.cells, i - 1, '');
          this.focus(i - 1);
        }
        this.emit();
      } else if (e.key === 'ArrowLeft' && i > 0) {
        this.focus(i - 1);
      } else if (e.key === 'ArrowRight' && i < this.length - 1) {
        this.focus(i + 1);
      }
    },
    onPaste(e) {
      e.preventDefault();
      const text = (e.clipboardData || window.clipboardData).getData('text') || '';
      const digits = text.replace(/\D/g, '').slice(0, this.length).split('');
      const arr = this.cells.slice();
      for (let k = 0; k < this.length; k++) arr[k] = digits[k] || '';
      this.cells = arr;
      this.focus(Math.min(digits.length, this.length - 1));
      this.emit();
    },
    focus(i) {
      this.$nextTick(() => {
        const el = this.$refs.inputs && this.$refs.inputs[i];
        if (el) el.focus();
      });
    }
  }
};
</script>

<style src="./CodeInput.css"></style>
