<template>
    <div class="common-layout">
        <el-container>
            <el-header>
                <Header></Header>
            </el-header>

            <el-main class="p-4">
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-6" v-loading="loading">
                    <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
                        <div class="text-lg font-semibold mb-4">学生详情</div>
                        <template v-if="detail">
                            <el-descriptions :column="1" border>
                                <el-descriptions-item label="ID">{{ detail.id }}</el-descriptions-item>
                                <el-descriptions-item label="姓名">{{ detail.name }}</el-descriptions-item>
                                <el-descriptions-item label="班级">{{ detail.className }}</el-descriptions-item>
                                <el-descriptions-item label="年级">{{ detail.gradeName }}</el-descriptions-item>
                                <el-descriptions-item label="学生实际水平年级">{{ detail.actualGrade }}</el-descriptions-item>
                            </el-descriptions>
                        </template>
                        <template v-else>
                            <el-empty description="请从班级页跳转" />
                        </template>
                    </div>

                    <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
                        <div class="text-lg font-semibold mb-4">学生词汇统计</div>
                        <template v-if="wordStat">
                            <el-descriptions :column="1" border>
                                <el-descriptions-item label="已掌握">{{ wordStat.masteredWordCount }}</el-descriptions-item>
                                <el-descriptions-item label="未掌握">{{ wordStat.unmasteredWordCount }}</el-descriptions-item>
                                <el-descriptions-item label="待复习">{{ wordStat.pendingReviewWordCount }}</el-descriptions-item>
                            </el-descriptions>
                        </template>
                        <template v-else>
                            <el-empty description="暂无统计" />
                        </template>
                    </div>

                    <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
                        <div class="text-md font-semibold mb-3">学生考试记录</div>
                        <ExamHistoryChart :data="history" />
                    </div>
                    <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
                        <div class="text-md font-semibold mb-3">学生学案记录</div>
                        <PlanHistoryChart :student-id="route.params.id" />
                    </div>
                    <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
                        <div class="text-md font-semibold mb-3">词汇掌握热力图</div>
                        <WordMasteryHeatmap :student-id="route.params.id" :columns="50" />
                    </div>
                    <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
                        <div class="flex items-center justify-between mb-3">
                            <div class="text-md font-semibold">学习分析</div>
                            <el-button type="primary" size="small" :loading="analyzeLoading" @click="fetchStudyAnalyze">
                                生成学习分析
                            </el-button>
                        </div>
                        <template v-if="analyzeLoading">
                            <div class="space-y-2">
                                <el-progress :percentage="analyzeProgress" :stroke-width="10" />
                                <div class="text-sm text-gray-500 dark:text-gray-400">正在生成学习分析，请稍候…</div>
                            </div>
                        </template>
                        <template v-else-if="analysisHtml">
                            <div class="leading-7 text-gray-700 dark:text-gray-200" v-html="analysisHtml"></div>
                        </template>
                        <template v-else>
                            <el-empty description="点击右上按钮生成学习分析" />
                        </template>
                    </div>
                </div>
            </el-main>

        </el-container>
    </div>
</template>

<script setup>
import Header from '@/layouts/components/Header.vue'
import { ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { getStudentDetail, getStudentStudyAnalyze } from '@/api/student'
import { getStudentExamHistory } from '@/api/exam'
import { getWordStudentDetail } from '@/api/words'
import ExamHistoryChart from '@/layouts/components/student/ExamHistoryChart.vue'
import PlanHistoryChart from '@/layouts/components/student/PlanHistoryChart.vue'
import WordMasteryHeatmap from '@/layouts/components/student/WordMasteryHeatmap.vue'
import MarkdownIt from 'markdown-it'

const loading = ref(false)
const detail = ref(null)
const route = useRoute()
const history = ref([])
const analyzeLoading = ref(false)
const analyzeProgress = ref(0)
let analyzeTimer = null
const analysisText = ref('')
const wordStat = ref(null)
const md = new MarkdownIt({
    html: false,
    linkify: true,
    breaks: true
})
const analysisHtml = computed(() => {
    return analysisText.value ? md.render(analysisText.value) : ''
})

async function fetchDetail() {
    const id = route.params.id
    if (!id) return
    loading.value = true
    try {
        const res = await getStudentDetail(id)
        const d = res.data
        detail.value = d?.data || null
    } finally {
        loading.value = false
    }
}

async function fetchExamHistory() {
    const id = route.params.id
    if (!id) return
    const res = await getStudentExamHistory(id)
    const d = res.data
    history.value = Array.isArray(d?.data) ? d.data.slice().sort((a, b) => {
        return new Date(a.startDate).getTime() - new Date(b.startDate).getTime()
    }) : []
}

async function fetchStudyAnalyze() {
    const id = route.params.id
    if (!id) return
    analyzeLoading.value = true
    analyzeProgress.value = 0
    if (analyzeTimer) {
        clearInterval(analyzeTimer)
        analyzeTimer = null
    }
    analyzeTimer = setInterval(() => {
        const inc = Math.floor(Math.random() * 8) + 3
        const next = analyzeProgress.value + inc
        analyzeProgress.value = next >= 90 ? 90 : next
    }, 300)
    try {
        const res = await getStudentStudyAnalyze({
            studentId: Number(id)
        })
        const d = res.data
        const raw = typeof d?.data === 'string' ? d.data : ''
        analysisText.value = raw.replace(/\\n/g, '\n')
    } finally {
        analyzeProgress.value = 100
        if (analyzeTimer) {
            clearInterval(analyzeTimer)
            analyzeTimer = null
        }
        analyzeLoading.value = false
    }
}

async function fetchWordStat() {
    const id = route.params.id
    if (!id) return
    const res = await getWordStudentDetail(Number(id))
    const d = res.data
    wordStat.value = d?.data || null
}

onMounted(() => {
    fetchDetail()
    fetchExamHistory()
    fetchWordStat()
})
</script>
