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

<script setup>
import { ref, computed, watch, onMounted, onBeforeUnmount } 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)
const isMobile = ref(false)

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
	}
}

function updateIsMobile() {
	isMobile.value = window.matchMedia('(max-width: 768px)').matches
}

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

onMounted(() => {
	updateIsMobile()
	window.addEventListener('resize', updateIsMobile)
})
onBeforeUnmount(() => {
	window.removeEventListener('resize', updateIsMobile)
})
</script>

<style scoped>
.footer-actions :deep(.el-button + .el-button) {
	margin-left: 0;
}
</style>
