<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 ) { 
      this.$toast('请输入正确的手机号')
      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{
    border-bottom: 1px solid #E4E4E4;
    font-size: 14px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #1F292D;
    .code-btn {
      border-left: 1px solid #E4E4E4;
      padding-left: 11px;
      color: $fontColorBlue;
      &.disabled {
        color: #8E8C92;
      }
    }
  }
  ::v-deep .van-field__control::placeholder {
  font-weight: 500;
  color: #C2C2C2 !important;
}
</style>