<template>
  <form
    autocorrect="off"
    autocapitalize="off"
    autocomplete="off"
    spellcheck="false"
  >
    <div class="row justify-between q-my-md">
      <div
        v-for="(x, i) in cols"
        :key="i"
        class="override-verfity-ipt col"
        :class="{ 'q-ml-sm': i > 0 }"
      >
        <q-input
          standout
          v-model="cols[i]"
          @focus="codeFocus($event)"
          ref="codes"
          @keyup="changFocus($event, i)"
          maxlength="1"
          mask="#"
          dense
        />
      </div>
      
    </div>
    <div class="q-mt-sm text-negative f12" v-if="hasError">{{ errorMsg }}</div>
  </form>
</template>

<script>
export default {
  props: {
    /**
     * @description 请传入能够被12整除的整数
     */
    digit: Number,

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

    /**
     * @description 绑定值
     */
    value: [String, Number],
  },
  data() {
    return {
      cols: [],
      hasError: false,
      errorMsg: "",
      colStyle: "",
    };
  },
  created() {
    this.initColHandler();
  },
  methods: {
    initColHandler() {
      for (let i = 0; i < this.digit; i++) {
        this.cols.push("");
      }
      this.colStyle = `col-${12 / this.digit}`;
    },
    changFocus(event, index) {
      if (event.key == "Backspace") {
        if (index != 0) {
          this.$refs.codes[index - 1].focus();
        }
      } else if (index < this.digit-1) {
        if (this.cols[index] != "") {
          this.$refs.codes[index + 1].focus();
        }
      }
      this.updateValue();
    },
    updateValue() {
      let tempValue = "";
      this.cols.forEach((x) => {
        tempValue += x;
      });
      this.$emit("input", tempValue);
    },
    codeFocus(e) {
      e.target.select();
    },
    validate() {
      if (this.value.length != this.cols.length) {
        this.errorMsg = "请输入正确的验证码";
        this.hasError = true;
      } else {
        this.errorMsg = "";
        this.hasError = false;
      }
      return !this.hasError
    },
  },
};
</script>

<style>
.override-verfity-ipt .q-field--dense .q-field__control,
.override-verfity-ipt .q-field--dense .q-field__marginal {
  height: 60px !important;
  text-align: center;
  font-family: din;
  font-size: 32px;
}
.override-verfity-ipt .q-field--dense .q-field__control input,
.override-verfity-ipt .q-field--dense .q-field__marginal input {
  text-align: center;
}
</style>
