<!--学员合同管理页面-->
<template>
	<view class="main_box">
		<!-- 自定义导航栏 -->
		<view class="navbar_section">
			<view class="navbar_back" @click="goBack">
				<text class="back_icon">‹</text>
			</view>
			<view class="navbar_title">合同管理</view>
			<view class="navbar_action"></view>
		</view>
		
		<!-- 学员信息 -->
		<view class="student_info_section" v-if="studentInfo">
			<view class="student_name">{{ studentInfo.name }}</view>
			<view class="contract_stats">
				<text class="stat_item">有效合同：{{ contractStats.active_contracts }}个</text>
				<text class="stat_item">剩余课时：{{ contractStats.remaining_hours }}节</text>
			</view>
		</view>
		
		<!-- 合同状态筛选 -->
		<view class="filter_section">
			<view class="filter_tabs">
				<view 
					v-for="tab in statusTabs" 
					:key="tab.value"
					:class="['filter_tab', activeStatus === tab.value ? 'active' : '']"
					@click="changeStatus(tab.value)"
				>
					{{ tab.text }}
					<view class="tab_badge" v-if="tab.count > 0">{{ tab.count }}</view>
				</view>
			</view>
		</view>
		
		<!-- 合同列表 -->
		<view class="contracts_section">
			<view v-if="loading" class="loading_section">
				<view class="loading_text">加载中...</view>
			</view>
			
			<view v-else-if="filteredContracts.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="contracts_list">
				<view 
					v-for="contract in filteredContracts" 
					:key="contract.id"
					class="contract_item"
					@click="viewContractDetail(contract)"
				>
					<view class="contract_header">
						<view class="contract_info">
							<view class="contract_name">{{ contract.contract_name }}</view>
							<view class="contract_number">合同类型：{{ contract.contract_type }}</view>
						</view>
						<view class="contract_status" :class="contract.status">
							{{ getStatusText(contract.status) }}
						</view>
					</view>
					
					<view class="contract_content">
						<view class="contract_details">
							<view class="detail_row">
								<text class="detail_label">课程类型：</text>
								<text class="detail_value">{{ contract.course_type }}</text>
							</view>
							<view class="detail_row">
								<text class="detail_label">总课时：</text>
								<text class="detail_value">{{ contract.total_hours }}节</text>
							</view>
							<view class="detail_row">
								<text class="detail_label">剩余课时：</text>
								<text class="detail_value remaining">{{ contract.remaining_hours }}节</text>
							</view>
							<view class="detail_row">
								<text class="detail_label">合同金额：</text>
								<text class="detail_value amount">¥{{ contract.total_amount }}</text>
							</view>
						</view>
						
						<view class="contract_dates">
							<view class="date_row">
								<text class="date_label">签署日期：</text>
								<text class="date_value">{{ formatDate(contract.sign_date) }}</text>
							</view>
							<view class="date_row">
								<text class="date_label">创建日期：</text>
								<text class="date_value">{{ formatDate(contract.create_date) }}</text>
							</view>
						</view>
					</view>
					
					<view class="contract_progress" v-if="contract.status === 3">
						<view class="progress_info">
							<text class="progress_text">课时使用进度</text>
							<text class="progress_percent">{{ getProgressPercent(contract) }}%</text>
						</view>
						<view class="progress_bar">
							<view class="progress_fill" :style="{ width: getProgressPercent(contract) + '%' }"></view>
						</view>
					</view>
					
					<view class="contract_actions" @click.stop>
						<view 
							v-if="contract.status === 3"
							class="action_button secondary_button"
							@click="handleViewDetail(index, $event)"
						>
							查看详情
						</view>
						
						<view 
							v-if="contract.status === 3 && contract.can_renew"
							class="action_button primary_button"
							@click="handleRenewContract(index, $event)"
						>
							续约
						</view>
						
						<view 
							v-if="contract.status === 1"
							class="action_button sign_button"
							@click="handleSignContract(index, $event)"
						>
							签署合同
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 加载更多 -->
		<view class="load_more_section" v-if="!loading && hasMore">
			<fui-button 
				background="transparent" 
				color="#666"
				@click="loadMoreContracts"
				:loading="loadingMore"
			>
				{{ loadingMore ? '加载中...' : '加载更多' }}
			</fui-button>
		</view>
		
		<!-- 合同详情弹窗 -->
		<view class="contract_popup" v-if="showContractPopup" @click="closeContractPopup">
			<view class="popup_content" @click.stop>
				<view class="popup_header">
					<view class="popup_title">合同详情</view>
					<view class="popup_close" @click="closeContractPopup">×</view>
				</view>
				
				<view class="popup_contract_detail" v-if="selectedContract">
					<view class="detail_section">
						<view class="section_title">基本信息</view>
						<view class="info_grid">
							<view class="info_row">
								<text class="info_label">合同名称：</text>
								<text class="info_value">{{ selectedContract.contract_name }}</text>
							</view>
							<view class="info_row">
								<text class="info_label">合同编号：</text>
								<text class="info_value">{{ selectedContract.contract_no }}</text>
							</view>
							<view class="info_row">
								<text class="info_label">课程类型：</text>
								<text class="info_value">{{ selectedContract.course_type }}</text>
							</view>
							<view class="info_row">
								<text class="info_label">总课时：</text>
								<text class="info_value">{{ selectedContract.total_hours }}节</text>
							</view>
							<view class="info_row">
								<text class="info_label">剩余课时：</text>
								<text class="info_value">{{ selectedContract.remaining_hours }}节</text>
							</view>
							<view class="info_row">
								<text class="info_label">合同金额：</text>
								<text class="info_value">¥{{ selectedContract.total_amount }}</text>
							</view>
						</view>
					</view>
					
					<view class="detail_section">
						<view class="section_title">时间信息</view>
						<view class="info_grid">
							<view class="info_row">
								<text class="info_label">签署日期：</text>
								<text class="info_value">{{ formatFullDate(selectedContract.sign_date) }}</text>
							</view>
							<view class="info_row">
								<text class="info_label">生效日期：</text>
								<text class="info_value">{{ formatFullDate(selectedContract.start_date) }}</text>
							</view>
							<view class="info_row">
								<text class="info_label">到期日期：</text>
								<text class="info_value">{{ formatFullDate(selectedContract.end_date) }}</text>
							</view>
						</view>
					</view>
					
					<view class="detail_section" v-if="selectedContract.terms">
						<view class="section_title">合同条款</view>
						<view class="contract_terms">{{ selectedContract.terms }}</view>
					</view>
				</view>
				
				<view class="popup_actions">
					<fui-button 
						v-if="selectedContract && selectedContract.contract_file_url"
						background="#3498db" 
						@click="downloadContract"
					>
						下载合同
					</fui-button>
					
					<fui-button 
						background="#f8f9fa" 
						color="#666"
						@click="closeContractPopup"
					>
						关闭
					</fui-button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import apiRoute from '@/api/apiRoute.js'
	
	export default {
		data() {
			return {
				studentId: 0,
				studentInfo: {},
				contractsList: [],
				filteredContracts: [],
				contractStats: {},
				loading: false,
				loadingMore: false,
				hasMore: true,
				currentPage: 1,
				activeStatus: '',
				showContractPopup: false,
				selectedContract: null,
				statusTabs: [
					{ value: '', text: '全部', count: 0 },
					{ value: '3', text: '生效中', count: 0 },
					{ value: '1', text: '待签署', count: 0 },
					{ value: '2', text: '已签署', count: 0 },
					{ value: '4', text: '已失效', count: 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.loadContracts()
				this.updateStatusCounts()
			},
			
			async loadStudentInfo() {
				try {
					// 从数据库获取学员基本信息
					const response = await this.getStudentBasicInfo()
					if (response && response.code === 1) {
						this.studentInfo = response.data
					} else {
						// 如果获取失败，使用默认信息
						this.studentInfo = {
							id: this.studentId,
							name: `学员${this.studentId}`
						}
					}
				} catch (error) {
					console.error('获取学员信息失败:', error)
					// 使用默认信息
					this.studentInfo = {
						id: this.studentId,
						name: `学员${this.studentId}`
					}
				}
			},
			
			async getStudentBasicInfo() {
				try {
					// 调用真实的API获取学员信息
					const response = await apiRoute.getStudentBasicInfo({
						student_id: this.studentId
					})
					return response
				} catch (error) {
					console.error('获取学员基本信息失败:', error)
					return null
				}
			},
			
			async loadContracts() {
				this.loading = true
				try {
					console.log('加载合同列表:', this.studentId)
					
					// 调用真实API
					const response = await apiRoute.getStudentContracts({
						student_id: this.studentId,
						status: this.activeStatus,
						page: this.currentPage,
						limit: 10
					})
					
					if (response.code === 1) {
						const newList = response.data.list || []
						if (this.currentPage === 1) {
							this.contractsList = newList
						} else {
							this.contractsList = [...this.contractsList, ...newList]
						}
						
						this.hasMore = response.data.has_more || false
						this.contractStats = response.data.stats || {}
						this.applyStatusFilter()
						console.log('合同数据加载成功:', this.contractsList)
					} 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 loadMoreContracts() {
				if (this.loadingMore || !this.hasMore) return
				
				this.loadingMore = true
				this.currentPage++
				await this.loadContracts()
			},
			
			changeStatus(status) {
				this.activeStatus = status
				this.currentPage = 1
				this.loadContracts()
			},
			
			applyStatusFilter() {
				// 不需要过滤,API已经返回过滤后的数据
				this.filteredContracts = [...this.contractsList]
			},
			
			updateStatusCounts() {
				// 从统计数据更新状态计数
				if (this.contractStats) {
					this.statusTabs.forEach(tab => {
						switch (tab.value) {
							case '':
								tab.count = this.contractStats.total_contracts || 0
								break
							case '1':
								tab.count = this.contractStats.pending_contracts || 0
								break
							case '2':
								tab.count = this.contractStats.signed_contracts || 0
								break
							case '3':
								tab.count = this.contractStats.active_contracts || 0
								break
							case '4':
								tab.count = this.contractStats.expired_contracts || 0
								break
						}
					})
				}
			},
			
			getStatusText(status) {
				const statusMap = {
					1: '未签署',
					2: '已签署',
					3: '已生效',
					4: '已失效'
				}
				return statusMap[status] || '未知状态'
			},
			
			getProgressPercent(contract) {
				if (contract.total_hours === 0) return 0
				return contract.progress_percent || Math.round((contract.used_hours / contract.total_hours) * 100)
			},
			
			formatDate(dateString) {
				if (!dateString) return '未设置'
				const date = new Date(dateString)
				const month = String(date.getMonth() + 1).padStart(2, '0')
				const day = String(date.getDate()).padStart(2, '0')
				return `${month}-${day}`
			},
			
			formatFullDate(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')
				return `${year}-${month}-${day}`
			},
			
			async viewContractDetail(contract) {
				try {
					uni.showLoading({ title: '加载中...' })
					
					// 获取合同详情
					const response = await apiRoute.getStudentContractDetail({
						contract_id: contract.contract_id,
						student_id: this.studentId
					})
					
					if (response.code === 1) {
						this.selectedContract = response.data
						this.showContractPopup = true
					} else {
						uni.showToast({
							title: response.msg || '获取合同详情失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('获取合同详情失败:', error)
					uni.showToast({
						title: '获取合同详情失败',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			},
			
			closeContractPopup() {
				this.showContractPopup = false
				this.selectedContract = null
			},
			
			async renewContract(contract) {
				uni.showModal({
					title: '确认续约',
					content: '确定要续约此合同吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								console.log('续约合同:', contract.id)
								
								// 模拟API调用
								await new Promise(resolve => setTimeout(resolve, 1000))
								const mockResponse = { code: 1, message: '续约申请已提交' }
								
								if (mockResponse.code === 1) {
									uni.showToast({
										title: '续约申请已提交',
										icon: 'success'
									})
								} else {
									uni.showToast({
										title: mockResponse.message || '续约申请失败',
										icon: 'none'
									})
								}
							} catch (error) {
								console.error('续约申请失败:', error)
								uni.showToast({
									title: '续约申请失败',
									icon: 'none'
								})
							}
						}
					}
				})
			},
			
			async signContract(contract) {
				try {
					// 首先获取签署表单配置
					const formResponse = await apiRoute.getStudentContractSignForm({
						contract_id: contract.contract_id,
						student_id: this.studentId
					})
					
					if (formResponse.code !== 1) {
						uni.showToast({
							title: formResponse.msg || '获取签署表单失败',
							icon: 'none'
						})
						return
					}
					
					const formConfig = formResponse.data
					
					// 如果有需要填写的字段，先展示表单
					if (formConfig.form_fields && formConfig.form_fields.length > 0) {
						uni.showModal({
							title: '提示',
							content: '此合同需要填写信息，将跳转到签署页面',
							success: (res) => {
								if (res.confirm) {
									// 跳转到签署页面
									uni.navigateTo({
										url: `/pages-student/contracts/sign?contract_id=${contract.contract_id}&student_id=${this.studentId}`
									})
								}
							}
						})
					} else {
						// 直接签署
						uni.showModal({
							title: '确认签署',
							content: '确定要签署此合同吗？',
							success: async (res) => {
								if (res.confirm) {
									try {
										const signResponse = await apiRoute.signStudentContract({
											contract_id: contract.contract_id,
											student_id: this.studentId,
											form_data: {}
										})
										
										if (signResponse.code === 1) {
											uni.showToast({
												title: '合同签署成功',
												icon: 'success'
											})
											
											// 重新加载合同列表
											this.currentPage = 1
											await this.loadContracts()
										} else {
											uni.showToast({
												title: signResponse.msg || '合同签署失败',
												icon: 'none'
											})
										}
									} catch (error) {
										console.error('合同签署失败:', error)
										uni.showToast({
											title: '合同签署失败',
											icon: 'none'
										})
									}
								}
							}
						})
					}
				} catch (error) {
					console.error('获取签署表单失败:', error)
					uni.showToast({
						title: '获取签署表单失败',
						icon: 'none'
					})
				}
			},
			
			async downloadContract() {
				if (!this.selectedContract) {
					uni.showToast({
						title: '请先选择一个合同',
						icon: 'none'
					})
					return
				}
				
				try {
					uni.showLoading({ title: '获取下载链接...' })
					
					const response = await apiRoute.downloadStudentContract({
						contract_id: this.selectedContract.contract_id,
						student_id: this.studentId
					})
					
					if (response.code === 1) {
						const downloadData = response.data
						
						// 在小程序中打开文件或跳转到下载链接
						if (downloadData.file_url) {
							// #ifdef MP-WEIXIN
							uni.downloadFile({
								url: downloadData.file_url,
								success: (res) => {
									if (res.statusCode === 200) {
										uni.openDocument({
											filePath: res.tempFilePath,
											success: () => {
												console.log('打开文档成功')
											},
											fail: (err) => {
												console.error('打开文档失败:', err)
												uni.showToast({
													title: '文件打开失败',
													icon: 'none'
												})
											}
										})
									}
								},
								fail: (err) => {
									console.error('下载失败:', err)
									uni.showToast({
										title: '下载失败',
										icon: 'none'
									})
								}
							})
							// #endif
							
							// #ifndef MP-WEIXIN
							// H5端直接打开链接
							window.open(downloadData.file_url, '_blank')
							// #endif
						} else {
							uni.showToast({
								title: '文件链接不存在',
								icon: 'none'
							})
						}
					} else {
						uni.showToast({
							title: response.msg || '获取下载链接失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('下载合同失败:', error)
					uni.showToast({
						title: '下载合同失败',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			}
		}
	}
</script>

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

// 自定义导航栏
.navbar_section {
	display: flex;
	justify-content: space-between;
	align-items: center;
	background: #29D3B4;
	padding: 40rpx 32rpx 20rpx;
	
	// 小程序端适配状态栏
	// #ifdef MP-WEIXIN
	padding-top: 80rpx;
	// #endif
	
	.navbar_back {
		width: 60rpx;
		
		.back_icon {
			color: #fff;
			font-size: 40rpx;
			font-weight: 600;
		}
	}
	
	.navbar_title {
		color: #fff;
		font-size: 32rpx;
		font-weight: 600;
	}
	
	.navbar_action {
		width: 60rpx;
	}
}

// 学员信息
.student_info_section {
	background: #fff;
	padding: 24rpx 32rpx;
	border-bottom: 1px solid #f0f0f0;
	
	.student_name {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
		margin-bottom: 12rpx;
	}
	
	.contract_stats {
		display: flex;
		gap: 24rpx;
		
		.stat_item {
			font-size: 24rpx;
			color: #666;
		}
	}
}

// 状态筛选
.filter_section {
	background: #fff;
	margin: 20rpx;
	border-radius: 16rpx;
	padding: 24rpx 32rpx;
	
	.filter_tabs {
		display: flex;
		flex-wrap: wrap;
		gap: 12rpx;
		
		.filter_tab {
			position: relative;
			padding: 10rpx 20rpx;
			font-size: 24rpx;
			color: #666;
			background: #f8f9fa;
			border-radius: 16rpx;
			
			&.active {
				color: #fff;
				background: #29D3B4;
			}
			
			.tab_badge {
				position: absolute;
				top: -6rpx;
				right: -6rpx;
				background: #ff4757;
				color: #fff;
				font-size: 18rpx;
				padding: 2rpx 6rpx;
				border-radius: 10rpx;
				min-width: 16rpx;
				text-align: center;
			}
		}
	}
}

// 合同列表
.contracts_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;
		}
	}
	
	.contracts_list {
		.contract_item {
			background: #fff;
			border-radius: 16rpx;
			padding: 24rpx;
			margin-bottom: 20rpx;
			box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
			
			.contract_header {
				display: flex;
				justify-content: space-between;
				align-items: flex-start;
				margin-bottom: 20rpx;
				
				.contract_info {
					flex: 1;
					
					.contract_name {
						font-size: 28rpx;
						font-weight: 600;
						color: #333;
						margin-bottom: 8rpx;
					}
					
					.contract_number {
						font-size: 24rpx;
						color: #666;
					}
				}
				
				.contract_status {
					font-size: 22rpx;
					padding: 6rpx 12rpx;
					border-radius: 12rpx;
					color: #666;
					background: rgba(102, 102, 102, 0.1);
				}
			}
			
			.contract_content {
				display: flex;
				gap: 32rpx;
				margin-bottom: 20rpx;
				
				.contract_details {
					flex: 1;
					
					.detail_row {
						display: flex;
						margin-bottom: 8rpx;
						
						.detail_label {
							font-size: 24rpx;
							color: #666;
							min-width: 120rpx;
						}
						
						.detail_value {
							font-size: 24rpx;
							color: #333;
							
							&.remaining {
								color: #29D3B4;
								font-weight: 600;
							}
							
							&.amount {
								color: #e74c3c;
								font-weight: 600;
							}
						}
					}
				}
				
				.contract_dates {
					.date_row {
						display: flex;
						margin-bottom: 8rpx;
						
						.date_label {
							font-size: 22rpx;
							color: #999;
							min-width: 100rpx;
						}
						
						.date_value {
							font-size: 22rpx;
							color: #666;
						}
					}
				}
			}
			
			.contract_progress {
				margin-bottom: 20rpx;
				
				.progress_info {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 8rpx;
					
					.progress_text {
						font-size: 22rpx;
						color: #666;
					}
					
					.progress_percent {
						font-size: 22rpx;
						color: #29D3B4;
						font-weight: 600;
					}
				}
				
				.progress_bar {
					height: 8rpx;
					background: #f0f0f0;
					border-radius: 4rpx;
					overflow: hidden;
					
					.progress_fill {
						height: 100%;
						background: linear-gradient(90deg, #29D3B4, #26c6a0);
						border-radius: 4rpx;
						transition: width 0.3s ease;
					}
				}
			}
			
			.contract_actions {
				display: flex;
				gap: 16rpx;
				justify-content: flex-end;
			}
		}
	}
}

// 加载更多
.load_more_section {
	padding: 40rpx 20rpx 80rpx;
}

// 合同详情弹窗
.contract_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;
	
	.popup_content {
		background: #fff;
		border-radius: 16rpx;
		width: 90%;
		max-height: 80vh;
		overflow: hidden;
		
		.popup_header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 32rpx;
			border-bottom: 1px solid #f0f0f0;
			
			.popup_title {
				font-size: 32rpx;
				font-weight: 600;
				color: #333;
			}
			
			.popup_close {
				font-size: 48rpx;
				color: #999;
				font-weight: 300;
			}
		}
		
		.popup_contract_detail {
			padding: 32rpx;
			max-height: 60vh;
			overflow-y: auto;
			
			.detail_section {
				margin-bottom: 32rpx;
				
				&:last-child {
					margin-bottom: 0;
				}
				
				.section_title {
					font-size: 28rpx;
					font-weight: 600;
					color: #333;
					margin-bottom: 16rpx;
					padding-bottom: 8rpx;
					border-bottom: 2rpx solid #29D3B4;
				}
				
				.info_grid {
					.info_row {
						display: flex;
						margin-bottom: 12rpx;
						
						.info_label {
							font-size: 26rpx;
							color: #666;
							min-width: 120rpx;
						}
						
						.info_value {
							font-size: 26rpx;
							color: #333;
							flex: 1;
						}
					}
				}
				
				.contract_terms {
					font-size: 24rpx;
					color: #666;
					line-height: 1.6;
					white-space: pre-line;
				}
			}
		}
		
		.popup_actions {
			padding: 24rpx 32rpx;
			display: flex;
			gap: 16rpx;
			border-top: 1px solid #f0f0f0;
			
			fui-button {
				flex: 1;
			}
		}
	}
}
</style>