<template>
	<div class="bg-white text-xl text-text px-5 py-7 rounded">
		<h1 class="font-medium">新增用户</h1>
		<section>
			<div class="grid grid-cols-[5rem_1fr] gap-x-8 gap-y-4 min-w-[30rem] mt-4 mb-7 px-4">
				<span class="text-right">用户名</span>
				<input type="text" class="border border-[#eee] rounded-sm px-2" v-model="user.username" />
				<span class="text-right">昵称</span>
				<input type="text" class="border border-[#eee] rounded-sm px-2" v-model.trim="user.nickname" />
				<span class="text-right">密码</span>
				<input type="text" class="border border-[#eee] rounded-sm px-2" v-model.trim="user.password" />
			</div>
		</section>
		<footer class="flex justify-center gap-x-6">
			<button class="btn-dark px-6 py-1" @click="onConfirm">确定</button>
			<button class="btn-light px-6 py-1" @click="$emit('cancel')">取消</button>
		</footer>
	</div>
</template>

<script setup lang="ts">
import { showToast } from "vant";
import { reactive, ref, watch } from "vue";

interface UserDto {
	username: string;
	nickname: string;
	password: string;
}

const emit = defineEmits<{
	(e: "confirm", user: UserDto): void;
	(e: "cancel"): void;
}>();

const user = reactive<UserDto>({ username: "", nickname: "", password: "" });

watch(
	() => user.username,
	newVal => {
		const reg = /^\S+$/;
		if (!reg.test(newVal)) {
			user.username = user.username.trim();
		}
	}
);
function onConfirm() {
    if (user.username === "") {
        showToast("用户名不能为空")
        return
    }
    if (user.nickname === "") {
        showToast("昵称不能为空")
        return
    }
    if (user.password === "") {
        showToast("密码不能为空")
        return
    }
	emit("confirm", user);
}
</script>
