<template>
  <section>
    <div class="title">输入验证码</div>
    <div style="font-size: 14px; color: #999999;text-align:left;line-height: 2em;margin-bottom: 30px;">6位验证码已发送至{{codeTo}}</div>
    <van-password-input
      :value="code"
      :mask="false"
      :focused="showKeyboard"
      @focus="showKeyboard = true"
    />
    <van-number-keyboard
      :show="showKeyboard"
      @input="onInput"
      @delete="onDelete"
      @blur="showKeyboard = false"
    />
    <div style="color:#737582;font-size: 14px;text-align:left;margin-top:15px;" @click="timerDown">重新发送{{count > 0 ? `(${count}s)` : ''}}</div>
  </section>
</template>
<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import { Button, Image, PasswordInput, NumberKeyboard } from 'vant';
import { State, Getter, Action, Mutation } from 'vuex-class';
import { Route } from 'vue-router';

@Component({
  components: {
    [Button.name]: Button,
    [Image.name]: Image,
    [PasswordInput.name]: PasswordInput,
    [NumberKeyboard.name]: NumberKeyboard,
  },
})
export default class CodeInput extends Vue {
  @Prop({
    required: true,
  })private codeTo!: string;
  @Prop()private code!: string;
  @Prop({
    default: () => {},
  })private sendCode!: () => Promise<any>;
  @Prop({
    default: () => {},
  })private validateCode!: () => Promise<any>;
  @Prop({
    default: () => {},
  })private next!: () => Promise<any>;

  private count: number = 0;
  private showKeyboard: boolean = true;
  private mounted() {
     this.timerDown();
  }
  private timerDown() {
    if (this.count > 0 ) { return; }
    this.count = 60;
    this.sendCode();
    const timer = setInterval(() => {
      if ( this.count <= 0) {
        clearInterval(timer);
        return;
      }
      this.count--;
    }, 1000);
    this.$once('hook:beforeDestory', () => {
      clearInterval(timer);
    });
  }
  private async onInput(key: any) {
    let code = (this.code + key).slice(0, 6);
    this.$emit('update:code', code );
    console.log(code);
    if (code.length < 6) { return; }
    try {
      await this.validateCode();
      this.showKeyboard = false;
      await this.next();
    }catch(err){
      console.error(err);
    }
  }
  private onDelete() {
    const { code, code: { length }} = this;
    this.$emit('update:code', code.slice(0, length - 1));
  }
}
</script>
<style scoped lang="scss">
  .set-passwd {
    padding: 31px 25px;
    .title{
      font-size: 22px;
      color: #353535;
      font-weight: 500;
      text-align: left;
    }
    .margin-top30{
      margin-top: 30px;
    }
  }
</style>