<template>
	<div class="video-analysis-container">
		<!-- 页面头部 -->
		<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="全部课程" style="width: 100%">
						<a-select-option value="">全部课程</a-select-option>
						<a-select-option v-for="course in courseOptions" :key="course.courseId" :value="course.courseId">
							{{ course.courseName }}
						</a-select-option>
					</a-select>
				</div>
				<!-- 日期范围选择 -->
				<div class="flex-1 mr-4">
					<label class="block text-sm font-medium text-gray-700 mb-1">时间</label>
<!--					<a-date-picker v-model:value="startTime" class="w-full" placeholder="开始时间" />-->
					<a-range-picker class="w-full" v-model:value="times" />
				</div>

<!--				<div class="flex-1 mr-4">-->
<!--					<label class="block text-sm font-medium text-gray-700 mb-1">结束时间</label>-->
<!--					<a-date-picker v-model:value="endTime" class="w-full" placeholder="结束时间" />-->
<!--				</div>-->

				<div class="filter-group">
					<a-button type="primary" @click="updateStats">查询</a-button>
				</div>
			</div>
		</div>

		<!-- 核心统计数据 -->
		<div class="stats-grid">
			<div class="stat-card" v-if="stats.countData">
				<h3>👥 观看人数统计</h3>
				<div class="stat-number">{{ stats.countData.alreadyWatchUserCount }}</div>
				<div class="stat-label">总观看人数</div>
				<div class="stat-number">{{ stats.countData.completeWatchUserCount }}</div>
				<div class="stat-label">完成观看人数</div>
				<div class="completion-rate">{{ tool.formatValue(stats.countData.completeRate) }}</div>
				<div class="stat-label">完成率</div>
			</div>

			<div class="stat-card" v-if="stats.downData">

				<h3>📥 讲义下载统计</h3>
				<div class="stat-number">{{ stats.downData.allDownloadCount }}</div>
				<div class="stat-label">总下载次数</div>
				<div class="stat-number">{{tool.formatValue(stats.downData.downloadRate)}}</div>
				<div class="stat-label">下载率</div>
				<div class="stat-number">{{ stats.downData.avgDownloadCount }}</div>
				<div class="stat-label">人均下载次数</div>
			</div>

			<div class="stat-card" v-if="stats.jumpData">
				<h3>⏱️ 跳出时间分析</h3>
				<div class="stat-number">{{ stats.jumpData.jumpOutCount }}</div>
				<div class="stat-label">总跳出次数</div>
				<div class="stat-number">{{tool.formatValue(stats.jumpData.jumpOutRate)}}</div>
				<div class="stat-label">跳出率</div>
				<div class="stat-number">{{ stats.jumpData.jumpAvgTime }}</div>
				<div class="stat-label">平均跳出时间</div>
			</div>

			<div class="stat-card" v-if="stats.interdata">
				<h3>📝 互动数据统计</h3>
				<div class="stat-number">{{ stats.interdata.noteCount }}</div>
				<div class="stat-label">笔记总数</div>
				<div class="stat-number">{{ stats.interdata.postCount }}</div>
				<div class="stat-label">讨论总数</div>
				<div class="stat-number">{{ stats.interdata.replyCount }}</div>
				<div class="stat-label">回帖总数</div>
			</div>
		</div>

		<!-- ECharts 图表区域 -->
		<div class="charts-section" v-if="false">
			<!-- 学习进度分布图 -->
			<div class="chart-container">
				<h3>📈 学习进度分布</h3>
				<div ref="progressChart" class="chart"></div>
			</div>

			<!-- 观看时长趋势图 -->
			<div class="chart-container">
				<h3>📊 观看时长趋势</h3>
				<div ref="timeChart" class="chart"></div>
			</div>

			<!-- 章节完成率对比图 -->
			<div class="chart-container">
				<h3>📚 章节完成率对比</h3>
				<div ref="chapterChart" class="chart"></div>
			</div>

			<!-- 互动数据统计图 -->
			<div class="chart-container">
				<h3>💬 互动数据统计</h3>
				<div ref="interactionChart" class="chart"></div>
			</div>
		</div>

		<!-- 学员详细数据表格 -->
		<div class="data-table">
			<h3>👤 学员学习行为详细数据</h3>
			<a-table
				:columns="studentColumns"
				:data-source="studentData"
				:pagination="pagination"
				:loading="loading"
			>
				<template #bodyCell="{ column, record }">
					<template v-if="column.key === 'finishRate'">
						<div class="progress-container">
							<a-progress :percent="record.finishRate * 100" size="small" />
							<span :class="{ 'low-engagement': record.finishRate * 100 < 50 }"> {{ record.finishRate * 100 }}% </span>
						</div>
					</template>
					<template v-else-if="column.key === 'jumpTimeContact'">
						<span v-for="point in record.jumpTimeContactArr" :key="point" class="time-point">
							{{ point }}
						</span>
					</template>
				</template>
			</a-table>
		</div>

		<!-- 视频章节详细统计 -->
		<div class="data-table">
			<h3>📚 视频章节详细统计</h3>
			<a-table
				:columns="chapterColumns"
				:data-source="chapterData"
				:pagination="chapterPagination"
				:loading="chapterLoading"
			>
				<template #bodyCell="{ column, record }">
					<template v-if="column.key === 'completeRate'">
						<span
							:class="{
								'completion-rate': record.completeRate * 100 >= 70,
								'low-engagement': record.completeRate * 100 < 70
							}"
						>
							{{ record.completeRate * 100 }}%
						</span>
					</template>
					<template v-else-if="column.key === 'jumpOutRate'">
						<span :class="{ 'low-engagement': record.jumpOutRate * 100 > 25 }"> {{ record.jumpOutRate * 100 }}% </span>
					</template>
				</template>
			</a-table>
		</div>
	</div>
</template>

<script setup>
	import { ref, reactive, onMounted, nextTick, watch, computed } from 'vue'
	import { message } from 'ant-design-vue'
	import * as echarts from 'echarts'
	import { getCourseOptions } from '@/api/statisticalAnalysis/analysisTeachingActivities'
	import { videoAnalysisApi } from '@/api/statisticalAnalysis/videoAnalysis'
	import dayjs from 'dayjs'
	import tool from "@/utils/tool";

	// 筛选条件
	const times = ref([])
	const startTime = ref('')
	const endTime = ref('')
	const filters = reactive({
		courseId: '',
		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 courseOptions = ref([])

	// 加载状态
	const loading = ref(false)
	const chapterLoading = ref(false)
	// 统计数据
	const stats = reactive({
		totalViewers: 2800,
		completedViewers: 2100,
		completionRate: 75,
		totalDownloads: 980,
		downloadRate: 35,
		avgDownloads: 0.35,
		totalExits: 560,
		exitRate: 20,
		avgExitTime: '12:34',
		totalNotes: 1680,
		totalDiscussions: 840,
		totalReplies: 2520
	})

	// 图表引用
	const progressChart = ref(null)
	const timeChart = ref(null)
	const chapterChart = ref(null)
	const interactionChart = ref(null)

	// 学员数据表格列定义
	const studentColumns = [
		{ title: '学员ID', dataIndex: 'userId', key: 'userId', width: 80 },
		{ title: '姓名', dataIndex: 'stuName', key: 'stuName', width: 100 },
		{ title: '访问总时长', dataIndex: 'allStayTime', key: 'allStayTime', width: 120 },
		{ title: '学习进度', dataIndex: 'finishRate', key: 'finishRate', width: 150 },
		{ title: '观看次数', dataIndex: 'watchCount', key: 'watchCount', width: 100 },
		{ title: '跳出时间点', dataIndex: 'jumpTimeContact', key: 'jumpTimeContact', width: 200 },
		{ title: '快进快退次数', dataIndex: 'quickOperaCount', key: 'quickOperaCount', width: 120 },
		{ title: '笔记数', dataIndex: 'noteCount', key: 'noteCount', width: 80 },
		{ title: '讨论数', dataIndex: 'postCount', key: 'postCount', width: 80 },
		{ title: '回帖数', dataIndex: 'replyCount', key: 'replyCount', width: 80 },
		{ title: '最后访问', dataIndex: 'lastLoginTime', key: 'lastLoginTime', width: 150 }
	]

	// 学员数据
	const studentData = ref([])

	// 分页配置
	const pagination = reactive({
		current: 1,
		pageSize: 10,
		total: 0,
		showSizeChanger: true,
		showQuickJumper: true,
		showTotal: (total, range) => `显示 ${range[0]}-${range[1]} 条，共 ${total} 条`,
		onChange: (page, pageSize) => {
			pagination.current = page
			pagination.pageSize = pageSize
			fetchStudentData()
		}
	})
	// 分页配置
	const chapterPagination = reactive({
		current: 1,
		pageSize: 10,
		total: 0,
		showTotal: (total, range) => `显示 ${range[0]}-${range[1]} 条，共 ${total} 条`,
		onChange: (page, pageSize) => {
			chapterPagination.current = page
			chapterPagination.pageSize = pageSize
			fetchChapterData()
		}
	})

	// 章节数据表格列定义
	const chapterColumns = [
		{ title: '课程名称', dataIndex: 'courseIdName', key: 'courseIdName', width: 200 },
		{ title: '章节名称', dataIndex: 'chapterIdName', key: 'chapterIdName', width: 200 },
		{ title: '课时名称', dataIndex: 'hourIdName', key: 'hourIdName', width: 200 },
		{ title: '视频时长', dataIndex: 'allStayTime', key: 'allStayTime', width: 100 },
		{ title: '观看人数', dataIndex: 'watchUserCount', key: 'watchUserCount', width: 100 },
		{ title: '完成人数', dataIndex: 'completeWatchUserCount', key: 'completeWatchUserCount', width: 100 },
		{ title: '完成率', dataIndex: 'completeRate', key: 'completeRate', width: 100 },
		{ title: '平均观看时长', dataIndex: 'avgStayTime', key: 'avgStayTime', width: 120 },
		{ title: '跳出率', dataIndex: 'jumpOutRate', key: 'jumpOutRate', width: 100 },
		{ title: '下载次数', dataIndex: 'downloadCount', key: 'downloadCount', width: 100 },
		{ title: '笔记数', dataIndex: 'noteCount', key: 'noteCount', width: 80 },
		{ title: '讨论数', dataIndex: 'postCount', key: 'postCount', width: 80 }
	]

	// 章节数据
	const chapterData = ref([])

	// 图表数据
	const chartData = reactive({
		progressDistribution: [],
		timeTrend: { chapters: [], watchTime: [], completedUsers: [] },
		chapterCompletion: { chapters: [], completionRates: [] },
		interactionData: { chapters: [], notes: [], discussions: [], replies: [] }
	})

	// 初始化图表
	const initCharts = () => {
		initProgressChart()
		initTimeChart()
		initChapterChart()
		initInteractionChart()
	}

	// 学习进度分布图
	const initProgressChart = () => {
		const chart = echarts.init(progressChart.value)
		const option = {
			title: {
				text: '学习进度分布',
				left: 'center'
			},
			tooltip: {
				trigger: 'item',
				formatter: '{a} <br/>{b}: {c} ({d}%)'
			},
			legend: {
				orient: 'vertical',
				left: 'left'
			},
			series: [
				{
					name: '学习进度',
					type: 'pie',
					radius: '50%',
					data:
						chartData.progressDistribution.length > 0
							? chartData.progressDistribution
							: [
									{ value: 420, name: '0-25%' },
									{ value: 560, name: '26-50%' },
									{ value: 700, name: '51-75%' },
									{ value: 1120, name: '76-100%' }
							  ],
					emphasis: {
						itemStyle: {
							shadowBlur: 10,
							shadowOffsetX: 0,
							shadowColor: 'rgba(0, 0, 0, 0.5)'
						}
					}
				}
			]
		}
		chart.setOption(option)
	}

	// 观看时长趋势图
	const initTimeChart = () => {
		const chart = echarts.init(timeChart.value)
		const option = {
			title: {
				left: 'center'
			},
			tooltip: {
				trigger: 'axis'
			},
			legend: {
				data: ['观看时长', '完成人数']
			},
			xAxis: {
				type: 'category',
				data:
					chartData.timeTrend.chapters.length > 0
						? chartData.timeTrend.chapters
						: ['第1章', '第2章', '第3章', '第4章', '第5章']
			},
			yAxis: [
				{
					type: 'value',
					name: '时长(分钟)',
					position: 'left'
				},
				{
					type: 'value',
					name: '人数',
					position: 'right'
				}
			],
			series: [
				{
					name: '观看时长',
					type: 'bar',
					data:
						chartData.timeTrend.watchTime.length > 0 ? chartData.timeTrend.watchTime : [33.2, 31.5, 28.8, 25.3, 22.1],
					itemStyle: {
						color: '#3498db'
					}
				},
				{
					name: '完成人数',
					type: 'line',
					yAxisIndex: 1,
					data:
						chartData.timeTrend.completedUsers.length > 0
							? chartData.timeTrend.completedUsers
							: [2800, 2450, 2100, 1680, 1260],
					itemStyle: {
						color: '#e74c3c'
					}
				}
			]
		}
		chart.setOption(option)
	}

	// 章节完成率对比图
	const initChapterChart = () => {
		const chart = echarts.init(chapterChart.value)
		const chapters =
			chartData.chapterCompletion.chapters.length > 0
				? [...chartData.chapterCompletion.chapters].reverse()
				: ['第5章', '第4章', '第3章', '第2章', '第1章']
		const rates =
			chartData.chapterCompletion.completionRates.length > 0
				? [...chartData.chapterCompletion.completionRates].reverse()
				: [65.2, 70.8, 78.3, 87.1, 94.5]

		const option = {
			title: {
				text: '章节完成率对比',
				left: 'center'
			},
			tooltip: {
				trigger: 'axis',
				axisPointer: {
					type: 'shadow'
				}
			},
			grid: {
				left: '3%',
				right: '4%',
				bottom: '3%',
				containLabel: true
			},
			xAxis: {
				type: 'value',
				max: 100
			},
			yAxis: {
				type: 'category',
				data: chapters
			},
			series: [
				{
					name: '完成率',
					type: 'bar',
					data: rates,
					itemStyle: {
						color: function (params) {
							const value = params.value
							if (value >= 80) return '#27ae60'
							if (value >= 60) return '#f39c12'
							return '#e74c3c'
						}
					}
				}
			]
		}
		chart.setOption(option)
	}

	// 互动数据统计图
	const initInteractionChart = () => {
		const chart = echarts.init(interactionChart.value)
		const option = {
			title: {
				left: 'center'
			},
			tooltip: {
				trigger: 'axis'
			},
			legend: {
				data: ['笔记数', '讨论数', '回帖数']
			},
			xAxis: {
				type: 'category',
				data:
					chartData.interactionData.chapters.length > 0
						? chartData.interactionData.chapters
						: ['第1章', '第2章', '第3章', '第4章', '第5章']
			},
			yAxis: {
				type: 'value'
			},
			series: [
				{
					name: '笔记数',
					type: 'bar',
					data:
						chartData.interactionData.notes.length > 0
							? chartData.interactionData.notes
							: [1680, 1470, 1260, 1008, 756],
					itemStyle: {
						color: '#3498db'
					}
				},
				{
					name: '讨论数',
					type: 'bar',
					data:
						chartData.interactionData.discussions.length > 0
							? chartData.interactionData.discussions
							: [840, 735, 630, 504, 378],
					itemStyle: {
						color: '#2ecc71'
					}
				},
				{
					name: '回帖数',
					type: 'bar',
					data:
						chartData.interactionData.replies.length > 0
							? chartData.interactionData.replies
							: [2520, 2205, 1890, 1512, 1134],
					itemStyle: {
						color: '#f39c12'
					}
				}
			]
		}
		chart.setOption(option)
	}

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

	// 获取统计数据
	const fetchVideoStats = async () => {
		try {
			const countData = await videoAnalysisApi.watchUserCountProgress(filters)
			const downData = await videoAnalysisApi.teachMaterialsDownloadCount(filters)
			const jumpData = await videoAnalysisApi.jumpTimeAnalyse(filters)
			const interdata = await videoAnalysisApi.interactionDataAnalyse(filters)

			// 更新统计数据
			Object.assign(stats, {
				countData,
				downData,
				jumpData,
				interdata
			})
			console.log('新的参数呢',stats)
		} catch (error) {
			console.error('获取统计数据失败:', error)
			message.error('获取统计数据失败')
		}
	}

	// 获取学员数据
	const fetchStudentData = async () => {
		try {
			const response = await videoAnalysisApi.studyBehaviorDetailData({
				...filters,
				current: pagination.current,
				pageSize: pagination.pageSize
			})
			const data = response.records || []
			studentData.value = data.map((r) => {
				return {
					...r,
					jumpTimeContactArr: r.jumpTimeContact?.split(',')
				}
			})
			pagination.total = response.total || 0
		} catch (error) {
			console.error('获取学员数据失败:', error)
			message.error('获取学员数据失败')
		}
	}

	// 获取章节数据
	const fetchChapterData = async () => {
		try {
			const response = await videoAnalysisApi.videoDetailDataAnalysis({
				...filters,
				current: chapterPagination.current,
				pageSize: chapterPagination.pageSize
			})
			chapterData.value = response.records || []
			chapterPagination.total = response.total || 0
		} catch (error) {
			console.error('获取章节数据失败:', error)
			message.error('获取章节数据失败')
		}
	}

	// 获取图表数据
	const fetchChartData = async () => {
		try {
			const response = await videoAnalysisApi.getChartData(filters)
			const data = response || {}

			// 更新图表数据
			Object.assign(chartData, data)

			// 重新初始化图表
			nextTick(() => {
				// initCharts()
			})
		} catch (error) {
			console.error('获取图表数据失败:', error)
			message.error('获取图表数据失败')
		}
	}

	// 更新统计数据
	const updateStats = async () => {
		// console.log('时间问题',' startTime.value ',startTime.value,' endTime.value ',endTime.value)
		// if((startTime.value != '' || startTime.value != null)  && (endTime.value != '' || endTime.value != null)){
		// 	if(dayjs(endTime.value).valueOf() - dayjs(startTime.value).valueOf() > 0){
		//
		// 	}else{
		// 		message.error('结束时间比开始时间小')
		// 		return
		// 	}
		// }
		loading.value = true
		chapterLoading.value = true
		try {
			await Promise.all([fetchVideoStats(), fetchStudentData(), fetchChapterData(), fetchChartData()])
			// message.success('数据已更新！')
		} catch (error) {
			console.error('更新数据失败:', error)
		} finally {
			loading.value = false
			chapterLoading.value = false
		}

	}

	// 初始化所有数据
	const initData = async () => {
		loading.value = true
		try {
			await fetchCourseOptions()
			await updateStats()
		} catch (error) {
			console.error('初始化数据失败:', error)
		} finally {
			loading.value = false
		}
	}

	// 监听筛选条件变化
	watch(
		() => [filters.courseId,filters.endTime,filters.startTime],
		() => {
			updateStats()
		},
		{ deep: true }
	)

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

		// 监听窗口大小变化，重新调整图表
		window.addEventListener('resize', () => {
			const charts = [progressChart, timeChart, chapterChart, interactionChart]
			charts.forEach((chartRef) => {
				if (chartRef.value) {
					const chart = echarts.getInstanceByDom(chartRef.value)
					if (chart) {
						chart.resize()
					}
				}
			})
		})
	})
</script>

<style scoped>
	.video-analysis-container {
		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;
		margin-bottom: 15px;
	}

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

	.chart-container {
		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);
	}

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

	.chart {
		height: 400px;
		width: 100%;
	}

	.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;
	}

	.progress-container {
		display: flex;
		align-items: center;
		gap: 10px;
	}

	.time-point {
		display: inline-block;
		background: #e74c3c;
		color: white;
		padding: 2px 8px;
		border-radius: 12px;
		font-size: 0.8em;
		margin: 2px;
	}

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

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

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

		.charts-section {
			grid-template-columns: 1fr;
		}

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

		.header h1 {
			font-size: 2em;
		}
	}
</style>
