<script setup>
import {ref} from "vue";
import XLink from "./XLink.vue";
import XInput from "./XInput.vue";
import Api from "../api/index.js";
import {showToast} from "../utils/uils.js";

const modalValue = defineModel();
const timer = ref(null);
const props = defineProps({
    mobile: {
        type: String,
        default: null
    },
    type: {
        type: Number,
        default: 1
    },
});

const sendMsg = async () => {
    if (!/^1[3-9]\d{9}$/.test(props.mobile)) {
        showToast('手机号不正确');
        return;
    }
    const {msg} = await Api.system.sendSms({
        mobile: props.mobile,
        type: props.type,
    });
    showToast(msg);
    timer.value = 60;
    const send = () => {
        if (timer.value === 0) {
            timer.value = null;
            return;
        }
        timer.value--;
        setTimeout(send, 1000);
    }
    setTimeout(send, 1000);
}
</script>

<template>
    <x-input v-bind="$attrs" v-model:model-value="modalValue" placeholder="验证码">
        <template #suffix>
            <x-link @click="sendMsg">{{
                    timer ? `${timer}秒后重试` : `发送验证码`
                }}
            </x-link>
        </template>
    </x-input>
</template>

<style scoped>

</style>
