<template>
	<div class="teaching-activity-analysis">
		<!-- 页面头部 -->
		<div class="header">
			<h1>📚 教学活动分析</h1>
			<p>为教学过程及课程内容改进提供数据支撑</p>
		</div>

		<!-- 筛选条件 -->
		<div class="filter-section">
			<h3>🔍 数据筛选</h3>
			<div class="filter-controls">
				<div class="filter-group">
					<label>选择课程</label>
					<a-select
						v-model:value="filters.courseId"
						placeholder="全部课程"
						@change="updateStats"
						:loading="loading"
						allowClear
					>
						<a-select-option v-for="option in courseOptions" :key="option.courseId" :value="option.courseId">
							{{ option.courseName }}
						</a-select-option>
					</a-select>
				</div>
				<div class="filter-group">
					<label>时间范围</label>
<!--					<a-select v-model:value="filters.timeRange" @change="updateStats">-->
<!--						<a-select-option :value="1">最近30天</a-select-option>-->
<!--						<a-select-option :value="2">最近90天</a-select-option>-->
<!--						<a-select-option :value="3">最近180天</a-select-option>-->
<!--						<a-select-option :value="4">最近一年</a-select-option>-->
<!--					</a-select>-->
					<a-range-picker class="w-full" v-model:value="times" />
				</div>
				<div class="filter-group">
					<a-button type="primary" @click="updateStats" :loading="loading">查询</a-button>
				</div>
			</div>
		</div>

		<!-- 核心统计数据 -->
		<div class="stats-grid">
			<div class="stat-card">
				<h3>📖 文档观看统计</h3>
				<div class="stat-number">{{ stats.allUserCount }}</div>
				<div class="stat-label">总观看人数</div>
				<div class="stat-number">{{ stats.alreadyUserCount }}</div>
				<div class="stat-label">完成观看人数</div>
				<div class="completion-rate">{{tool.formatValue(stats.finishRate) }}</div>
				<div class="stat-label">完成率</div>
			</div>

			<div class="stat-card">
				<h3>🚪 文档跳出分析</h3>
				<div class="stat-number">{{ stats.allHourCount }}</div>
				<div class="stat-label">总跳出次数</div>
				<div class="stat-number">{{tool.formatValue(stats.allHourCount)  }}</div>
				<div class="stat-label">跳出率</div>
				<div class="stat-number">{{ stats.jumpAvgTime }}</div>
				<div class="stat-label">平均跳出时间</div>
			</div>

			<div class="stat-card" v-if="forumType">
				<h3>💬 讨论互动统计</h3>
				<div class="stat-number">{{ stats.totalDiscussions }}</div>
				<div class="stat-label">讨论总数</div>
				<div class="stat-number">{{ stats.totalReplies }}</div>
				<div class="stat-label">回帖总数</div>
				<div class="stat-number">{{ stats.avgRepliesPerDiscussion }}</div>
				<div class="stat-label">平均回帖数</div>
			</div>
		</div>

		<!-- 每日访问统计图表 -->
		<div class="chart-container">
			<h3>📈 开课每日访问人数统计</h3>
			<div ref="dailyVisitsChart" class="chart"></div>
		</div>

		<!-- 每周发帖回帖统计 -->
		<div class="weekly-stats" v-if="forumType">
			<div class="weekly-card">
				<h4>👨‍🎓 学员每周发帖统计</h4>
				<div class="weekly-number">{{ weeklyStats.studentWeeklyPosts }}</div>
				<div class="weekly-label">本周发帖数</div>
				<div class="weekly-number">{{ weeklyStats.studentWeeklyReplies }}</div>
				<div class="weekly-label">本周回帖数</div>
				<div class="weekly-number">{{ weeklyStats.studentAvgPostsPerDay }}</div>
				<div class="weekly-label">日均发帖数</div>
			</div>

			<div class="weekly-card">
				<h4>👨‍🏫 教员每周发帖统计</h4>
				<div class="weekly-number">{{ weeklyStats.teacherWeeklyPosts }}</div>
				<div class="weekly-label">本周发帖数</div>
				<div class="weekly-number">{{ weeklyStats.teacherWeeklyReplies }}</div>
				<div class="weekly-label">本周回帖数</div>
				<div class="weekly-number">{{ weeklyStats.teacherAvgPostsPerDay }}</div>
				<div class="weekly-label">日均发帖数</div>
			</div>
		</div>

		<!-- 讨论详情表格 -->
		<div class="data-table" v-if="forumType">
			<h3>💬 课程讨论详情</h3>
			<a-table
				:columns="discussionColumns"
				:data-source="discussionData"
				:pagination="discussionPagination"
				:loading="loading"
				row-key="id"
				@change="handleDiscussionTableChange"
			/>
		</div>

		<!-- 文档观看详细统计 -->
		<div class="data-table">
			<h3>📚 文档观看详细统计</h3>
			<a-table
				:columns="documentColumns"
				:data-source="documentData"
				:pagination="documentPagination"
				:loading="loading"
				row-key="id"
				@change="handleDocumentTableChange"
			/>
		</div>
	</div>
</template>

<script setup>
import {ref, reactive, onMounted, nextTick, h, computed} from 'vue'
	import * as echarts from 'echarts'
	import {
		getCourseOptions,
		getTeachingStats,
		documentJumpStatistic,
		getWeeklyStats,
		getDailyVisits,
		getDiscussionData,
		getDocumentStats
	} from '@/api/statisticalAnalysis/analysisTeachingActivities'
	import tool from '@/utils/tool'
import dayjs from "dayjs";
// 课程选项
const courseOptions = ref([])
const times = ref([])
	const forumType = computed(() => (tool.dictList('FORUM_TYPE')[0].value == 1 ? true : false))
	// 响应式数据
	const filters = reactive({
		courseId: undefined,
		startTime: computed(() => (  times.value && times.value[0] ? dayjs(times.value[0]).format('YYYY-MM-DD') :  undefined)),
		endTime: computed(() => (times.value && times.value[1] ? dayjs(times.value[1]).format('YYYY-MM-DD') :  undefined))
	})

	const stats = reactive({
		totalDiscussions: 0,
		totalReplies: 0,
		avgRepliesPerDiscussion: 0
	})

	const weeklyStats = reactive({
		studentWeeklyPosts: 0,
		studentWeeklyReplies: 0,
		studentAvgPostsPerDay: 0,
		teacherWeeklyPosts: 0,
		teacherWeeklyReplies: 0,
		teacherAvgPostsPerDay: 0
	})



	// 图表引用
	const dailyVisitsChart = ref(null)
	let chartInstance = null

	// 讨论表格列定义
	const discussionColumns = [
		{
			title: '讨论主题',
			dataIndex: 'title',
			key: 'title'
		},
		{
			title: '发起人',
			dataIndex: 'author',
			key: 'author'
		},
		{
			title: '发起时间',
			dataIndex: 'createTime',
			key: 'createTime'
		},
		{
			title: '回帖数',
			dataIndex: 'replyCount',
			key: 'replyCount'
		},
		{
			title: '最后回复',
			dataIndex: 'lastReplyTime',
			key: 'lastReplyTime'
		}
	]

	// 讨论数据
	const discussionData = ref([])
	const discussionPagination = reactive({
		current: 1,
		pageSize: 10,
		total: 0
	})

	// 文档表格列定义
	const documentColumns = [
		{
			title: '文档名称',
			dataIndex: 'fileName',
			key: 'fileName'
		},
		{
			title: '文档类型',
			dataIndex: 'extendName',
			key: 'extendName',
			width: '100px'
		},
		{
			title: '观看人数',
			dataIndex: 'seeNum',
			key: 'seeNum',
			width: '100px'
		},
		{
			title: '完成人数',
			dataIndex: 'finishNum',
			key: 'finishNum',
			width: '100px'
		},
		{
			title: '完成率',
			dataIndex: 'finishRate',
			key: 'finishRate',
			customRender: ({ text }) => {
				const rate = parseFloat(text)
				const className = rate >= 70 ? 'completion-rate' : rate < 50 ? 'low-engagement' : ''
				return h('span', { class: className }, `${text}%`)
			}
		},
		{
			title: '平均阅读时长',
			dataIndex: 'jumpAvgTime',
			key: 'jumpAvgTime',
			width: '130px'
		},
		{
			title: '跳出率',
			dataIndex: 'jumpRate',
			key: 'jumpRate',
			customRender: ({ text }) => {
				const rate = parseFloat(text)
				const className = rate > 30 ? 'low-engagement' : ''
				return h('span', { class: className }, `${text}%`)
			}
		},
		{
			title: '下载次数',
			dataIndex: 'downNum',
			key: 'downNum',
			width: '100px'
		}
	]

	// 文档数据
	const documentData = ref([])
	const documentPagination = reactive({
		current: 1,
		pageSize: 10,
		total: 0
	})
	// 图表数据
	const chartData = reactive({
		dates: [],
		visits: []
	})

	// 加载状态
	const loading = ref(false)

	// 初始化图表
	const initChart = () => {
		if (!dailyVisitsChart.value) return

		chartInstance = echarts.init(dailyVisitsChart.value)
		updateChartData()

		// 响应式处理
		window.addEventListener('resize', () => {
			chartInstance?.resize()
		})
	}

	// 更新图表数据
	const updateChartData = () => {
		if (!chartInstance) return

		const days = filters.timeRange
		const { dates, visits } = chartData

		const option = {
			title: {
				text: `最近一个月访问人数趋势`,
				left: 'center',
				textStyle: {
					color: '#2c3e50',
					fontSize: 16,
					fontWeight: 'bold'
				}
			},
			tooltip: {
				trigger: 'axis',
				backgroundColor: 'rgba(255, 255, 255, 0.95)',
				borderColor: '#3498db',
				borderWidth: 1,
				textStyle: {
					color: '#333'
				},
				formatter: function (params) {
					let result = params[0].name + '<br/>'
					params.forEach((param) => {
						result += param.marker + param.seriesName + ': ' + param.value + '人<br/>'
					})
					return result
				}
			},
			legend: {
				data: ['访问人数'],
				top: 30,
				textStyle: {
					color: '#2c3e50'
				}
			},
			grid: {
				left: '3%',
				right: '4%',
				bottom: '3%',
				containLabel: true
			},
			xAxis: {
				type: 'category',
				boundaryGap: false,
				data: dates,
				axisLine: {
					lineStyle: {
						color: '#bdc3c7'
					}
				},
				axisLabel: {
					color: '#2c3e50',
					rotate: days > 30 ? 45 : 0
				}
			},
			yAxis: {
				type: 'value',
				name: '访问人数',
				nameTextStyle: {
					color: '#2c3e50'
				},
				axisLine: {
					lineStyle: {
						color: '#bdc3c7'
					}
				},
				axisLabel: {
					color: '#2c3e50'
				},
				splitLine: {
					lineStyle: {
						color: '#ecf0f1'
					}
				}
			},
			series: [
				{
					name: '访问人数',
					type: 'line',
					smooth: true,
					data: visits,
					itemStyle: {
						color: '#3498db'
					},
					areaStyle: {
						color: {
							type: 'linear',
							x: 0,
							y: 0,
							x2: 0,
							y2: 1,
							colorStops: [
								{
									offset: 0,
									color: 'rgba(52, 152, 219, 0.3)'
								},
								{
									offset: 1,
									color: 'rgba(52, 152, 219, 0.1)'
								}
							]
						}
					},
					lineStyle: {
						width: 3
					},
					symbol: 'circle',
					symbolSize: 8
				}
			]
		}

		chartInstance.setOption(option, true)
	}

	// 获取课程选项
	const loadCourseOptions = async () => {
		try {
			const response = await getCourseOptions()
			courseOptions.value = response
		} catch (error) {
			console.error('获取课程选项失败:', error)
		}
	}

	// 获取核心统计数据
	const loadTeachingStats = async () => {
		try {
			const response = await getTeachingStats({
				courseId: filters.courseId,
				startTime: filters.startTime,
				endTime: filters.endTime,
			})
			const statistic = await documentJumpStatistic({
				courseId: filters.courseId,
				startTime: filters.startTime,
				endTime: filters.endTime,
			})

			Object.assign(stats, response, statistic)
		} catch (error) {
			console.error('获取统计数据失败:', error)
		}
	}

	// 获取每周统计数据
	const loadWeeklyStats = async () => {
		try {
			const response = await getWeeklyStats({
				courseId: filters.courseId
			})
			Object.assign(weeklyStats, response)
		} catch (error) {
			console.error('获取每周统计数据失败:', error)
		}
	}

	// 获取每日访问数据
	const loadDailyVisits = async () => {
		try {
			const response = await getDailyVisits({
				courseId: filters.courseId
			})
			chartData.dates = response.map((r) => r.TIME)
			chartData.visits = response.map((r) => r.num)
			updateChartData()
		} catch (error) {
			console.error('获取每日访问数据失败:', error)
		}
	}

	// 获取讨论数据
	const loadDiscussionData = async () => {
		try {
			const response = await getDiscussionData({
				courseId: filters.courseId,
				startTime: filters.startTime,
				endTime: filters.endTime,
				page: discussionPagination.current,
				pageSize: discussionPagination.pageSize
			})
			discussionData.value = response.list
			discussionPagination.total = response.total
		} catch (error) {
			console.error('获取讨论数据失败:', error)
		}
	}

	// 获取文档数据
	const loadDocumentData = async () => {
		try {
			const response = await getDocumentStats({
				courseId: filters.courseId,
				page: documentPagination.current,
				pageSize: documentPagination.pageSize,
				startTime: filters.startTime,
				endTime: filters.endTime,
			})
			documentData.value = response
			documentPagination.total = response.total
		} catch (error) {
			console.error('获取文档数据失败:', error)
		}
	}

	// 更新所有数据
	const updateStats = async () => {
		loading.value = true
		try {
			await Promise.all([
				loadTeachingStats(),
				loadWeeklyStats(),
				loadDailyVisits(),
				loadDiscussionData(),
				loadDocumentData()
			])
		} finally {
			loading.value = false
		}
	}

	// 初始化所有数据
	const initData = async () => {
		loading.value = true
		try {
			await Promise.all([
				loadCourseOptions(),
				loadTeachingStats(),
				loadWeeklyStats(),
				loadDailyVisits(),
				loadDiscussionData(),
				loadDocumentData()
			])
		} finally {
			loading.value = false
		}
	}

	// 处理讨论表格分页变化
	const handleDiscussionTableChange = (pagination) => {
		discussionPagination.current = pagination.current
		discussionPagination.pageSize = pagination.pageSize
		loadDiscussionData()
	}

	// 处理文档表格分页变化
	const handleDocumentTableChange = (pagination) => {
		documentPagination.current = pagination.current
		documentPagination.pageSize = pagination.pageSize
		loadDocumentData()
	}

	// 组件挂载后初始化
	onMounted(() => {
		nextTick(() => {
			initChart()
			initData()
		})
	})
</script>

<style scoped>
	.teaching-activity-analysis {
		padding: 20px;
		/* background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); */
	}

	.header {
		background: rgba(255, 255, 255, 0.95);
		backdrop-filter: blur(10px);
		border-radius: 15px;
		padding: 30px;
		margin-bottom: 30px;
		box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
		text-align: center;
	}

	.header h1 {
		color: #2c3e50;
		font-size: 2.5em;
		margin-bottom: 10px;
	}

	.header p {
		color: #7f8c8d;
		font-size: 1.1em;
	}

	.filter-section {
		background: rgba(255, 255, 255, 0.95);
		backdrop-filter: blur(10px);
		border-radius: 15px;
		padding: 25px;
		margin-bottom: 30px;
		box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
	}

	.filter-section h3 {
		color: #2c3e50;
		margin-bottom: 20px;
		font-size: 1.5em;
	}

	.filter-controls {
		display: grid;
		grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
		gap: 15px;
		align-items: end;
	}

	.filter-group {
		display: flex;
		flex-direction: column;
	}

	.filter-group label {
		margin-bottom: 8px;
		color: #2c3e50;
		font-weight: 600;
	}

	.stats-grid {
		display: grid;
		grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
		gap: 25px;
		margin-bottom: 30px;
	}

	.stat-card {
		background: rgba(255, 255, 255, 0.95);
		backdrop-filter: blur(10px);
		border-radius: 15px;
		padding: 25px;
		box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
		transition: transform 0.3s ease, box-shadow 0.3s ease;
	}

	.stat-card:hover {
		transform: translateY(-5px);
		box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
	}

	.stat-card h3 {
		color: #2c3e50;
		margin-bottom: 15px;
		font-size: 1.3em;
		border-bottom: 2px solid #3498db;
		padding-bottom: 10px;
	}

	.stat-number {
		font-size: 2.5em;
		font-weight: bold;
		color: #3498db;
		margin-bottom: 10px;
	}

	.stat-label {
		color: #7f8c8d;
		font-size: 0.9em;
	}

	.chart-container {
		background: rgba(255, 255, 255, 0.95);
		backdrop-filter: blur(10px);
		border-radius: 15px;
		padding: 25px;
		margin-bottom: 30px;
		box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
	}

	.chart-container h3 {
		color: #2c3e50;
		margin-bottom: 20px;
		font-size: 1.5em;
	}

	.chart {
		height: 400px;
		border-radius: 10px;
	}

	.weekly-stats {
		display: grid;
		grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
		gap: 20px;
		margin-bottom: 30px;
	}

	.weekly-card {
		background: rgba(255, 255, 255, 0.95);
		backdrop-filter: blur(10px);
		border-radius: 15px;
		padding: 20px;
		box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
	}

	.weekly-card h4 {
		color: #2c3e50;
		margin-bottom: 15px;
		font-size: 1.2em;
	}

	.weekly-number {
		font-size: 2em;
		font-weight: bold;
		color: #3498db;
		margin-bottom: 5px;
	}

	.weekly-label {
		color: #7f8c8d;
		font-size: 0.9em;
	}

	.data-table {
		background: rgba(255, 255, 255, 0.95);
		backdrop-filter: blur(10px);
		border-radius: 15px;
		padding: 25px;
		margin-bottom: 30px;
		box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
	}

	.data-table h3 {
		color: #2c3e50;
		margin-bottom: 20px;
		font-size: 1.5em;
	}

	:deep(.completion-rate) {
		color: #27ae60;
		font-weight: bold;
		font-size: 2.5em;
	}

	:deep(.low-engagement) {
		color: #e74c3c;
		font-weight: bold;
	}

	@media (max-width: 768px) {
		.stats-grid {
			grid-template-columns: 1fr;
		}

		.filter-controls {
			grid-template-columns: 1fr;
		}

		.header h1 {
			font-size: 2em;
		}

		.weekly-stats {
			grid-template-columns: 1fr;
		}
	}
</style>
