<template>
	<el-dialog v-model="visible" title="新增学生" width="560px" :fullscreen="isMobile" :close-on-click-modal="false" class="responsive-dialog">
		<div class="space-y-4" v-loading="loading">
			<el-form :label-width="isMobile ? 0 : 90" :label-position="isMobile ? 'top' : 'right'">
				<el-form-item label="姓名">
					<el-input v-model="name" placeholder="请输入学生姓名" clearable class="w-full" />
				</el-form-item>
				<el-form-item label="年级">
					<el-select v-model="gradeId" placeholder="请选择年级" class="w-full sm:w-[260px]" @change="handleGradeChange">
						<el-option v-for="g in gradeOptions" :key="g.id" :label="g.title" :value="g.id" />
					</el-select>
				</el-form-item>
				<el-form-item label="班级">
					<el-select v-model="classId" placeholder="请选择班级" class="w-full sm:w-[260px]">
						<el-option v-for="c in filteredClassOptions" :key="c.id" :label="c.title" :value="c.id" />
					</el-select>
					<div v-if="gradeId && filteredClassOptions.length === 0" class="mt-2 flex items-center gap-2">
						<span class="text-xs text-gray-500">当前年级暂无班级</span>
						<el-button type="primary" size="small" @click="showAddClassDialog = true">新增班级</el-button>
					</div>
				</el-form-item>
				<el-form-item label="入学时间">
					<el-date-picker v-model="startDate" type="datetime" placeholder="选择日期时间" class="w-full"
						format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
				</el-form-item>
			</el-form>
		</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>
	<AddClassDialog v-model="showAddClassDialog" :default-grade-id="gradeId" @success="onAddClassSuccess" />
</template>

<script setup>
import { ref, computed, watch, onMounted, onBeforeUnmount } from 'vue'
import { getGradeList } from '@/api/grade'
import { getClassList } from '@/api/class'
import { addStudent } from '@/api/student'
import AddClassDialog from '@/layouts/components/AddClassDialog.vue'

const props = defineProps({
	modelValue: { type: Boolean, default: false },
	defaultClassId: { type: [Number, String], default: null },
	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 classId = ref(null)
const startDate = ref('')
const gradeOptions = ref([])
const classOptions = ref([])
const isMobile = ref(false)

const filteredClassOptions = computed(() => {
	if (!gradeId.value) return []
	return classOptions.value.filter(c => String(c.gradeId) === String(gradeId.value))
})
const showAddClassDialog = ref(false)
function onAddClassSuccess() {
	fetchBaseOptions().then(() => {
		handleGradeChange()
	})
}

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

async function fetchBaseOptions() {
	loading.value = true
	try {
		const [gr, cl] = await Promise.all([
			getGradeList(1, 100),
			getClassList(1, 100)
		])
		const gd = gr?.data
		const cd = cl?.data
		gradeOptions.value = Array.isArray(gd?.data) ? gd.data : []
		classOptions.value = Array.isArray(cd?.data) ? cd.data : []
	} finally {
		loading.value = false
	}
}

function handleGradeChange() {
	if (classId.value) {
		const match = filteredClassOptions.value.some(c => String(c.id) === String(classId.value))
		if (!match) classId.value = null
	}
}

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

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

watch(
	() => props.modelValue,
	async (v) => {
		if (v) {
			name.value = ''
			gradeId.value = props.defaultGradeId ? Number(props.defaultGradeId) : null
			classId.value = props.defaultClassId ? Number(props.defaultClassId) : null
			startDate.value = ''
			await fetchBaseOptions()
			if (gradeId.value) handleGradeChange()
			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;
}
.responsive-dialog :deep(.el-dialog__body) {
	max-height: 70vh;
	overflow-y: auto;
}
</style>
