<template>
  <div class="w-full flex justify-between" :phone="phone">
    <a-input
      placeholder="请输入验证码"
      style="margin-right: 10px"
      @blur="getCode"
      class="w-200"
      v-model="code"
    />
    <a-button type="primary" v-if="smsCount === 60" @click="handleClickSendSms">
      获取验证码
    </a-button>
    <a-button v-else type="primary" disabled>
      已发送 {{ smsCount }} S
    </a-button>
  </div>
</template>

<script lang="ts">
import Vue from "vue";
import { smsSend } from "@/service/Verification/index";
import { isPhoneValid } from '@/utils/phone/index';
import { Modal } from "ant-design-vue";

export default Vue.extend({
  props: {
    phone: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      code: "",
      smsLock: false,
      smsCount: 60,
      timerId: 0,
    };
  },
  methods: {
    getCode() {
      this.$emit("getCode", this.code);
    },
    isValid(): boolean {
      let result;
      if ( !isPhoneValid(this.phone)) {
        Modal.warning({
          title: "",
          content: "请输入正确的手机号",
        });
        result = false;
      } else {
        result = true;
      }
      return result;
    },
    async sendSmsFunc(phone: string) {
      const ret = await smsSend({
        phone: phone,
        smsType: 0,
      });
    },
    async handleClickSendSms() {
      if (this.isValid()) {
        if (this.smsLock === true) return;
        this.smsLock = true;
        try {
          await this.sendSmsFunc(this.phone);
        } catch (err) {
          this.smsLock = false;
          return;
        }
        this.smsCount--;
        this.timerId = window.setInterval(() => {
          this.smsCount--;
          if (this.smsCount === -1) {
            this.smsCount = 60;
            this.smsLock = false;
            window.clearInterval(this.timerId);
          }
        }, 1000);
      }
    },
  },
  beforeDestroy() {
    clearInterval(this.timerId);
  },
});
</script>

<style scoped>
.w-200 {
  width: 200px;
}
</style>