<template>
	<el-dialog v-model="visible" title="学生学案列表" width="680px" :close-on-click-modal="false">
		<div v-loading="loading">
			<el-table :data="plans" border>
				<el-table-column prop="title" label="标题" min-width="360" />
				<el-table-column label="状态" width="120">
					<template #default="{ row }">
						<el-tag :type="row.isFinished === 1 ? 'success' : 'info'" effect="plain">
							{{ row.isFinished === 1 ? '已完成' : '未完成' }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="160" fixed="right">
					<template #default="{ row }">
						<el-button
							type="primary"
							size="small"
							:loading="downloadingIds.includes(row.id)"
							@click="handleDownload(row)"
						>下载</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<template #footer>
			<div class="flex justify-end gap-2">
				<el-button @click="visible = false">关闭</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { getPlanListByStudentId, downloadLessonPlan } 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'])

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

const loading = ref(false)
const plans = ref([])
const downloadingIds = ref([])

async function fetchPlans() {
	if (!props.studentId) return
	loading.value = true
	try {
		const res = await getPlanListByStudentId(Number(props.studentId))
		const d = res?.data
		if (d?.success !== false) {
			const items = d?.data?.lessonPlanItems
			plans.value = Array.isArray(items) ? items : []
		} else {
			showMessage(d?.message || '获取学案失败', 'error')
		}
	} finally {
		loading.value = false
	}
}

async function handleDownload(row) {
	if (!row?.id) {
		showMessage('无效的计划ID', 'error')
		return
	}
	if (!downloadingIds.value.includes(row.id)) {
		downloadingIds.value = [...downloadingIds.value, row.id]
	}
	try {
		await downloadLessonPlan({ id: row.id })
		showMessage('开始下载', 'success')
	} finally {
		downloadingIds.value = downloadingIds.value.filter(id => id !== row.id)
	}
}

watch(
	() => props.modelValue,
	(v) => {
		if (v) {
			fetchPlans()
		}
	}
)
</script>

<style scoped></style>
