<template>
	<slot :disabled="isDisabled" :countdown="countdown" :btnText="btnText">
		<cl-button text :disabled="isDisabled" @tap="open">
			{{ btnText }}
		</cl-button>
	</slot>

</template>

<script lang="ts" setup>
import { computed, reactive, ref } from "vue";
import { useUi } from "@/uni_modules/cool-ui";
import { request, type Response, isDark, t, $t, parse } from "@/.cool";
import { sendSmsCode } from "@/services/user";
const props = defineProps({
	phone: String
});

const ui = useUi();

type Captcha = {
	visible: boolean;
	loading: boolean;
	sending: boolean;
	img: string;
};

// 验证码
const captcha = reactive<Captcha>({
	visible: false,
	loading: false,
	sending: false,
	img: ""
});

// 倒计时
const countdown = ref(0);

// 是否禁用
const isDisabled = computed(() => countdown.value > 0 || props.phone == "");

// 按钮文案
const btnText = computed(() =>
	countdown.value > 0 ? $t("{n}s后重新获取", { n: countdown.value }) : t("获取验证码")
);


// 开始倒计时
function startCountdown() {
	countdown.value = 60;

	let timer: number = 0;

	function fn() {
		countdown.value--;

		if (countdown.value < 1) {
			clearInterval(timer);
		}
	}

	// @ts-ignore
	timer = setInterval(() => {
		fn();
	}, 1000);
	fn();
}


// 发送短信
async function send() {
	captcha.sending = true;
	const res = await sendSmsCode({
		mobile: props.phone,
		randomStr: 12,
		messageType: 1
	})
	ui.showToast({
		message: t("短信已发送，请查收")
	});
	startCountdown();
	captcha.sending = false;

}

// 打开
function open() {
	if (props.phone != "") {
		if (/^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(props.phone!)) {
			captcha.visible = true;
			send();
		} else {
			ui.showToast({
				message: t("请填写正确的手机号格式")
			});
		}
	}
}

defineExpose({
	open,
	send,
	startCountdown
});
</script>
