<template>
	<view class="workbench-stats-cards">
		<!-- 1. 学年数据统计 -->
		<view class="card">
			<view class="card-header">
				<text class="card-title">📊 学年数据统计</text>
				<view class="btn-outline" @click="handleShowReport">毕业报告</view>
			</view>
			<view class="card-body">
				<view class="year-row" v-for="(item, index) in yearStatsList" :key="index">
					<text class="year-label">{{ item.year }}</text>
					<text :class="['year-status', item.statusClass]">{{ item.statusText }}</text>
				</view>
				<view v-if="!yearStatsList.length" class="empty-tip">暂无统计数据</view>
			</view>
		</view>

		<!-- 2. 学习任务 -->
		<view class="card">
			<view class="card-header">
				<view class="header-left">
					<text class="card-title">📚 学习任务 <text class="badge" v-if="taskListTotal">{{ taskListTotal }}</text></text>
					<text class="header-subtitle">待完成的学习任务</text>
				</view>
				<text class="header-link" @click="goToPage('/pages_safetyEducationExamination/screen-knowledge-list/screen-knowledge-list?tab=2')">更多 ›</text>
			</view>
			<view class="card-body">
				<view class="list-item" v-for="(item, index) in taskList" :key="index" @click="goToPage('/pages_safetyEducationExamination/screen-study-detail/screen-study-detail?id=' + item.id)">
					<view class="list-left">
						<text class="item-title">{{ item.courseName }}</text>
						<text class="item-desc">{{ item.deptName }}下发 · <text class="text-orange">待完成</text></text>
					</view>
					<text class="list-arrow">›</text>
				</view>
				<view v-if="!taskList.length" class="empty-tip">暂无待完成任务</view>
			</view>
		</view>

		<!-- 3. 模拟考试 -->
		<view class="card">
			<view class="card-header">
				<view class="header-left">
					<text class="card-title">📝 模拟考试 <text class="badge" v-if="mockExamListTotal">{{ mockExamListTotal }}</text></text>
					<text class="header-subtitle">待完成的模拟练习</text>
				</view>
				<text class="header-link" @click="goToPage('/pages_safetyEducationExamination/screen-exam-list/screen-exam-list?tab=1')">更多 ›</text>
			</view>
			<view class="card-body">
				<view class="list-item" v-for="(item, index) in mockExamList" :key="index" @click="goToPage('/pages_safetyEducationExamination/screen-mock-detail/screen-mock-detail?id=' + item.id)">
					<view class="list-left">
						<text class="item-title">{{ item.examName }}</text>
						<text class="item-desc">最高成绩: <text class="text-orange">{{ item.maxScore?item.maxScore:0 }} 分</text> · 及格: {{ item.passScore }}分</text>
					</view>
					<text class="list-arrow">›</text>
				</view>
				<view v-if="!mockExamList.length" class="empty-tip">暂无模拟考试</view>
			</view>
		</view>

		<!-- 4. 在线考试 -->
		<view class="card">
			<view class="card-header">
				<view class="header-left">
					<text class="card-title">🎓 在线考试</text>
					<text class="header-subtitle">待完成的在线考试</text>
				</view>
				<text class="header-link" @click="goToPage('/pages_safetyEducationExamination/screen-exam-list/screen-exam-list?tab=0')">更多 ›</text>
			</view>
			<view class="card-body">
				<view 
					class="exam-task-card" 
					:class="{ 'active-exam': item.isActive }" 
					v-for="(item, index) in onlineExamList" 
					:key="index"
					@click="goToPage('/pages_safetyEducationExamination/screen-exam-detail/screen-exam-detail?id=' + item.id)"
				>
					<view class="exam-header-row">
						<view class="exam-tag-row">
							<text class="tag" :class="item.isActive ? 'tag-blue' : 'tag-orange'">{{ item.examTypeName }}</text>
							<view class="dot dot-orange" v-if="item.isActive"></view>
							<text class="text-orange text-xs" v-if="item.isActive">进行中</text>
						</view>
						<text class="list-arrow" :class="item.isActive ? 'text-blue' : ''">›</text>
					</view>
					<text class="exam-title">{{ item.title }}</text>
				</view>
				<view v-if="!onlineExamList[0]" class="empty-tip">暂无在线考试</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { 
		examElLabEduRelationAcademicYearProgress, 
		examUserCourseLearningList, 
		examUserExamMockList, 
		examUserExamStudyTaskList 
	} from '@/pages_safetyEducationExamination/api/index.js'

	export default {
		name: 'WorkbenchStatsCards',
		data() {
			return {
				yearStatsList: [],
				taskList: [],
				taskListTotal:0,
				mockExamList: [],
				mockExamListTotal: 0,
				onlineExamList: [],
			}
		},
		created() {
			this.fetchAllData();
		},
		methods: {
			async fetchAllData() {
				// 并行请求所有数据，提升加载速度
				await Promise.all([
					this.examElLabEduRelationAcademicYearProgress(),
					this.examUserCourseLearningList(),
					this.examUserExamMockList(),
					this.examUserExamStudyTaskList(),
				]);
			},
			//年度数据
			async examElLabEduRelationAcademicYearProgress() {
				try {
					const { data } = await examElLabEduRelationAcademicYearProgress();
					if (data.code === 200) {
						this.yearStatsList = (data.data || []).map(item => ({
							year: item.academicYear,
							statusText: item.statusCode == '0' ? `未开始` : (item.statusCode == '2' ? `通过丨`+item.score : (item.statusCode == '1' ? `进行中` : '未通过')),
							statusClass: item.statusCode == '2' ? 'year-status-pass' : (item.statusCode == '1' ? 'year-status-going' : 'year-status-text')
						}));
					}
				} catch (e) { console.error('获取学年统计失败', e); }
			},
			//学习任务
			async examUserCourseLearningList() {
				try {
					const { data } = await examUserCourseLearningList({page:1,pageSize:2,learnStatus:'01'});
					if (data.code === 200) {
						this.taskList = data.data.records || [];
						this.taskListTotal = data.data.total || 0;
					}
				} catch (e) { console.error('获取学习任务失败', e); }
			},
			//模拟考试
			async examUserExamMockList() {
				try {
					const { data } = await examUserExamMockList({page:1,pageSize:1});
					if (data.code === 200){
						this.mockExamList = data.data.records || [];
						this.mockExamListTotal = data.data.total || 0;
					}
				} catch (e) { console.error('获取模拟考试失败', e); }
			},
			//在线考试(查询1条特殊考试1条普通考试并组合数据)
			async examUserExamStudyTaskList() {
				try {
        const [res1, res2] = await Promise.all([
					examUserExamStudyTaskList({ page: 1, pageSize: 1, examStatus: 2, isSpecialExam: true }),
					examUserExamStudyTaskList({ page: 1, pageSize: 1, examStatus: 2, isSpecialExam: false })
        ]);
        let list = [];
        if (res1.data.code === 200) {
					list = [...list, ...(res1.data.data.records || [])];
        }
        if (res2.data.code === 200) {
					list = [...list, ...(res2.data.data.records || [])];
        }
				console.log('res1',res1)
				console.log('res2',res2)
				console.log('list',list)
				this.$set(this,'onlineExamList',list);
				} catch (e) { console.error('获取在线考试失败', e); }
			},

			// 根据考试类型动态生成底部信息字段
			buildExamFields(item) {
				const fields = [];
				if (item.requiredHours !== undefined) {
					fields.push({
						label: '学时要求',
						value: `${item.completedHours || 0}/${item.requiredHours} 学时`,
						valueClass: item.hoursMet ? '' : 'text-orange',
						extra: item.hoursMet ? '' : '未达标'
					});
				}
				if (item.taskStatus) {
					fields.push({ label: '学习任务', value: item.taskStatus, valueClass: item.taskStatus === '已完成' ? '' : 'text-orange' });
				}
				if (item.mockStatus) {
					fields.push({ label: '模拟考试', value: item.mockStatus, valueClass: item.mockStatus === '已完成' ? '' : 'text-orange' });
				}
				if (item.examConfirmStatus) {
					fields.push({ label: '考试状态', value: item.examConfirmStatus, valueClass: 'text-gray' });
				}
				return fields;
			},

			goToPage(url) {
				uni.navigateTo({ url });
			},
			
			handleShowReport() {
				// 触发事件让父组件处理弹窗，或直接在组件内处理
				uni.navigateTo({ url: '/pages_safetyEducationExamination/graduation-report/graduation-report' });
			},
		}
	}
</script>

<style lang="stylus" scoped>
	.workbench-stats-cards {
		padding:0 32rpx;
		.card {
			background: #fff;
			border-radius: 24rpx;
			overflow: hidden;
			margin-bottom: 24rpx;
			box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.03);
			border:1px solid #dde3ed;
		}

		.card-header {
			background: #f4f6fa;
			padding: 20rpx 28rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
		}

		.header-left {
			display: flex;
			align-items: center;
			gap: 12rpx;
		}

		.card-title {
			font-size: 28rpx;
			font-weight: 700;
			color: #333;
		}

		.header-subtitle {
			font-size: 22rpx;
			color: #8896a7;
		}

		.header-link {
			font-size: 24rpx;
			color: #1857d4;
		}

		.btn-outline {
			font-size: 22rpx;
			color: #1857d4;
			border: 1px solid rgba(24, 87, 212, 0.3);
			padding: 6rpx 16rpx;
			border-radius: 8rpx;
		}

		.badge {
			background: #ff4d4f;
			color: #fff;
			font-size: 20rpx;
			padding: 2rpx 10rpx;
			border-radius: 20rpx;
			margin-left: 8rpx;
			font-weight: 400;
		}

		.card-body {
			padding: 16rpx 28rpx 24rpx;
		}

		// 学年统计样式
		.year-row {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 12rpx 0;
			border-bottom: 1px solid #f4f6fa;
			&:last-child { border-bottom: none; }
		}
		.year-label { font-size: 26rpx; color: #333; font-weight: 500; }
		.year-status { font-size: 24rpx; font-weight: 500; }
		.year-status-pass { color: #0d8f6f; }
		.year-status-going { color: #1857d4; }
		.year-status-text { color: #333; }

		// 列表项样式
		.list-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 16rpx 0;
			border-bottom: 1px solid #f4f6fa;
			&:last-child { border-bottom: none; }
		}
		.item-title { font-size: 28rpx; font-weight: 500; color: #333; margin-bottom: 8rpx; display: block; }
		.item-desc { font-size: 22rpx; color: #8896a7; }
		.list-arrow { font-size: 32rpx; color: #ccc; }

		// 在线考试卡片样式
		.exam-task-card {
			background: #f4f6fa;
			border-radius: 16rpx;
			padding: 20rpx;
			margin-bottom: 16rpx;
			&:last-child { margin-bottom: 0; }
		}
		.active-exam {
			background: #eef3fd;
			border: 1px solid rgba(24, 87, 212, 0.15);
		}
		.exam-header-row {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 12rpx;
		}
		.exam-tag-row { display: flex; align-items: center; gap: 8rpx; }
		.exam-title { font-size: 28rpx; font-weight: 500; color: #333; margin-bottom: 16rpx; display: block; }
		
		// 通用工具类
		.tag {
			display: inline-flex;
			padding: 4rpx 12rpx;
			border-radius: 8rpx;
			font-size: 22rpx;
			font-weight: 500;
		}
		.tag-blue { background: #eef3fd; color: #1857d4; }
		.tag-orange { background: #fef6ec; color: #e67e22; }
		.dot { width: 12rpx; height: 12rpx; border-radius: 50%; }
		.dot-orange { background: #e67e22; }
		.text-xs { font-size: 22rpx; }
		.text-orange { color: #e67e22; }
		.text-blue { color: #1857d4; }
		.text-gray { color: #8896a7; }
		.empty-tip { text-align: center; padding: 30rpx 0; color: #ccc; font-size: 24rpx; }
	}
</style>