<template>
  <div class="verificationCode">
    <input
      type="text"
      ref="input"
      class="input-class"
      @keyup="changeCode"
      @blur="leaveFock"
      v-model="inputValue"
    />
    <p v-if="tip" class="code-input__tip">{{tip}}</p>
    <div class="content" @click="onFock()">
      <div
        :class="['codeCount', {'active': index === showEachArray.length && focus}]"
        v-for="(item, index) in showCode"
        :type="isPassword ? 'password' : 'text'"
        :key="index"
      >
        <span v-show="showEachArray[index]">{{isPassword ? '·' : showEachArray[index]}}</span>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  name: "verificationCode",
  data() {
    return {
      inputValue: "",
      showEachArray: [],
      showCode: "",
      focus: false
    };
  },
  props: ["tip", "codeCount", "isPassword", "type"],
  watch: {
    codeCount: {
      handler: function(val) {
        this.showCode = new Array(+val);
      },
      immediate: true
    }
  },
  methods: {
    onFock() {
      this.focus = true;
      this.$refs.input.focus();
    },
    leaveFock() {
      this.focus = false;
    },
    changeCode() {
      let reg =
        this.type === 1
          ? `[a-zA-Z]`
          : this.type === 2
          ? `[0-9a-zA-Z]`
          : "[0-9]";
      this.inputValue = new RegExp(`${reg}{0,${this.codeCount}}`).exec(
        this.inputValue
      )[0];
      this.showEachArray = [...this.inputValue];
      if (this.showEachArray.length === +this.codeCount) {
        this.$emit("codeInputted", this.showEachArray.join(""));
      }
    },
    clear() {
      this.inputValue = "";
      this.showEachArray = [];
    }
  },
  mounted() {
    // this.onFock()
  }
};
</script>
<style scoped lang="less">
.verificationCode {
  .input-class {
    position: fixed;
    top: -999px;
  }
  .content {
    display: flex;
    justify-content: space-around;
    align-items: center;
    .codeCount {
      display: inline-flex;
      justify-content: center;
      align-items: center;
      width: 44px;
      height: 44px;
      border: 1px solid #909090;
      border-radius: 6px;
      font-size: 30px;
      color: #1e1a1b;
      font-weight: bold;
      > span {
        line-height: 0px;
      }
    }
    .active {
      box-shadow: 0px 0px 2px 2px #1e1a1b;
    }
  }
}
</style>

