<template>
    <el-button
        type="text"
        :loading="buttonLoading"
        :disabled="buttonDisabled"
        @click="handleSendSMSCode"
        >{{ buttonText }}
    </el-button>
</template>

<script>
import SMSService from "@/api/sms";

const COUNT_DOWN_MAX = 60;
const BUTTON_TEXT_DEF = "发送短信验证码";

export default {
    name: "SendSMSCodeButton",
    props: {
        // 发送验证码的目标电话号码
        mobile: {
            type: String,
            default: "",
        },
    },
    data() {
        return {
            timer: null, // 定时器
            countdownNumber: COUNT_DOWN_MAX, // 倒计时（秒）
            buttonDisabled: false, // 按钮是否禁用
            buttonLoading: false, // 按钮加载中
            buttonText: BUTTON_TEXT_DEF, // 按钮文本
        };
    },
    methods: {
        handleSendSMSCode: function () {
            const reg = /^1\d{10}$/;
            if (!reg.test(this.mobile)) {
                this.$message.error("请输入正确的手机号码!");
                console.log(this.mobile);
            } else {
                this.callAPISendSMSCode(this.mobile);
            }
        },
        callAPISendSMSCode: function (mobile) {
            const _this = this;
            _this.buttonLoading = true;
            SMSService.getSmscode(mobile)
                .then((val) => {
                    _this.createCountdownTimer();
                })
                .catch((err) => {
                    _this.$message.error(err);
                })
                .finally(() => {
                    _this.buttonLoading = false;
                });
        },
        /**
         * 创建倒计时定时器
         */
        createCountdownTimer: function () {
            const _this = this;

            // 设置按钮
            const setButton = function (countdownNumber) {
                if (_this.countdownNumber > 0) {
                    _this.buttonDisabled = true;
                    _this.buttonText = _this.countdownNumber + "秒后重新获取";
                } else {
                    _this.buttonDisabled = false;
                    _this.countdownNumber = COUNT_DOWN_MAX;
                    _this.buttonText = BUTTON_TEXT_DEF;
                    clearInterval(_this.timer);
                }
            };

            setButton(_this.countdownNumber);

            _this.timer = setInterval(() => {
                _this.countdownNumber--;
                setButton(_this.countdownNumber);
            }, 1000);
        },
    },
};
</script>