<template>
	<el-dialog v-model="visible" title="新增单元" width="480px" :close-on-click-modal="false">
		<div class="space-y-4" v-loading="loading">
			<el-form label-width="80px">
				<el-form-item label="单元名称">
					<el-input v-model="name" placeholder="请输入单元名称，如：Unit 1" clearable />
				</el-form-item>
				<el-form-item label="年级">
					<el-select v-model="gradeId" placeholder="请选择年级" style="width: 260px">
						<el-option v-for="g in gradeOptions" :key="g.id" :label="g.title" :value="g.id" />
					</el-select>
				</el-form-item>
			</el-form>
		</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 { getGradeList } from '@/api/grade'
import { addUnit } from '@/api/unit'

const props = defineProps({
	modelValue: { type: Boolean, default: false },
	defaultGradeId: { type: [Number, String], default: null }
})
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 gradeId = ref(null)
const gradeOptions = ref([])

const canSubmit = computed(() => name.value.trim().length > 0 && !!gradeId.value)

async function fetchGrades() {
	loading.value = true
	try {
		const res = await getGradeList(1, 100)
		const d = res?.data
		gradeOptions.value = Array.isArray(d?.data) ? d.data : []
		if (props.defaultGradeId && !gradeId.value) {
			gradeId.value = Number(props.defaultGradeId)
		}
	} finally {
		loading.value = false
	}
}

async function handleSubmit() {
	if (!canSubmit.value) return
	loading.value = true
	try {
		await addUnit(name.value.trim(), Number(gradeId.value))
		ElMessage.success('新增单元成功')
		emit('success')
		visible.value = false
	} finally {
		loading.value = false
	}
}

watch(
	() => props.modelValue,
	(v) => {
		if (v) {
			name.value = ''
			gradeId.value = props.defaultGradeId ? Number(props.defaultGradeId) : null
			fetchGrades()
		}
	}
)
</script>

<style scoped></style>
