<!--学员体测数据页面-->
<template>
	<view class="main_box">
		<!-- 自定义导航栏 -->
		<view class="navbar_section">
			<view class="navbar_content">
        <view class="navbar_back" @click="goBack">
          <text class="back_icon">‹</text>
        </view>
				<view class="navbar_title">体测数据</view>
				<view class="navbar_action">
					<view class="share_button" @click="sharePhysicalTest" v-if="physicalTestList.length > 0">
						<image src="/static/icon-img/share.png" class="share_icon"></image>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 学员基本信息 -->
		<view class="student_basic_section" v-if="studentInfo">
			<view class="student_name">{{ studentInfo.name }}</view>
			<view class="student_meta">
				<text class="meta_item">{{ studentInfo.gender_text }}</text>
				<text class="meta_item">{{ studentInfo.age }}岁</text>
			</view>
		</view>
		
		<!-- 数据统计卡片 -->
		<view class="stats_section">
			<view class="stat_card">
				<view class="stat_number">{{ physicalTestList.length }}</view>
				<view class="stat_label">测试次数</view>
			</view>
			<view class="stat_card" v-if="latestTest">
				<view class="stat_number">{{ latestTest.height }}cm</view>
				<view class="stat_label">最新身高</view>
			</view>
			<view class="stat_card" v-if="latestTest">
				<view class="stat_number">{{ latestTest.weight }}kg</view>
				<view class="stat_label">最新体重</view>
			</view>
		</view>
		
		<!-- 体测记录列表 -->
		<view class="test_list_section">
			<view v-if="loading" class="loading_section">
				<view class="loading_text">加载中...</view>
			</view>
			
			<view v-else-if="physicalTestList.length === 0" class="empty_section">
				<view class="empty_icon">📊</view>
				<view class="empty_text">暂无体测数据</view>
				<view class="empty_hint">完成体测后数据会在这里显示</view>
			</view>
			
			<view v-else class="test_list">
				<view 
					v-for="test in physicalTestList" 
					:key="test.id"
					class="test_item"
				>
					<view class="test_header">
						<view class="test_date">{{ formatDate(test.created_at) }}</view>
						<view class="test_status">体测记录</view>
					</view>
					
					<view class="test_content">
						<view class="measurement_row">
							<view class="measurement_item">
								<view class="item_label">身高</view>
								<view class="item_value">{{ test.height || '-' }}cm</view>
							</view>
							<view class="measurement_item">
								<view class="item_label">体重</view>
								<view class="item_value">{{ test.weight || '-' }}kg</view>
							</view>
						</view>
						
						<!-- PDF报告列表 -->
						<view class="pdf_reports" v-if="test.physical_test_report">
							<view class="reports_title">体测报告</view>
							<view class="reports_list">
								<view 
									v-for="(pdfUrl, index) in getPdfList(test.physical_test_report)" 
									:key="index"
									class="pdf_item"
									@click="previewPdf(pdfUrl, test.id, index)"
								>
									<view class="pdf_icon">
										<image src="/static/icon-img/pdf.png" class="icon_image"></image>
									</view>
									<view class="pdf_info">
										<view class="pdf_name">体测报告{{ index + 1 }}</view>
										<view class="pdf_action">点击预览</view>
									</view>
									<view class="pdf_arrow">
										<image src="/static/icon-img/arrow-right.png" class="arrow_icon"></image>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 加载更多 -->
		<view class="load_more_section" v-if="!loading && hasMore">
			<button class="load_more_button" @click="loadMoreTests" :disabled="loadingMore">
				{{ loadingMore ? '加载中...' : '加载更多' }}
			</button>
		</view>
		
		<!-- PDF预览弹窗 -->
		<view class="pdf_preview_popup" v-if="showPdfPreview" @click="closePdfPreview">
			<view class="preview_content" @click.stop>
				<view class="preview_header">
					<view class="preview_title">体测报告预览</view>
					<view class="preview_close" @click="closePdfPreview">×</view>
				</view>
				<view class="preview_body">
					<view v-if="pdfPreviewLoading" class="preview_loading">
						<view class="loading_text">加载中...</view>
					</view>
					<view v-else-if="pdfImageUrl" class="preview_image_container">
						<image 
							:src="pdfImageUrl" 
							class="preview_image"
							mode="widthFix"
							@error="onImageError"
						></image>
					</view>
					<view v-else class="preview_error">
						<view class="error_text">预览失败</view>
						<button class="retry_button" @click="retryPreview">重试</button>
					</view>
				</view>
				<view class="preview_footer">
					<button class="share_pdf_button" @click="sharePdfImage" :disabled="!pdfImageUrl">
						分享报告
					</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import apiRoute from '@/api/member.js'
	
	export default {
		data() {
			return {
				studentId: 0,
				studentInfo: {},
				physicalTestList: [],
				loading: false,
				loadingMore: false,
				hasMore: true,
				currentPage: 1,
				showPdfPreview: false,
				pdfPreviewLoading: false,
				pdfImageUrl: '',
				currentPdfUrl: '',
				currentTestId: 0,
				currentPdfIndex: 0
			}
		},
		
		computed: {
			latestTest() {
				if (this.physicalTestList.length === 0) return null
				return this.physicalTestList[0]
			}
		},
		
		onLoad(options) {
			this.studentId = parseInt(options.student_id) || 0
			if (this.studentId) {
				this.initPage()
			} else {
				uni.showToast({
					title: '参数错误',
					icon: 'none'
				})
			}
		},
		
		methods: {
			goBack() {
				uni.navigateBack()
			},
			
			async initPage() {
				await this.loadStudentInfo()
				await this.loadPhysicalTests()
			},
			
			async loadStudentInfo() {
				try {
					// 调用真实API获取学员信息
					const response = await apiRoute.getStudentSummary(this.studentId)
					if (response.code === 1) {
						this.studentInfo = response.data
					} else {
						console.error('获取学员信息失败:', response)
					}
				} catch (error) {
					console.error('获取学员信息失败:', error)
				}
			},
			
			async loadPhysicalTests() {
				this.loading = true
				try {
					console.log('加载体测数据:', this.studentId)
					
					// 调用真实API获取体测数据
					const response = await apiRoute.getPhysicalTestList({
						student_id: this.studentId,
						page: this.currentPage,
						limit: 10
					})
					
					if (response.code === 1) {
						const newList = response.data.list || []
						if (this.currentPage === 1) {
							this.physicalTestList = newList
						} else {
							this.physicalTestList = [...this.physicalTestList, ...newList]
						}
						
						this.hasMore = response.data.has_more || false
						console.log('体测数据加载成功:', this.physicalTestList)
					} else {
						uni.showToast({
							title: response.msg || '获取体测数据失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('获取体测数据失败:', error)
					uni.showToast({
						title: '获取体测数据失败',
						icon: 'none'
					})
				} finally {
					this.loading = false
					this.loadingMore = false
				}
			},
			
			async loadMoreTests() {
				if (this.loadingMore || !this.hasMore) return
				
				this.loadingMore = true
				this.currentPage++
				await this.loadPhysicalTests()
			},
			
			getPdfList(pdfReportString) {
				if (!pdfReportString || pdfReportString.trim() === '') {
					return []
				}
				
				// 按逗号分割PDF URL列表，并过滤空值
				return pdfReportString.split(',').filter(url => url.trim() !== '')
			},
			
			async previewPdf(pdfUrl, testId, pdfIndex) {
				console.log('预览PDF:', pdfUrl)
				
				this.currentPdfUrl = pdfUrl
				this.currentTestId = testId
				this.currentPdfIndex = pdfIndex
				this.showPdfPreview = true
				this.pdfPreviewLoading = true
				this.pdfImageUrl = ''
				
				try {
					// 调用后端API将PDF转换为图片
					const response = await apiRoute.generateShareImage({
						pdf_url: pdfUrl,
						test_id: testId,
						pdf_index: pdfIndex
					})
					
					if (response.code === 1) {
						this.pdfImageUrl = response.data.image_url
					} else {
						throw new Error(response.msg || 'PDF转换失败')
					}
				} catch (error) {
					console.error('PDF预览失败:', error)
					uni.showToast({
						title: error.message || 'PDF预览失败',
						icon: 'none'
					})
				} finally {
					this.pdfPreviewLoading = false
				}
			},
			
			closePdfPreview() {
				this.showPdfPreview = false
				this.pdfImageUrl = ''
				this.currentPdfUrl = ''
			},
			
			retryPreview() {
				this.previewPdf(this.currentPdfUrl, this.currentTestId, this.currentPdfIndex)
			},
			
			onImageError() {
				console.error('图片加载失败')
				uni.showToast({
					title: '图片加载失败',
					icon: 'none'
				})
			},
			
			async sharePdfImage() {
				if (!this.pdfImageUrl) {
					uni.showToast({
						title: '没有可分享的内容',
						icon: 'none'
					})
					return
				}
				
				try {
					uni.showActionSheet({
						itemList: ['保存到相册', '分享给朋友'],
						success: async (res) => {
							if (res.tapIndex === 0) {
								// 保存到相册
								try {
									await uni.saveImageToPhotosAlbum({
										filePath: this.pdfImageUrl
									})
									uni.showToast({
										title: '已保存到相册',
										icon: 'success'
									})
								} catch (error) {
									console.error('保存图片失败:', error)
									uni.showToast({
										title: '保存失败',
										icon: 'none'
									})
								}
							} else if (res.tapIndex === 1) {
								// 分享功能
								uni.showToast({
									title: '分享功能开发中',
									icon: 'none'
								})
							}
						}
					})
				} catch (error) {
					console.error('分享操作失败:', error)
				}
			},
			
			formatDate(dateString) {
				if (!dateString) return '-'
				
				const date = new Date(dateString)
				const year = date.getFullYear()
				const month = String(date.getMonth() + 1).padStart(2, '0')
				const day = String(date.getDate()).padStart(2, '0')
				const hours = String(date.getHours()).padStart(2, '0')
				const minutes = String(date.getMinutes()).padStart(2, '0')
				
				return `${year}-${month}-${day} ${hours}:${minutes}`
			},
			
			async sharePhysicalTest() {
				try {
					uni.showLoading({
						title: '生成分享图片...'
					})
					
					// 调用API生成分享图片
					const response = await apiRoute.generateShareImage({
						student_id: this.studentId,
						type: 'physical_test'
					})
					
					if (response.code === 1) {
						uni.hideLoading()
						uni.showActionSheet({
							itemList: ['保存到相册', '分享给朋友'],
							success: async (res) => {
								if (res.tapIndex === 0) {
									try {
										await uni.saveImageToPhotosAlbum({
											filePath: response.data.image_url
										})
										uni.showToast({
											title: '已保存到相册',
											icon: 'success'
										})
									} catch (error) {
										uni.showToast({
											title: '保存失败',
											icon: 'none'
										})
									}
								} else if (res.tapIndex === 1) {
									uni.showToast({
										title: '分享功能开发中',
										icon: 'none'
									})
								}
							}
						})
					} else {
						throw new Error(response.msg || '生成分享图片失败')
					}
				} catch (error) {
					console.error('分享失败:', error)
					uni.hideLoading()
					uni.showToast({
						title: error.message || '分享失败',
						icon: 'none'
					})
				}
			}
		}
	}
</script>

<style lang="less" scoped>
.main_box {
	background: #f8f9fa;
	min-height: 100vh;
}

// 自定义导航栏
.navbar_section {
	background: linear-gradient(135deg, #29D3B4 0%, #1BA297 100%);
	padding: 40rpx 32rpx 32rpx;
	
	// 小程序端适配状态栏
	// #ifdef MP-WEIXIN
	padding-top: 80rpx;
	// #endif
  .navbar_back {
    width: 60rpx;

    .back_icon {
      color: #fff;
      font-size: 40rpx;
      font-weight: 600;
    }
  }
	.navbar_content {
		display: flex;
		align-items: center;
		justify-content: space-between;
		
		.back_button {
			width: 40rpx;
			height: 40rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			
			.back_icon {
				width: 24rpx;
				height: 24rpx;
			}
		}
		
		.navbar_title {
			color: #fff;
			font-size: 36rpx;
			font-weight: 600;
		}
		
		.navbar_action {
			width: 40rpx;
			height: 40rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			
			.share_button {
				background: rgba(255, 255, 255, 0.2);
				padding: 12rpx;
				border-radius: 50%;
				
				.share_icon {
					width: 20rpx;
					height: 20rpx;
				}
			}
		}
	}
}

// 学员基本信息
.student_basic_section {
	background: #fff;
	padding: 24rpx 32rpx;
	border-bottom: 1px solid #f0f0f0;
	
	.student_name {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
		margin-bottom: 12rpx;
	}
	
	.student_meta {
		display: flex;
		gap: 16rpx;
		
		.meta_item {
			font-size: 24rpx;
			color: #666;
			background: #f0f0f0;
			padding: 6rpx 12rpx;
			border-radius: 12rpx;
		}
	}
}

// 统计卡片
.stats_section {
	display: flex;
	background: #fff;
	margin: 20rpx;
	border-radius: 16rpx;
	padding: 32rpx 24rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
	
	.stat_card {
		flex: 1;
		text-align: center;
		
		.stat_number {
			font-size: 36rpx;
			font-weight: 600;
			color: #29D3B4;
			margin-bottom: 8rpx;
		}
		
		.stat_label {
			font-size: 24rpx;
			color: #666;
		}
	}
}

// 体测记录列表
.test_list_section {
	margin: 0 20rpx;
	
	.loading_section, .empty_section {
		background: #fff;
		border-radius: 16rpx;
		padding: 80rpx 32rpx;
		text-align: center;
		
		.loading_text, .empty_text {
			font-size: 28rpx;
			color: #666;
			margin-bottom: 12rpx;
		}
		
		.empty_icon {
			font-size: 80rpx;
			margin-bottom: 24rpx;
		}
		
		.empty_hint {
			font-size: 24rpx;
			color: #999;
		}
	}
	
	.test_list {
		.test_item {
			background: #fff;
			border-radius: 16rpx;
			padding: 32rpx;
			margin-bottom: 20rpx;
			box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
			
			.test_header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 24rpx;
				
				.test_date {
					font-size: 28rpx;
					color: #333;
					font-weight: 600;
				}
				
				.test_status {
					font-size: 24rpx;
					color: #29D3B4;
					background: rgba(41, 211, 180, 0.1);
					padding: 6rpx 16rpx;
					border-radius: 12rpx;
				}
			}
			
			.test_content {
				.measurement_row {
					display: flex;
					gap: 32rpx;
					margin-bottom: 24rpx;
					
					.measurement_item {
						flex: 1;
						text-align: center;
						background: #f8f9fa;
						padding: 24rpx;
						border-radius: 12rpx;
						
						.item_label {
							font-size: 24rpx;
							color: #666;
							margin-bottom: 8rpx;
						}
						
						.item_value {
							font-size: 32rpx;
							color: #333;
							font-weight: 600;
						}
					}
				}
				
				.pdf_reports {
					.reports_title {
						font-size: 26rpx;
						color: #333;
						font-weight: 600;
						margin-bottom: 16rpx;
					}
					
					.reports_list {
						.pdf_item {
							display: flex;
							align-items: center;
							gap: 20rpx;
							padding: 20rpx;
							background: #f8f9fa;
							border-radius: 12rpx;
							margin-bottom: 12rpx;
							
							&:last-child {
								margin-bottom: 0;
							}
							
							.pdf_icon {
								width: 60rpx;
								height: 60rpx;
								background: rgba(231, 76, 60, 0.1);
								border-radius: 12rpx;
								display: flex;
								align-items: center;
								justify-content: center;
								
								.icon_image {
									width: 32rpx;
									height: 32rpx;
								}
							}
							
							.pdf_info {
								flex: 1;
								
								.pdf_name {
									font-size: 26rpx;
									color: #333;
									font-weight: 500;
									margin-bottom: 4rpx;
								}
								
								.pdf_action {
									font-size: 22rpx;
									color: #666;
								}
							}
							
							.pdf_arrow {
								.arrow_icon {
									width: 16rpx;
									height: 16rpx;
									opacity: 0.6;
								}
							}
						}
					}
				}
			}
		}
	}
}

// 加载更多
.load_more_section {
	padding: 40rpx 20rpx 80rpx;
	
	.load_more_button {
		width: 100%;
		background: #f8f9fa;
		color: #666;
		border: 1px solid #e9ecef;
		border-radius: 16rpx;
		padding: 24rpx 0;
		font-size: 28rpx;
		
		&:disabled {
			opacity: 0.6;
		}
	}
}

// PDF预览弹窗
.pdf_preview_popup {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	display: flex;
	justify-content: center;
	align-items: center;
	z-index: 1000;
	
	.preview_content {
		background: #fff;
		border-radius: 16rpx;
		width: 90%;
		max-height: 80vh;
		overflow: hidden;
		
		.preview_header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 32rpx;
			border-bottom: 1px solid #f0f0f0;
			
			.preview_title {
				font-size: 32rpx;
				font-weight: 600;
				color: #333;
			}
			
			.preview_close {
				font-size: 48rpx;
				color: #999;
				font-weight: 300;
			}
		}
		
		.preview_body {
			max-height: 60vh;
			overflow-y: auto;
			
			.preview_loading, .preview_error {
				padding: 80rpx 32rpx;
				text-align: center;
				
				.loading_text, .error_text {
					font-size: 28rpx;
					color: #666;
					margin-bottom: 24rpx;
				}
				
				.retry_button {
					background: #29D3B4;
					color: #fff;
					border: none;
					border-radius: 12rpx;
					padding: 16rpx 32rpx;
					font-size: 26rpx;
				}
			}
			
			.preview_image_container {
				padding: 20rpx;
				
				.preview_image {
					width: 100%;
					border-radius: 12rpx;
				}
			}
		}
		
		.preview_footer {
			padding: 32rpx;
			border-top: 1px solid #f0f0f0;
			
			.share_pdf_button {
				width: 100%;
				background: linear-gradient(135deg, #29D3B4 0%, #1BA297 100%);
				color: #fff;
				border: none;
				border-radius: 16rpx;
				padding: 24rpx 0;
				font-size: 28rpx;
				font-weight: 600;
				
				&:disabled {
					opacity: 0.6;
				}
			}
		}
	}
}
</style>