<template>
	<el-dialog v-model="visible" title="生成试题" width="520px" :close-on-click-modal="false">
		<div class="space-y-4" v-loading="loading">
			<el-form label-width="80px">
				<el-form-item label="类型">
					<el-select v-model="type" placeholder="请选择类型" style="width: 240px">
						<el-option :label="'摸底'" :value="1" />
						<el-option :label="'期中'" :value="2" />
						<el-option :label="'期末'" :value="3" />
					</el-select>
				</el-form-item>
			</el-form>
			<div class="text-sm text-gray-500">
				已选学生数量：{{ studentIds.length }}
			</div>
		</div>
		<template #footer>
			<div class="flex justify-end gap-2">
				<el-button @click="visible = false">取消</el-button>
				<el-button type="primary" :disabled="!type" @click="handleGenerate">生成并下载</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { getGradeList } from '@/api/grade'
import { generateExamWords } from '@/api/exam'

const props = defineProps({
	modelValue: { type: Boolean, default: false },
	studentIds: { type: Array, default: () => [] },
	defaultGradeId: { type: [Number, String], default: null }
})
const emit = defineEmits(['update:modelValue'])

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

const loading = ref(false)
const gradeOptions = ref([])
const gradeId = ref(null)
const level = ref(null)
const type = ref(null)
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 handleGenerate() {
	if (!type.value) return
	await generateExamWords({
		type: Number(type.value),
		studentId: props.studentIds[0]
	})
	ElMessage.success('生成任务已提交，正在下载')
	visible.value = false
}

watch(
	() => props.modelValue,
	(v) => {
		if (v) {
			level.value = null
			gradeId.value = props.defaultGradeId ? Number(props.defaultGradeId) : null
			fetchGrades()
		}
	}
)

onMounted(() => {
	if (visible.value) fetchGrades()
})
</script>

<style scoped></style>
