<!--
 * @Author: Jackie
 * @Date: 2023-08-24 14:18:05
 * @LastEditTime: 2023-09-11 14:58:21
 * @LastEditors: Jackie
 * @Description: code输入框-over
 * @FilePath: /web/src/views/Register/components/CodeInput.vue
 * @version:
-->
<template>
  <div class="verification-container">
    <a-input
      v-for="(code, index) in verificationCodes"
      :key="index"
      type="number"
      :style="{ textAlign: 'center' }"
      v-model="verificationCodes[index]"
      @input="handleInput(index, $event)"
      @keydown="handleKeyDown(index, $event)"
      :maxlength="1"
      class="verification-input"
    />
  </div>
</template>
<script setup>
import { ref, defineProps, defineEmits, nextTick, defineModel } from 'vue'
const model = defineModel()
// defineProps({
//   modelValue: {
//     type: [String,Number],
//     default: '',
//   },
// });
// const emits = defineEmits(['update:modelValue']);
const verificationCodes = ref(['', '', '', '', '', ''])

const handleInput = (index, event) => {
  const value = event.target.value
  verificationCodes.value[index] = value

  model.value = verificationCodes.value.join('')
  // 判断是否输入完成
  if (verificationCodes.value.join('').length === 6) {
    // // emits('modelValue', verificationCodes.value.join(''));
    // model.value = verificationCodes.value.join('')
  }
  // model.value = verificationCodes.value.join('')

  // 自动跳到下一个输入框
  if (value && index < verificationCodes.value.length - 1) {
    const nextInput = event.target.nextElementSibling
    if (nextInput) {
      nextTick(() => {
        nextInput.focus()
      })
    }
  }
}
const handleKeyDown = (index, event) => {
  model.value = '' // 清空绑定值

  // 处理删除操作
  if (event.key === 'Backspace' && !event.target.value && index > 0) {
    const prevInput = event.target.previousElementSibling
    if (prevInput) {
      nextTick(() => {
        prevInput.focus()
      })
    }
  }
}
</script>
<style lang="less" scoped>
.verification-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.verification-input {
  width: 54px;
  height: 54px;
  margin-right: 16px;
  text-align: center;
  font-size: 20px;
  border: 1px solid #ebebeb;
  // border-radius: 5px;
  background-color: #eeeeee;
  &:last-child {
    margin-right: 0;
  }
}
::v-deep(input::-webkit-outer-spin-button),
::v-deep(input::-webkit-inner-spin-button) {
  -webkit-appearance: none !important;
  margin: 0;
}
::v-deep(input[type='number']) {
  -moz-appearance: textfield;
}

.verification-input:focus {
  outline: none;
  // border-color: #007bff;
  // box-shadow: 0 0 5px #007bff;
}
</style>
