<template>
	<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>
</template>

<script setup>
import { ref, computed } from 'vue'
import MarkdownIt from 'markdown-it'
import { getStudentStudyAnalyze } from '@/api/student'

const props = defineProps({
	studentId: {
		type: [String, Number],
		required: true
	}
})

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

async function fetchStudyAnalyze() {
	const id = props.studentId
	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
	}
}
</script>
