<template>
  <div class="code-input">
    <van-field
      :value="code"
      placeholder="验证码"
      label-align="right"
      @input="input"
    >
      <template #button>
        <div 
          @click="sendCode"
          :class="[isCodeBtnDisabled? 'disabled': '']"
          class="code-btn">{{codeBtnStr}}</div>
      </template>
    </van-field>
  </div>
</template>
<script lang="ts">
import { Component, Prop, PropSync, Vue, Watch, Inject, Emit, Model } from 'vue-property-decorator';
import { Action } from 'vuex-class';
import { isCode, isEmail } from '@/const/pattern';
import { LoginType } from '@/const/enum';

/**
 * 验证码输入框
 */
@Component({
  name: 'codeInput',
})
export default class CodeInput extends Vue {
  @Model ('input', { type: String, required: true })
  private readonly code!: string;

  @Prop({ type: Boolean, required: true})
  private readonly canGetCode!: boolean;

  @PropSync('countDown', { type: Number, required: true })
  private countDownSync!: number; // 验证码倒计时

  @Emit('input')
  private input(e: string) {
    return e;
  }

  private get codeBtnStr(): string { // 获取验证码按钮文案
    const { countDownSync } = this;
    return countDownSync > 0 ? `${countDownSync}s` : '获取验证码';
  }

  private get isCodeBtnDisabled(): boolean {
    if ( !this.canGetCode || this.countDownSync > 0) { return true; }
    return false;
  }

  private sendCode() {
    if ( this.isCodeBtnDisabled ) { return; }
    this.countDownSync = 60;
    this.$emit('get-code');
    const countTimer = setInterval(() => {
      if (this.countDownSync <= 0) {
        clearInterval(countTimer);
      }
      this.countDownSync--;
    }, 1000);
    this.$once('hook:beforeDestroy', () => { clearInterval( countTimer ); });
  }
}
</script>
<style scoped lang="scss">
  .code-input{
    .code-btn {
      font-size: 16px;
      color: $fontColorBlue;
      &.disabled {
        color: $fontColorGray;
      }
    }
  }
</style>