<script setup>
import { ref,onMounted } from 'vue'

const emit = defineEmits([
  'finish'
])

const activeInput = ref(0)

//   页面加载后聚焦第一个
onMounted(()=> {
  let dom = document.getElementById("captcha" + activeInput.value);
  dom.focus();
})

// 自动校准输入顺序
function adjust(index) {
  let dom = document.getElementById("captcha" + activeInput.value);
  if (index !== activeInput.value && dom) {
    dom.focus();
  }
}

const captchas = ref([
    { num: "" },
    { num: "" },
    { num: "" },
    { num: "" },
    { num: "" },
    { num: "" },
])
// 控制前后方向
function inputDirection(index,e) {
  let val = captchas.value[index].num;
  // 回退键处理
  if (e.key==='Backspace' && val === "") {
    // 重新校准
    let dom = document.getElementById("captcha" + (index - 1));
    activeInput.value = index - 1;
    if (dom) dom.focus();
  }
  if (e.key!=='Backspace' && val !== "") {
    let dom = document.getElementById("captcha" + (index + 1));
    activeInput.value = index + 1;
    if (dom) dom.focus();
  }
}
// 输入框相互联动
function inputFinash(index) {
  let val = captchas.value[index].num;
  activeInput.value = val ? index + 1 : index - 1;
  let dom = document.getElementById("captcha" + activeInput.value);
  if (dom) dom.focus();
  if (index == captchas.value.length - 1) {
    let code = captchas.value.map((x) => x.num).join("");
    if (code.length == 6) {
      emit("finish", code);
    }
  }
}

defineExpose({
  captchas
})
</script>
<template>
    <!-- 格子验证码输入组件 -->
    <div class="row-center captcha_input_wrap">
        <input
            v-for="(item, index) in captchas"
            :key="index"
            v-model="item.num"
            :id="'captcha' + index"
            @input="inputFinash(index)"
            @focus="adjust(index)"
            @keydown="(e)=>{inputDirection(index,e)}"
            class="captcha_input_box row-center"
            :class="[index <= activeInput ? 'active' : '']"
            type="tel"
            maxlength="1"
        />
  </div>
</template>
  
<style scoped lang='scss'>
.row-center {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    gap:40px;
}
.captcha_input_wrap {
    width: 100%;
}
.captcha_input_box {
    width: 40px;
    height: 40px;
    background: rgba(255, 255, 255, 1);
    border-radius: 6px;
    border: 1px solid #dddddd;
    font-size: 16px;
    text-align: center;
    color: #1e243a;
    outline: none;
}
.active {
    border: 1px solid #3654C1 !important;
}

@media screen and (max-width:650px) {
  .row-center {
    gap:10px;
  }
  .captcha_input_box{
    box-sizing: border-box;
  }
}
</style>