<template>
  <div class="code-btn">
    <el-button
      type="primary"
      @click="getCode()"
      class="send-btn"
      :disabled="!show"
      >{{ show ? "获取验证码" : "重新发送" + count }}</el-button
    >
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Watch } from "vue-property-decorator";
import { sendSms, sendEmail } from "./Api.service";
@Component
export default class VerCode extends Vue {
  @Prop({ type: Boolean, default: false }) Modifyphone!: boolean;

  public show: boolean = true;
  public count: number = 0;
  public timer: number = 0;

  public start() {
    this.show = true;
    clearInterval((this as any).timer);
    (this as any).timer = 0;
  }
  // 倒计时开始
  public CountDowns() {
    const TIME_COUNT = 60;
    if (!(this as any).timer) {
      this.count = TIME_COUNT;
      this.show = false;
      (this as any).timer = setInterval(() => {
        if (this.count > 0 && this.count <= TIME_COUNT) {
          this.count--;
        } else {
          this.show = true;
          clearInterval((this as any).timer);
          (this as any).timer = 0;
        }
      }, 1000);
    }
  }
  // 发送验证码
  public async getCode() {
    if (this.$store.state.userInfos.phone !== "") {
      const res = await sendSms({
        phone: this.$store.state.userInfos.phone,
        template_id: this.Modifyphone ? 3 : 1,
      });
      if (res) {
        this.CountDowns();
        this.$emit("sendCode");
      }
    } else {
      const res = await sendEmail({
        email: this.$store.state.userInfos.email,
        template_id: this.Modifyphone ? 3 : 1,
      });
      if (res) {
        this.CountDowns();
        this.$emit("sendCode");
      }
    }
  }
}
</script>

<style scoped>
.code-btn {
  display: inline-block;
  margin-left: 15px;
}
.send-btn {
  width: 112px;
}
</style>
