<template>
  <form autocorrect="off" autocapitalize="off" autocomplete="off" spellcheck="false">
    <div class="row flex-between">
      <div v-for="(x, i) in formatStyle.col" :key="i" class="override-verfity-ipt" style="width: 60px">
        <el-input style="height: 60px" v-model="formatStyle.col[i]" @focus="codeFocus($event)" :ref="setRef" @keyup="changFocus($event, i)" maxlength="1" />
      </div>
      <div class="q-my-md negative f12" v-if="hasError">{{ errorMsg }}</div>
    </div>
  </form>
</template>

<script>
import { reactive, ref } from 'vue'
export default {
  props: {
    /**
     * @description 请传入能够被12整除的整数
     */
    digit: Number,

    /**
     * @description 提示语
     */
    hint: String,

    /**
     * @description 绑定值
     */
    modelValue: [String, Number]
  },
  setup(props, context) {
    const cols = reactive([])
    const hasError = ref(false)
    const errorMsg = ref('')
    for (let i = 0; i < props.digit; i++) {
      cols.push('')
    }
    const formatStyle = reactive({
      col: reactive(cols),
      colStyle: ref(`col-${12 / props.digit}`)
    })
    const myRef = ref([])
    const setRef = el => {
      myRef.value.push(el)
    }
    const changFocus = (event, index) => {
      if (event.key == 'Backspace') {
        if (index != 0) {
          myRef.value[index - 1].focus()
        }
      } else if (index < props.digit) {
        if (formatStyle.col[index] != '') {
          myRef.value[index + 1].focus()
        }
      }
      updateValue()
    }
    const updateValue = () => {
      let tempValue = ref('')
      formatStyle.col.forEach(x => {
        tempValue.value += x.toString()
      })
      context.emit('update:modelValue', tempValue.value)
    }
    const codeFocus = e => {
      e.target.select()
    }
    const validate = () => {
      if (props.modelValue.length != formatStyle.col.length) {
        errorMsg.value = '请输入正确的验证码'
        hasError.value = true
      } else {
        errorMsg.value = ''
        hasError.value = false
      }
    }
    return { formatStyle, changFocus, setRef, codeFocus, validate, hasError, errorMsg }
  }
}
</script>

<style>
/* .override-verfity-ipt .q-field--dense .q-field__control,
.override-verfity-ipt .q-field--dense .q-field__marginal {
  
} */
.override-verfity-ipt .el-input__inner{
  text-align: center;
  height: 50px !important;
  text-align: center;
  font-family: pingfangr;
  font-weight: bold;
  font-size: 32px;
}
</style>
