<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="unitId" placeholder="请选择单元" style="width: 300px" filterable>
						<el-option
							v-for="u in unitOptions"
							:key="u.id"
							:label="u.title"
							:value="u.id"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="单词数">
					<el-input v-model="wordSize" type="number" placeholder="请输入单词数" style="width: 300px" />
				</el-form-item>
			</el-form>
			<div class="text-sm text-gray-500">
				学生ID：{{ studentId }}
			</div>
		</div>
		<template #footer>
			<div class="flex justify-end gap-2">
				<el-button @click="visible = false">取消</el-button>
				<el-button type="primary" :disabled="!unitId" @click="handleGenerate">生成</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { getUnitList } from '@/api/unit'
import { generateLessonPlan } from '@/api/plan'
import { showMessage } from '../../composables/util'

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

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

const loading = ref(false)
const unitId = ref(null)
const wordSize = ref(0)
const unitOptions = ref([])

async function fetchUnits() {
	loading.value = true
	try {
		const res = await getUnitList(1, 100)
		const d = res?.data
		if (d.success) {
			unitOptions.value = Array.isArray(d?.data) ? d.data : []
		} else {
		}
	} finally {
		loading.value = false
	}
}

async function handleGenerate() {
	if (!unitId.value || !props.studentId) return
	const res = await generateLessonPlan(Number(props.studentId), Number(unitId.value), Number(wordSize.value))
	const d = res?.data
	if (d.success) {
		ElMessage.success('生成学案任务已提交，请等待十分钟')
		emit('success', { studentId: Number(props.studentId) })
		visible.value = false
	} else {
		showMessage(d.message || '生成学案失败，请联系管理员', 'error')
		visible.value = false
	}
}

watch(
	() => props.modelValue,
	(v) => {
		if (v) {
			unitId.value = null
			fetchUnits()
		}
	}
)
</script>

<style scoped></style>
