<template>
	<img
		class="tui-captcha ir-pixelated"
		v-if="src"
		:width="width"
		:height="height"
		:src="src"
		alt="验证码"
		@click="update()"
	/>
</template>

<script lang="ts" setup>
import Toolkit from "~/utils/Toolkit";

defineOptions({
	name: "Captcha"
});

const props = withDefaults(defineProps<{
	width: number,
	height: number,
	from: string,
	api: string,
}>(), {});
const { width, height, from, api } = toRefs(props);

const src = ref("");
const captchaId = ref("");

const emit = defineEmits<{
	"update:captchaId": [id: string],
}>();

async function update() {
	if (src.value && src.value.startsWith("blob:")) {
		URL.revokeObjectURL(src.value);
	}
	const response = await fetch(`${api.value}?from=${from.value}&width=${width.value}&height=${height.value}&r=${Toolkit.random(0, 999999)}`);
	if (!response.ok) {
		throw new Error(`fetch captcha error: ${response.status}`);
	}
	captchaId.value = response.headers.get("X-Captcha-ID") || "";
	src.value = URL.createObjectURL(await response.blob());
	emit("update:captchaId", captchaId.value);
}
onMounted(update);

watch([width, height], () => {
	update();
});

onUnmounted(() => {
	if (src.value && src.value.startsWith("blob:")) {
		URL.revokeObjectURL(src.value);
	}
});

defineExpose({
	update,
	getCaptchaId: () => captchaId.value,
	refresh: update
});

</script>

<style lang="less" scoped>
.tui-captcha {
	cursor: var(--tui-cur-pointer);
	display: block;
	pointer-events: all;
}
</style>
