<script setup>
import {defineModel, defineProps, ref} from 'vue';
import {Message, Notification} from "@arco-design/web-vue";
import Api from "../../api/index.js";

const verificationCode = defineModel('verificationCode', {type: String});
const {mobile, api, type} = defineProps({
    mobile: {
        type: String,
        default: null,
    },
    type: {
        type: Number,
        default: null,
    },
    api: {
        type: Function,
        default: Api.admin.sendSms
    }
});

const time = ref(null);
let timer = null;

const verifyPhone = async () => {
    if (/^1[3-9]\d{9}$/.test(mobile)) {
        if (timer === null) {
            const {msg, code} = await api(mobile, type);
            if (code === 1) Message.success(msg);
            time.value = 10;
            timer = setInterval(() => {
                if (time.value <= 0) {
                    time.value = null;
                    clearInterval(timer);
                    timer = null;
                } else {
                    time.value--;
                }
            }, 1000);
        }
        return true;
    } else {
        Notification.error({
            title: '手机号错误',
            content: '请检查后重新输入'
        });
        return false;
    }
}
</script>

<template>
    <a-input v-model:model-value="verificationCode" placeholder="验证码">
        <template #append>
            <a-link @click="verifyPhone" :disabled="Boolean(time)" :hoverable="false">
                {{ time ? `${time}s后重新获取` : '发送验证码' }}
            </a-link>
        </template>
    </a-input>
</template>

<style scoped>

</style>
