<template>
	<view class="contract-detail-container">
		<!-- 自定义导航栏 -->
		<view class="custom-nav">
			<view class="nav-left" @click="goBack">
				<text class="iconfont icon-arrow-left"></text>
			</view>
			<view class="nav-title">合同详情</view>
			<view class="nav-right">
				<view v-if="contractData.sign_file" class="share-btn" @click="shareContract">
					<text class="iconfont icon-share"></text>
				</view>
			</view>
		</view>

		<!-- 加载状态 -->
		<view v-if="loading" class="loading-container">
			<uni-load-more status="loading" content-text="加载中..."></uni-load-more>
		</view>

		<!-- 合同内容 -->
		<view v-else class="contract-content">
			<!-- 合同状态卡片 -->
			<view class="status-card">
				<view class="status-header">
					<view class="status-info">
						<text class="contract-name">{{contractData.contract_name}}</text>
						<view class="status-badge" :class="needSignButton() ? 'status-unsigned' : 'status-signed'">
							{{needSignButton() ? '待签订' : '已签订'}}
						</view>
					</view>
					<view class="status-icon">
						<text v-if="needSignButton()" class="status-icon-text">⏰</text>
						<text v-else class="status-icon-text">✅</text>
					</view>
				</view>

				<view class="status-desc">
					<text v-if="needSignButton()" class="desc-text">请仔细阅读合同内容，确认无误后进行签订</text>
					<text v-else class="desc-text">合同已签订完成，您可以查看或下载合同文件</text>
				</view>
			</view>

			<!-- 合同基本信息 -->
			<view class="info-section">
				<view class="section-title">基本信息</view>
				<view class="info-list">
					<view class="info-item">
						<text class="info-label">合同名称</text>
						<text class="info-value">{{contractData.contract_name}}</text>
					</view>
					<view class="info-item">
						<text class="info-label">合同类型</text>
						<text class="info-value">{{contractData.contract_type}}</text>
					</view>
					<view class="info-item">
						<text class="info-label">合同状态</text>
						<text class="info-value">{{contractData.contract_status}}</text>
					</view>
					<view class="info-item">
						<text class="info-label">创建时间</text>
						<text class="info-value">{{formatDate(contractData.created_at)}}</text>
					</view>
					<view class="info-item" v-if="contractData.sign_time">
						<text class="info-label">签订时间</text>
						<text class="info-value">{{formatDate(contractData.sign_time)}}</text>
					</view>
					<view class="info-item" v-if="contractData.remarks">
						<text class="info-label">备注</text>
						<text class="info-value">{{contractData.remarks}}</text>
					</view>
				</view>
			</view>

			<!-- 合同模板预览 -->
			<view class="template-section" v-if="contractData.contract_template">
				<view class="section-title">合同模板</view>
				<view class="template-preview" @click="previewTemplate">
					<view class="template-icon">
						<text class="iconfont icon-file"></text>
					</view>
					<view class="template-info">
						<text class="template-name">{{getTemplateName()}}</text>
						<text class="template-desc">点击预览合同模板</text>
					</view>
					<view class="template-arrow">
						<text class="iconfont icon-arrow-right"></text>
					</view>
				</view>
			</view>

			<!-- 签名文件 -->
			<view class="signature-section" v-if="contractData.sign_file">
				<view class="section-title">签名文件</view>
				<view class="signature-preview" @click="previewSignature">
					<image :src="getSignatureUrl()" class="signature-image" mode="aspectFit"></image>
					<view class="signature-overlay">
						<text class="signature-text">点击查看完整签名</text>
					</view>
				</view>
			</view>

			<!-- 操作历史 -->
			<view class="history-section">
				<view class="section-title">操作历史</view>
				<view class="history-list">
					<view class="history-item">
						<view class="history-dot"></view>
						<view class="history-content">
							<text class="history-title">合同创建</text>
							<text class="history-time">{{formatDate(contractData.created_at)}}</text>
						</view>
					</view>
					<view class="history-item" v-if="contractData.sign_time">
						<view class="history-dot active"></view>
						<view class="history-content">
							<text class="history-title">合同签订</text>
							<text class="history-time">{{formatDate(contractData.sign_time)}}</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部操作按钮 -->
		<view class="footer-actions" v-if="!loading">
			<button v-if="needSignButton()" 
					class="action-btn primary" 
					@click="goToSign">
				立即签订
			</button>
			<button v-else 
					class="action-btn secondary" 
					@click="downloadContract">
				下载合同
			</button>
		</view>

		<!-- 图片预览模态框 -->
		<view v-if="showImagePreview" class="image-preview-modal" @click="closeImagePreview">
			<view class="preview-content" @click.stop>
				<image :src="previewImageUrl" class="preview-image" mode="aspectFit"></image>
				<view class="preview-close" @click="closeImagePreview">
					<text class="iconfont icon-close"></text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import apiRoute from '@/common/axios.js'

export default {
	data() {
		return {
			contractId: 0,
			contractData: {},
			loading: true,
			showImagePreview: false,
			previewImageUrl: ''
		}
	},
	onLoad(options) {
		if (options.id) {
			this.contractId = parseInt(options.id)
			this.loadContractDetail()
		} else {
			uni.showToast({
				title: '合同ID不能为空',
				icon: 'none'
			})
			setTimeout(() => {
				uni.navigateBack()
			}, 1500)
		}
	},
	methods: {
		// 返回上一页
		goBack() {
			uni.navigateBack()
		},

		// 加载合同详情
		async loadContractDetail() {
			this.loading = true

			try {
				const response = await apiRoute.get('contract/detail', {
					id: this.contractId
				})

				if (response.data.code === 1) {
					this.contractData = response.data.data || {}
				} else {
					uni.showToast({
						title: response.data.msg || '加载失败',
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				}
			} catch (error) {
				console.error('加载合同详情失败:', error)
				uni.showToast({
					title: '网络错误，请稍后重试',
					icon: 'none'
				})
			} finally {
				this.loading = false
			}
		},

		// 判断是否需要显示签订按钮
		needSignButton() {
			return this.contractData.status === 1 && (
				this.contractData.sign_file === null || 
				this.contractData.sign_file === '' || 
				this.contractData.sign_file === undefined
			)
		},


		// 前往签名页面
		goToSign() {
			uni.navigateTo({
				url: `/pages/common/contract/contract_sign?id=${this.contractId}&contractName=${encodeURIComponent(this.contractData.contract_name)}`
			})
		},

		// 预览合同模板
		previewTemplate() {
			if (this.contractData.contract_template) {
				const templateUrl = this.$baseUrl + '/' + this.contractData.contract_template
				// #ifdef APP-PLUS
				plus.runtime.openURL(templateUrl)
				// #endif

				// #ifdef H5
				window.open(templateUrl, '_blank')
				// #endif

				// #ifdef MP-WEIXIN
				uni.downloadFile({
					url: templateUrl,
					success: (res) => {
						uni.openDocument({
							filePath: res.tempFilePath,
							fileType: this.getFileType(this.contractData.contract_template)
						})
					}
				})
				// #endif
			}
		},

		// 预览签名文件
		previewSignature() {
			if (this.contractData.sign_file) {
				this.previewImageUrl = this.getSignatureUrl()
				this.showImagePreview = true
			}
		},

		// 关闭图片预览
		closeImagePreview() {
			this.showImagePreview = false
			this.previewImageUrl = ''
		},

		// 获取签名文件URL
		getSignatureUrl() {
			if (this.contractData.sign_file) {
				if (this.contractData.sign_file.startsWith('http')) {
					return this.contractData.sign_file
				} else {
					return this.$baseUrl + '/' + this.contractData.sign_file
				}
			}
			return ''
		},

		// 获取模板名称
		getTemplateName() {
			if (this.contractData.contract_template) {
				const parts = this.contractData.contract_template.split('/')
				return parts[parts.length - 1]
			}
			return '合同模板'
		},

		// 获取文件类型
		getFileType(fileName) {
			const ext = fileName.split('.').pop().toLowerCase()
			const typeMap = {
				'pdf': 'pdf',
				'doc': 'doc',
				'docx': 'doc',
				'xls': 'xls',
				'xlsx': 'xls'
			}
			return typeMap[ext] || 'doc'
		},

		// 下载合同
		downloadContract() {
			if (this.contractData.sign_file) {
				const signUrl = this.getSignatureUrl()
				uni.downloadFile({
					url: signUrl,
					success: (res) => {
						uni.showToast({
							title: '下载成功',
							icon: 'success'
						})
					},
					fail: () => {
						uni.showToast({
							title: '下载失败',
							icon: 'none'
						})
					}
				})
			}
		},

		// 分享合同
		shareContract() {
			uni.showActionSheet({
				itemList: ['分享给好友', '保存到相册'],
				success: (res) => {
					if (res.tapIndex === 0) {
						// 分享功能
						this.shareToFriend()
					} else if (res.tapIndex === 1) {
						// 保存到相册
						this.saveToAlbum()
					}
				}
			})
		},

		// 分享给好友
		shareToFriend() {
			uni.showToast({
				title: '分享功能开发中',
				icon: 'none'
			})
		},

		// 保存到相册
		saveToAlbum() {
			if (this.contractData.sign_file) {
				uni.saveImageToPhotosAlbum({
					filePath: this.getSignatureUrl(),
					success: () => {
						uni.showToast({
							title: '保存成功',
							icon: 'success'
						})
					},
					fail: () => {
						uni.showToast({
							title: '保存失败',
							icon: 'none'
						})
					}
				})
			}
		},

		// 格式化日期
		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 hour = String(date.getHours()).padStart(2, '0')
			const minute = String(date.getMinutes()).padStart(2, '0')
			return `${year}-${month}-${day} ${hour}:${minute}`
		}
	}
}
</script>

<style lang="scss" scoped>
.contract-detail-container {
	min-height: 100vh;
	background-color: #f5f5f5;
	padding-bottom: 120rpx;
}

/* 自定义导航栏 */
.custom-nav {
	display: flex;
	align-items: center;
	justify-content: space-between;
	height: 88rpx;
	padding: 0 32rpx;
	background-color: #fff;
	border-bottom: 1rpx solid #e5e5e5;
	position: sticky;
	top: 0;
	z-index: 100;

	.nav-left, .nav-right {
		width: 80rpx;
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;

		.iconfont {
			font-size: 36rpx;
			color: #333;
		}
	}

	.nav-title {
		font-size: 36rpx;
		font-weight: 600;
		color: #333;
	}

	.share-btn {
		cursor: pointer;
	}
}

/* 合同内容 */
.contract-content {
	padding: 20rpx;
}

/* 状态卡片 */
.status-card {
	background: linear-gradient(135deg, #007ACC 0%, #0056b3 100%);
	border-radius: 20rpx;
	padding: 40rpx;
	margin-bottom: 24rpx;
	color: #fff;

	.status-header {
		display: flex;
		align-items: flex-start;
		justify-content: space-between;
		margin-bottom: 24rpx;

		.status-info {
			flex: 1;

			.contract-name {
				font-size: 36rpx;
				font-weight: 600;
				display: block;
				margin-bottom: 16rpx;
			}

			.status-badge {
				display: inline-block;
				padding: 8rpx 20rpx;
				border-radius: 20rpx;
				font-size: 24rpx;
				font-weight: 500;
				background-color: rgba(255, 255, 255, 0.2);
				border: 1rpx solid rgba(255, 255, 255, 0.3);
			}
		}

		.status-icon {
			width: 80rpx;
			height: 80rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			.status-icon-text {
				font-size: 48rpx;
			}
		}
	}

	.status-desc {
		.desc-text {
			font-size: 28rpx;
			opacity: 0.9;
			line-height: 1.5;
		}
	}
}

/* 信息区块 */
.info-section, .template-section, .signature-section, .history-section {
	background-color: #fff;
	border-radius: 16rpx;
	padding: 32rpx;
	margin-bottom: 24rpx;

	.section-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
		margin-bottom: 24rpx;
		border-left: 6rpx solid #007ACC;
		padding-left: 16rpx;
	}
}

.info-list {
	.info-item {
		display: flex;
		align-items: center;
		margin-bottom: 24rpx;

		&:last-child {
			margin-bottom: 0;
		}

		.info-label {
			font-size: 28rpx;
			color: #666;
			width: 140rpx;
			flex-shrink: 0;
		}

		.info-value {
			font-size: 28rpx;
			color: #333;
			flex: 1;
		}
	}
}

/* 模板预览 */
.template-preview {
	display: flex;
	align-items: center;
	padding: 24rpx;
	background-color: #f8f9fa;
	border-radius: 12rpx;
	cursor: pointer;

	.template-icon {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #007ACC;
		border-radius: 12rpx;
		margin-right: 20rpx;

		.iconfont {
			font-size: 32rpx;
			color: #fff;
		}
	}

	.template-info {
		flex: 1;

		.template-name {
			font-size: 28rpx;
			color: #333;
			font-weight: 500;
			display: block;
			margin-bottom: 8rpx;
		}

		.template-desc {
			font-size: 24rpx;
			color: #999;
		}
	}

	.template-arrow {
		width: 40rpx;
		height: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;

		.iconfont {
			font-size: 24rpx;
			color: #999;
		}
	}
}

/* 签名预览 */
.signature-preview {
	position: relative;
	width: 100%;
	height: 300rpx;
	border-radius: 12rpx;
	overflow: hidden;
	cursor: pointer;

	.signature-image {
		width: 100%;
		height: 100%;
		border-radius: 12rpx;
	}

	.signature-overlay {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
		padding: 20rpx;
		display: flex;
		align-items: center;
		justify-content: center;

		.signature-text {
			color: #fff;
			font-size: 24rpx;
		}
	}
}

/* 操作历史 */
.history-list {
	.history-item {
		display: flex;
		align-items: flex-start;
		margin-bottom: 32rpx;

		&:last-child {
			margin-bottom: 0;
		}

		.history-dot {
			width: 20rpx;
			height: 20rpx;
			border-radius: 50%;
			background-color: #e5e5e5;
			margin-right: 20rpx;
			margin-top: 8rpx;
			flex-shrink: 0;

			&.active {
				background-color: #007ACC;
			}
		}

		.history-content {
			flex: 1;

			.history-title {
				font-size: 28rpx;
				color: #333;
				font-weight: 500;
				display: block;
				margin-bottom: 8rpx;
			}

			.history-time {
				font-size: 24rpx;
				color: #999;
			}
		}
	}
}

/* 底部操作按钮 */
.footer-actions {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #fff;
	padding: 24rpx 32rpx;
	border-top: 1rpx solid #e5e5e5;
	z-index: 100;

	.action-btn {
		width: 100%;
		height: 88rpx;
		border-radius: 12rpx;
		font-size: 32rpx;
		font-weight: 600;
		border: none;
		display: flex;
		align-items: center;
		justify-content: center;

		&.primary {
			background-color: #007ACC;
			color: #fff;

			&:active {
				background-color: #0056b3;
			}
		}

		&.secondary {
			background-color: #f5f5f5;
			color: #666;

			&:active {
				background-color: #e5e5e5;
			}
		}
	}
}

/* 加载状态 */
.loading-container {
	padding: 120rpx 40rpx;
	text-align: center;
}

/* 图片预览模态框 */
.image-preview-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.8);
	z-index: 1000;
	display: flex;
	align-items: center;
	justify-content: center;

	.preview-content {
		position: relative;
		width: 90%;
		height: 70%;

		.preview-image {
			width: 100%;
			height: 100%;
		}

		.preview-close {
			position: absolute;
			top: -60rpx;
			right: 0;
			width: 60rpx;
			height: 60rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			.iconfont {
				font-size: 36rpx;
				color: #fff;
			}
		}
	}
}
</style>