<template>
  <div class="sk-codeinput-x sk-flex sk-between">
    <input
      v-for="item in size"
      :key="item"
      :ref="setInputRef"
      maxlength="1"
      class="sk-code-input"
      :class="{
        'is-danger': false,
        'is-border': border
      }"
      :style="{width: `calc(${1 / size * 100}% - 10px)`}"
      @input="handleInput($event, item)"
      @keyup.delete="handleDel(item)"
      @keydown.left.prevent="handleLeft(item)"
      @keydown.right="handleRight(item)"
    >
  </div>
</template>

<script lang="ts">
import { defineComponent, onBeforeUpdate, onMounted, ref } from 'vue'

export default defineComponent({
  name: 'SkCodeInput',
  props: {
    border: {
      type: String,
    },
    modelValue: {
      type: String,
      default: '',
    },
    size: {
      type: Number,
      default: 6,
    },
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    let inputNodes: Array<HTMLInputElement> = []
    let inputValArr = ref<Array<string| number>>([])
    onBeforeUpdate(() => {
      inputNodes = []
    })
    const setInputRef = el => {
      inputNodes.push(el)
    }

    const resolve = (arr: Array<string| number> ): string => {
      const temp =  arr.map(item => {
        if (item) return item
        else return ''
      })
      return temp.join('')
    }
    const handleInput = (event, index) => {
      inputValArr.value[index - 1] = event.data ? event.data : ''
      if (event.inputType === 'insertText') {
        if (index < props.size) {
          inputNodes[index].focus()
        } else {
          // inputNodes.value[0].el.focus()
        }
      }
      emit('update:modelValue', resolve(inputValArr.value))
    }
    const handleDel = index => {
      if (!inputValArr.value[index - 1]) {
        if (index > 1) {
          inputNodes[index - 2].focus()
        } else {
          // inputNodes.value[props.size - 1].el.focus()
        }
      }
      emit('update:modelValue', resolve(inputValArr.value))
    }

    const handleLeft = index => {
      if (index > 1) {
        inputNodes[index - 2].focus()
      }else {
        inputNodes[props.size - 1].focus()
      }
    }

    const handleRight = index => {
      if (index < props.size) {
        inputNodes[index].focus()
      } else {
        inputNodes[0].focus()
      }
    }

    onMounted(() => {
      const tempArr = props.modelValue.split('')
      tempArr.forEach((item, index) => {
        inputValArr.value[index] = item
        inputNodes[index].value = item
      })
    })
    return {
      handleLeft,
      handleRight,
      setInputRef,
      handleInput,
      handleDel,
      inputNodes,

    }
  },
})
</script>
