<template>
	<t-form class="tui-comment-form">
		<t-form-item label="昵称" name="nick">
			<t-input
				class="nick"
				v-model="formData.data.nick"
				:disabled="userStore.isLogged()"
				placeholder="昵称"
			/>
		</t-form-item>
		<t-form-item label="评论" name="content">
			<markdown-editor v-model:data="formData.data.content" />
		</t-form-item>
		<t-form-item label="验证码" name="captcha">
			<t-input class="captcha" v-model="formData.captcha" placeholder="" />
			<captcha
				ref="captchaRef"
				class="captcha-img"
				:api="CommonAPI.getCaptchaAPI()"
				:width="90"
				:height="28"
				:from="CaptchaFrom.COMMENT"
			/>
			<t-button
				type="submit"
				:loading="doSubmitting"
				:disabled="doSubmitting"
				@click="doSubmit"
			>提交</t-button>
		</t-form-item>
	</t-form>
</template>

<script lang="ts" setup>
import {
	Captcha,
	CaptchaData,
	CaptchaFrom,
	Comment,
	CommentAPI,
	CommentBizType,
	CommonAPI,
	MarkdownEditor,
	userStore
} from "timi-web";
import { Emits, useHandler } from "~/components/comment/form/emits";

defineOptions({
	name: "CommentForm"
});

const emits = defineEmits<Emits>();
const { onSubmit } = useHandler(emits);

const props = withDefaults(defineProps<{
	bizType: CommentBizType,
	bizId: number,
}>(), {});
const { bizType, bizId } = toRefs(props);

const captchaRef = ref<{ update: () => void}>();
const formData = reactive<CaptchaData<Comment>>({
	from: CaptchaFrom.COMMENT,
	captcha: "",
	data: {
		bizType: bizType.value,
		bizId: bizId.value,
		nick: "",
		content: ""
	}
});
const doSubmitting = ref(false);

async function doSubmit() {
	doSubmitting.value = true;

	const loginUser = userStore.loginUser;
	if (userStore.isLogged() && loginUser.user) {
		formData.data.nick = loginUser.user.name;
		formData.data.userId = loginUser.user.id;
	}
	await CommentAPI.create(formData);
	formData.captcha = "";
	formData.data.content = "";
	captchaRef.value?.update();

	doSubmitting.value = false;

	await onSubmit(formData.data);
}

// 登录用户
const updateNick = () => formData.data.nick = userStore.loginUser?.user?.name || "";
watch(userStore.loginUser, updateNick);
onMounted(updateNick);
</script>

<style lang="less" scoped>
.tui-comment-form {
	padding: 1rem;

	.nick {
		width: 12rem;
	}

	.captcha {
		width: 6rem;
	}

	.captcha-img {
		margin: 0 1rem;
	}
}
</style>
