<template>
	<el-dialog v-model="visible" title="新增年级" width="420px" :close-on-click-modal="false">
		<div class="space-y-4" v-loading="loading">
			<el-input v-model="name" placeholder="请输入年级名称，如：一年级" clearable />
		</div>
		<template #footer>
			<div class="flex justify-end gap-2">
				<el-button @click="visible = false">取消</el-button>
				<el-button type="primary" :disabled="!canSubmit" @click="handleSubmit">确定</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { addGrade } from '@/api/grade'

const props = defineProps({
	modelValue: { type: Boolean, default: false }
})
const emit = defineEmits(['update:modelValue', 'success'])

const visible = computed({
	get: () => props.modelValue,
	set: (val) => emit('update:modelValue', val)
})

const loading = ref(false)
const name = ref('')
const canSubmit = computed(() => name.value.trim().length > 0)

async function handleSubmit() {
	if (!canSubmit.value) return
	loading.value = true
	try {
		await addGrade(name.value.trim())
		ElMessage.success('新增年级成功')
		emit('success')
		visible.value = false
	} finally {
		loading.value = false
	}
}

watch(
	() => props.modelValue,
	(v) => {
		if (v) name.value = ''
	}
)
</script>

<style scoped></style>
