<template>
	<el-dialog v-model="visible" title="词条记录详情" width="820px" :fullscreen="isMobile" :close-on-click-modal="false" class="responsive-dialog">
		<div class="space-y-4" v-loading="loading">
			<el-card shadow="hover">
				<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
					<div>
						<div class="text-gray-500 text-sm">记录ID</div>
						<div class="text-base font-medium">{{ detail?.id ?? '-' }}</div>
					</div>
					<div>
						<div class="text-gray-500 text-sm">学生</div>
						<div class="text-base font-medium">
							{{ studentDetail?.name ?? '-' }}
						</div>
						<div class="text-gray-500 text-xs mt-1">
							班级：{{ studentDetail?.className ?? '-' }}　年级：{{ studentDetail?.gradeName ?? '-' }}
						</div>
					</div>
					<div>
						<div class="text-gray-500 text-sm">试题ID</div>
						<div class="text-base font-medium">{{ detail?.examWordsId ?? '-' }}</div>
					</div>
				</div>
				<div class="mt-4 flex flex-wrap items-center gap-3">
					<el-tag type="success">正确词数：{{ detail?.correctWordCount ?? 0 }}</el-tag>
					<el-tag type="danger">错误词数：{{ detail?.wrongWordCount ?? 0 }}</el-tag>
					<el-tag :type="detail?.isFinished === 1 ? 'success' : 'info'">
						{{ detail?.isFinished === 1 ? '已完成' : '未完成' }}
					</el-tag>
					<el-tag>
						开始时间：{{ detail?.startDate ?? '-' }}
					</el-tag>
				</div>
				<div class="mt-2" v-if="detail?.errorMsg">
					<el-alert :title="detail.errorMsg" type="warning" show-icon :closable="false" />
				</div>
			</el-card>

			<el-card shadow="never">
				<el-collapse v-model="activeNames">
					<el-collapse-item :name="'correct'">
						<template #title>
							正确词条（{{ detail?.correctWordCount ?? 0 }}）
						</template>
						<el-scrollbar style="max-height: 240px">
							<div class="flex flex-wrap gap-2">
								<template v-if="(correctTitles.length ?? 0) > 0">
									<el-tag v-for="(title, idx) in correctTitles" :key="'c-' + idx" type="success"
										effect="plain">
										{{ title }}
									</el-tag>
								</template>
								<div v-else class="text-gray-500">暂无数据</div>
							</div>
						</el-scrollbar>
					</el-collapse-item>

					<el-collapse-item :name="'wrong'">
						<template #title>
							错误词条（{{ detail?.wrongWordCount ?? 0 }}）
						</template>
						<el-scrollbar style="max-height: 240px">
							<div class="flex flex-wrap gap-2">
								<template v-if="(wrongTitles.length ?? 0) > 0">
									<el-tag v-for="(title, idx) in wrongTitles" :key="'w-' + idx" type="danger"
										effect="plain">
										{{ title }}
									</el-tag>
								</template>
								<div v-else class="text-gray-500">暂无数据</div>
							</div>
						</el-scrollbar>
					</el-collapse-item>
				</el-collapse>
			</el-card>
		</div>
	</el-dialog>
	<div v-if="false"></div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onBeforeUnmount } from 'vue'
import { getExamWordsDetailResult } from '@/api/exam'
import { getStudentDetail } from '@/api/student'
import { getWordsListByIds } from '@/api/words'

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

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

const loading = ref(false)
const detail = ref(null)
const activeNames = ref(['correct', 'wrong'])
const correctTitles = ref([])
const wrongTitles = ref([])
const studentDetail = ref(null)
const isMobile = ref(false)

async function fetchDetail() {
	if (!props.id && props.id !== 0) return
	loading.value = true
	try {
		const res = await getExamWordsDetailResult(Number(props.id))
		const d = res?.data?.data ?? null
		detail.value = d
		await fetchTitles()
		await fetchStudent()
	} finally {
		loading.value = false
	}
}

async function fetchTitles() {
	correctTitles.value = []
	wrongTitles.value = []
	const cIds = detail.value?.correctWordIds || []
	const wIds = detail.value?.wrongWordIds || []
	const tasks = []
	if (cIds.length > 0) {
		tasks.push(
			getWordsListByIds(cIds).then(res => {
				correctTitles.value = res?.data?.data?.wordTitles || []
			})
		)
	}
	if (wIds.length > 0) {
		tasks.push(
			getWordsListByIds(wIds).then(res => {
				wrongTitles.value = res?.data?.data?.wordTitles || []
			})
		)
	}
	if (tasks.length > 0) {
		await Promise.all(tasks)
	}
}

async function fetchStudent() {
	studentDetail.value = null
	const sid = detail.value?.studentId
	if (!sid && sid !== 0) return
	const res = await getStudentDetail(Number(sid))
	studentDetail.value = res?.data?.data ?? null
}

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

watch(
	() => props.modelValue,
	(v) => {
		if (v) {
			updateIsMobile()
			fetchDetail()
		}
	}
)
watch(
	() => props.id,
	(v) => {
		if (visible.value && v !== undefined && v !== null) fetchDetail()
	}
)

onMounted(() => {
	updateIsMobile()
	window.addEventListener('resize', updateIsMobile)
})
onBeforeUnmount(() => {
	window.removeEventListener('resize', updateIsMobile)
})
</script>

<style scoped>
.responsive-dialog :deep(.el-dialog__body) {
	max-height: 70vh;
	overflow-y: auto;
}
</style>
