<template>
  <div class="app-login-note-verify">
    <div class="content">
      <i-input
        size="default"
        type="text"
        v-model="phoneNumber"
        :placeholder="$t('components.login.phoneplaceholder')"
        @on-blur="veriPhoneNumber"
      ></i-input>
      <el-button
        :disabled="disabled"
        size="mini"
        type="primary"
        @click="getVeriCode()"
        >{{ disabled ? `${countDown}s ${$t('components.login.getcodeafter')}` : `${$t('components.login.getcode')}` }}</el-button
      >
    </div>
    <div class="code">
      <i-input
        size="default"
        type="text"
        :value="currentValue"
        @input="codeChange"
        :placeholder="$t('components.login.codeplaceholder')"
      ></i-input>
    </div>
  </div>
</template>

<script lang='ts'>
import { Vue, Component, Prop } from "vue-property-decorator";

@Component({})
export default class AppPresetSmsVerification extends Vue {

  /**
   *验证码值
   *
   * @type {string}
   * @memberof AppPresetSmsVerification
   */
  @Prop() public value!: string;

  /**
   *验证码当前值
   *
   * @type {string}
   * @memberof AppPresetSmsVerification
   */
  get currentValue(): string {
    return this.value;
  }


  /**
   * 手机号
   *
   * @type {*}
   * @memberof AppPresetSmsVerification
   */
  public phoneNumber: string = '';

  /**
   * 倒计时
   *
   * @type {*}
   * @memberof AppPresetSmsVerification
   */
  public countDown: number = 60;

  /**
   * 错误提示
   * @type {*}
   * @memberof AppPresetSmsVerification
   */
  public phoneError = false;

  /**
   * 是否禁用获取验证码按钮
   *
   * @type {*}
   * @memberof AppPresetSmsVerification
   */
  public disabled: boolean = false;

  /**
   * 定时器
   *
   * @type {*}
   * @memberof AppPresetSmsVerification
   */
  public timer: any;

  /**
   * @description 设置倒计时
   * @memberof AppPresetSmsVerification
   */
  public setCountDown() {
    if (this.countDown > 0) {
      this.countDown--;
    } else {
      this.countDown = 60;
      this.disabled = false;
      clearInterval(this.timer);
    }
    this.$forceUpdate();
  }

  /**
   * @description 验证码输入变化
   * @memberof AppPresetSmsVerification
   */
  public codeChange(value: string) {
    this.$emit("change", value);
  }

  /**
   * @description 校验手机号
   * @memberof AppPresetSmsVerification
   */
  public veriPhoneNumber(): boolean {
    this.phoneError = !/^1[3-9]\d{9}$/.test(this.phoneNumber); 
    if(this.phoneError) {
      this.$emit("error", this.$t('components.login.phonefailed'));
    } else {
      this.$emit("error", '');
    }
    return this.phoneError;
  }

  /**
   * @description 获取验证码
   * @memberof AppPresetSmsVerification
   */
  public getVeriCode() {
    if(this.phoneError) return;
    // todo 获取验证码
  }
}
</script>

<style lang='less'>
@import "./app-login-note-verify.less";
</style>