<template>
	<view class="precise-match">
		<!-- 顶部导航栏 -->
		<view class="header">
			<view class="back-icon" @click="handleBack"></view>
			<text class="header-title">精准匹配</text>
			<view class="header-right"></view>
		</view>

		<!-- 加载中 -->
		<view class="loading-container" v-if="loading">
			<text class="loading-text">正在匹配中...</text>
		</view>

		<!-- 匹配客户列表 -->
		<scroll-view scroll-y class="match-list" v-if="!loading">
			<view class="match-client" v-for="(client, index) in matchClients" :key="client.id || index">
				<!-- 匹配度标签 -->
				<view class="match-score-badge" v-if="client.matchScore">
					<text class="score-text">匹配度: {{ Math.round(client.matchScore) }}%</text>
				</view>
				<view class="client-info">
					<image :src="client.avatar" class="client-avatar" mode="aspectFill"></image>
					<view class="info-content">
						<view class="client-name">
							<text class="name-text">{{ client.name }}</text>
							<text class="client-gender">{{ client.gender }}</text>
							<text class="client-status">{{ client.status }}</text>
						</view>
						<view class="client-tags">
							<text class="tag" v-for="(tag, tagIndex) in client.tags" :key="tagIndex">{{ tag }}</text>
						</view>
						<view class="user-details" v-if="client.age || client.height || client.diploma">
							<text class="detail-item" v-if="client.age">{{ client.age }}岁</text>
							<text class="detail-item" v-if="client.height">{{ client.height }}cm</text>
							<text class="detail-item" v-if="client.diploma">{{ client.diploma }}</text>
							<text class="detail-item" v-if="client.income">{{ client.income }}</text>
							<text class="detail-item" v-if="client.occupation">{{ client.occupation }}</text>
						</view>
						<view class="requirement">
							<text class="requirement-label">择偶要求:</text>
							<text class="requirement-content">{{ client.requirement }}</text>
						</view>
						<view class="contact-info">
							<text class="contact-label">联系方式:</text>
							<text class="contact-number">{{ client.contact || '暂无' }}</text>
							<text class="copy-btn" @click="handleCopy(index)">复制</text>
						</view>
					</view>
				</view>
				<view class="action-btn" @click="handleChat(index)">牵线聊聊</view>
			</view>
		</scroll-view>

		<!-- 底部导航 -->
		<view class="tabbar">
			<view class="tabbar-item" @click="handleHome">
				<view class="tabbar-icon home"></view>
				<text class="tabbar-text">工作台</text>
			</view>
			<view class="tabbar-item active" @click="handleMyResources">
				<view class="tabbar-icon resources"></view>
				<text class="tabbar-text">我的资源</text>
			</view>
			<view class="tabbar-item" @click="handleRanking">
				<view class="tabbar-icon trophy"></view>
				<text class="tabbar-text">排行榜</text>
			</view>
			<!-- <view class="tabbar-item" @click="handleMessage">
				<view class="tabbar-icon message">
					<text class="badge">3</text>
				</view>
				<text class="tabbar-text">消息</text>
			</view> -->
			<view class="tabbar-item" @click="handleMine">
				<view class="tabbar-icon mine"></view>
				<text class="tabbar-text">我的</text>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	name: 'precise-match',
		data() {
			return {
				resourceId: null,
				matchClients: [],
				loading: false
			}
		},
	onLoad(options) {
		
		if (options.resourceId) {
			
			this.loadMatchClients(options.resourceId)
		} else if (options.id) {
			
			
			this.loadMatchClients(options.id)
		} else {
			uni.showToast({
				title: '缺少资源ID参数',
				icon: 'none'
			})
			setTimeout(() => {
				uni.navigateBack()
			}, 1500)
		}
	},
	methods: {
		// 返回上一页
		handleBack() {
			uni.navigateBack()
		},
		// 复制联系方式
		handleCopy(index) {
			
			
			// 从matchClients数组中获取client对象
			if (index === undefined || index === null || index < 0 || index >= this.matchClients.length) {
			
				uni.showToast({
					title: '数据错误',
					icon: 'none'
				})
				return
			}
			
			const client = this.matchClients[index]
			
			
			if (!client) {
				
				
				uni.showToast({
					title: '数据错误',
					icon: 'none'
				})
				return
			}
			
			
			// 优先使用完整手机号（originalPhone），如果没有则使用脱敏的手机号
			let phoneToCopy = ''
			
			// 优先使用originalPhone（完整手机号）
			const originalPhone = client.originalPhone || client.original_phone || client.originalphone
			
			if (originalPhone && typeof originalPhone === 'string' && originalPhone.trim() !== '') {
				phoneToCopy = originalPhone.trim()
				
			} else {
				
				// 如果没有originalPhone，尝试从脱敏的手机号中提取（但这样无法获取完整号码）
				if (client.contact) {
					try {
						const contactStr = String(client.contact || '')
						
						if (contactStr && contactStr.trim() !== '') {
							// 去除星号（但这样只能得到部分号码，不是完整号码）
							const extracted = contactStr.replace(/\*+/g, '').trim()
							if (extracted.length >= 11) {
								phoneToCopy = extracted
							
							}
						}
					} catch (e) {
						
					}
				}
			}
			
		
			
			// 检查是否为空
			if (!phoneToCopy || phoneToCopy === '') {
				
				uni.showToast({
					title: '联系方式为空',
					icon: 'none'
				})
				return
			}
			
			// 复制到剪贴板
			uni.setClipboardData({
				data: phoneToCopy,
				success: () => {
				
					uni.showToast({
						title: '复制成功',
						icon: 'success'
					})
				},
				fail: () => {
					
					uni.showToast({
						title: '复制失败',
						icon: 'none'
					})
				}
			})
		},
		// 牵线聊聊
		handleChat(index) {
		
			// 验证 index 是否有效
			if (index === null || index === undefined || index < 0 || index >= this.matchClients.length) {
				
				uni.showToast({
					title: '数据索引错误',
					icon: 'none'
				})
				return
			}
			
			// 从数组中获取 client 对象
			const client = this.matchClients[index]
		
			
			// 验证 client 对象是否存在
			if (!client) {
				
				
				uni.showToast({
					title: '客户信息为空，请刷新重试',
					icon: 'none',
					duration: 3000
				})
				return
			}
			
			
			
			// 尝试多种方式获取用户ID
			let targetUserId = null
			
			// 方式1: 使用 id 字段
			if (client.id !== null && client.id !== undefined && client.id !== '') {
				targetUserId = String(client.id)
			
			}
			// 方式2: 使用 userId 字段（后端原始字段）
			else if (client.userId !== null && client.userId !== undefined && client.userId !== '') {
				targetUserId = String(client.userId)
				
			}
			// 方式3: 使用 user_id 字段（下划线格式）
			else if (client.user_id !== null && client.user_id !== undefined && client.user_id !== '') {
				targetUserId = String(client.user_id)
				
			}
			
			// 如果仍然没有获取到用户ID
			if (!targetUserId || targetUserId === 'null' || targetUserId === 'undefined' || targetUserId === '') {
				
				
				uni.showToast({
					title: '无法获取用户ID，请刷新重试',
					icon: 'none',
					duration: 3000
				})
				return
			}
			
			// 获取其他必要信息
			const targetUserName = client.name || client.nickname || '用户'
			const targetUserAvatar = client.avatar || client.avatarUrl || '/static/default-avatar.svg'
			
		
			
			// 跳转到聊天页面
			// 注意：fromMatchmaker=1 表示来自红娘工作台，会跳过消息限制和审核
			uni.navigateTo({
				url: `/pages/message/chat?targetUserId=${targetUserId}&targetUserName=${encodeURIComponent(targetUserName)}&targetUserAvatar=${encodeURIComponent(targetUserAvatar)}&fromMatchmaker=1`,
				success: () => {
					
				},
				fail: (err) => {
					
					uni.showToast({
						title: '跳转失败，请重试',
						icon: 'none'
					})
				}
			})
		},
		// 从API加载匹配客户信息
		async loadMatchClients(resourceId) {
			if (!resourceId) {
				
				return
			}
			
			this.resourceId = resourceId
			this.loading = true
			
			try {
				const baseUrl = process.env.NODE_ENV === 'development' 
					? 'https://api.zhongruanke.cn/api'  // 开发环境 - 通过网关
					: 'https://your-domain.com/api'  // 生产环境
				
				// 加载匹配结果
				const [matchError, matchRes] = await uni.request({
					url: `${baseUrl}/my-resource/precise-match/${resourceId}`,
					method: 'GET'
				})
				
				this.loading = false
				
				if (matchError) {
					
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					})
					return
				}
				
				if (matchRes.statusCode === 200 && matchRes.data && matchRes.data.code === 200) {
					const matchList = matchRes.data.data || []
					
					
					
					
					// 转换数据格式
					this.matchClients = matchList.map((item, index) => {
						// 确保 originalPhone 被正确映射
						let originalPhoneValue = ''
						if (item.originalPhone !== null && item.originalPhone !== undefined) {
							originalPhoneValue = String(item.originalPhone).trim()
						} else if (item.original_phone !== null && item.original_phone !== undefined) {
							originalPhoneValue = String(item.original_phone).trim()
						}
						
						// 获取用户ID，支持多种字段名
						let userId = null
						if (item.userId !== null && item.userId !== undefined) {
							userId = item.userId
						} else if (item.user_id !== null && item.user_id !== undefined) {
							userId = item.user_id
						} else if (item.id !== null && item.id !== undefined) {
							userId = item.id
						}
						
						const mappedItem = {
							id: userId,  // 使用获取到的userId
							userId: userId,  // 同时保留原始字段，方便容错
							name: item.nickname || item.name || '未知',
							nickname: item.nickname || item.name,  // 保留原始字段
							gender: item.gender === 1 ? '男' : item.gender === 2 ? '女' : '未知',
							status: '未匹配',
							tags: item.tags || [],
							avatar: item.avatarUrl || item.avatar || 'https://via.placeholder.com/150',
							avatarUrl: item.avatarUrl || item.avatar,  // 保留原始字段
							requirement: item.requirement || '暂无要求',
							contact: (item.phone && typeof item.phone === 'string') ? item.phone : (item.phone ? String(item.phone) : ''),
							originalPhone: originalPhoneValue,
							matchScore: item.matchScore || 0,
							age: item.age,
							height: item.height,
							diploma: item.diploma,
							income: item.income,
							occupation: item.occupation,
							address: item.address
						}
						
						
						return mappedItem
					})
					
				
					
					if (this.matchClients.length === 0) {
						uni.showToast({
							title: '未找到匹配的用户',
							icon: 'none'
						})
					}
				} else {
					const errorMsg = matchRes.data?.message || '加载失败'
					
					uni.showToast({
						title: errorMsg,
						icon: 'none'
					})
				}
			} catch (e) {
				this.loading = false
			
				uni.showToast({
					title: '加载失败，请稍后重试',
					icon: 'none'
				})
			}
		},
		// 底部导航 - 工作台
		handleHome() {
			uni.navigateTo({
				url: '/pages/matchmaker-workbench/index'
			})
		},
		// 底部导航 - 我的资源
		handleMyResources() {
			uni.navigateTo({
				url: '/pages/matchmaker-workbench/my-resources'
			})
		},
		// 底部导航 - 排行榜
		handleRanking() {
			uni.navigateTo({
				url: '/pages/matchmaker-workbench/ranking'
			})
		},
		// 底部导航 - 消息
		handleMessage() {
			uni.navigateTo({
				url: '/pages/matchmaker-workbench/message'
			})
		},
		// 底部导航 - 我的
		handleMine() {
			uni.navigateTo({
				url: '/pages/matchmaker-workbench/mine'
			})
		}
	}
}
</script>

<style lang="scss" scoped>
	.precise-match {
		min-height: 100vh;
		background-color: #FFF9F9;
		padding-top: 90rpx;
	}

	/* 顶部导航栏 */
	.header {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		height: 90rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 20rpx;
		background: linear-gradient(135deg, #FCE4EC 0%, #F8BBD0 100%);
		z-index: 999;

		.back-icon {
			width: 44rpx;
			height: 44rpx;
			background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%23333"><path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/></svg>');
			background-size: contain;
			background-repeat: no-repeat;
			background-position: center;
		}

		.header-title {
			font-size: 38rpx;
			font-weight: bold;
			color: #333;
		}

		.header-right {
			width: 44rpx;
		}
	}

	/* 匹配客户列表 */
	.match-list {
		padding: 20rpx;
		padding-bottom: 120rpx;

		.match-client {
			background-color: #FFFFFF;
			border-radius: 20rpx;
			margin-bottom: 20rpx;
			padding: 25rpx;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);

			.client-info {
				display: flex;
				align-items: flex-start;
				margin-bottom: 20rpx;

				.client-avatar {
					width: 120rpx;
					height: 120rpx;
					border-radius: 50%;
					margin-right: 20rpx;
					background-color: #F5F5F5;
				}

				.info-content {
					flex: 1;

					.client-name {
						display: flex;
						align-items: center;
						gap: 15rpx;
						margin-bottom: 10rpx;

						.name-text {
							font-size: 32rpx;
							font-weight: bold;
							color: #333;
						}

						.client-gender {
							font-size: 26rpx;
							color: #666;
						}

						.client-status {
							font-size: 24rpx;
							color: #FF6B8A;
							background-color: #FFF3F5;
							padding: 4rpx 12rpx;
							border-radius: 15rpx;
						}
					}

					.client-tags {
						display: flex;
						flex-wrap: wrap;
						gap: 10rpx;
						margin-bottom: 15rpx;

						.tag {
							padding: 6rpx 16rpx;
							background-color: #F3E5F5;
							color: #9C27B0;
							border-radius: 15rpx;
							font-size: 22rpx;
						}
					}

					.requirement {
						display: flex;
						margin-bottom: 15rpx;

						.requirement-label {
							font-size: 26rpx;
							color: #666;
							margin-right: 10rpx;
						}

						.requirement-content {
							font-size: 26rpx;
							color: #333;
						}
					}
					
					.user-details {
						display: flex;
						flex-wrap: wrap;
						gap: 10rpx;
						margin-bottom: 15rpx;
						font-size: 24rpx;
						color: #999;
						
						.detail-item {
							display: flex;
							align-items: center;
							
							&::after {
								content: '|';
								margin: 0 10rpx;
								color: #ddd;
							}
							
							&:last-child::after {
								display: none;
							}
						}
					}

					.contact-info {
						display: flex;
						align-items: center;

						.contact-label {
							font-size: 26rpx;
							color: #666;
							margin-right: 10rpx;
						}

						.contact-number {
							font-size: 26rpx;
							color: #333;
							margin-right: 15rpx;
						}

						.copy-btn {
							font-size: 24rpx;
							color: #9C27B0;
							padding: 6rpx 16rpx;
							background-color: #F3E5F5;
							border-radius: 15rpx;
						}
					}
				}
			}

			.action-btn {
				width: 200rpx;
				height: 60rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				background-color: #9C27B0;
				color: #FFFFFF;
				border-radius: 30rpx;
				font-size: 28rpx;
				font-weight: bold;
				margin-left: auto;
			}
			
			.match-score-badge {
				position: absolute;
				top: 20rpx;
				right: 20rpx;
				background: linear-gradient(135deg, #FF6B8A 0%, #FF8E9B 100%);
				color: #FFFFFF;
				padding: 8rpx 16rpx;
				border-radius: 20rpx;
				font-size: 22rpx;
				font-weight: bold;
				z-index: 10;
				
				.score-text {
					color: #FFFFFF;
				}
			}
		}
	}
	
	/* 加载中 */
	.loading-container {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 100rpx 0;
		
		.loading-text {
			font-size: 28rpx;
			color: #999;
		}
	}

	/* 资源跟进状态区域 */
	.follow-status-section {
		background-color: #FFFFFF;
		margin: 20rpx;
		padding: 30rpx;
		border-radius: 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
		display: flex;
		justify-content: space-around;
		align-items: center;
	}

	.follow-status-group {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 12rpx;
	}

	.status-label {
		font-size: 26rpx;
		color: #666;
		font-weight: 500;
	}

	.status-tags {
		display: flex;
		gap: 10rpx;
	}

	.status-tag {
		padding: 8rpx 20rpx;
		border-radius: 20rpx;
		font-size: 24rpx;
		background-color: #FAF5FF;
		color: #9C27B0;
		border: 2rpx solid #E1BEE7;

		&.active {
			background-color: #F8BBD0;
			border-color: #F06292;
			color: #FFFFFF;
		}
	}

	/* 底部导航 */
	.tabbar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 100rpx;
		background: #FFFFFF;
		border-top: 1rpx solid #F0F0F0;
		display: flex;
		justify-content: space-around;
		align-items: center;
		padding-bottom: env(safe-area-inset-bottom);

		.tabbar-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			gap: 8rpx;
			padding: 10rpx 0;

			.tabbar-icon {
				width: 44rpx;
				height: 44rpx;
				background-size: contain;
				background-repeat: no-repeat;
				background-position: center;
				position: relative;

				.badge {
					position: absolute;
					top: -8rpx;
					right: -8rpx;
					width: 32rpx;
					height: 32rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					background-color: #FF4444;
					color: #FFFFFF;
					font-size: 20rpx;
					font-weight: bold;
					border-radius: 50%;
				}
			}

			.tabbar-text {
				font-size: 20rpx;
				color: #999;
			}

			&.active {
				.tabbar-text {
					color: #9C27B0;
					font-weight: bold;
				}
			}

			&.home .tabbar-icon {
				background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%23999"><path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/></svg>');
			}

			&.resources .tabbar-icon {
				background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%239C27B0"><path d="M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5C6.34 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z"/></svg>');
			}

			&.trophy .tabbar-icon {
				background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%23999"><path d="M18 6l-1.42 1.42-1.59-1.59L13 8.17l-1.42-1.42L9 8.17l-1.59-1.59L6 6l3 3V18c0 1.1.9 2 2 2h4c1.1 0 2-.9 2-2V9l3-3zm-4 12H8v-7.5l4-4 4 4V18z"/></svg>');
			}

			&.message .tabbar-icon {
				background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%23999"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/></svg>');
			}

			&.mine .tabbar-icon {
				background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%23999"><path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/></svg>');
			}
		}
	}
</style>