<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(client)">牵线聊聊</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) {
		// 从URL参数获取资源ID
		if (options.resourceId) {
			console.log('当前资源ID:', options.resourceId)
			this.loadMatchClients(options.resourceId)
		} else if (options.id) {
			// 兼容旧的参数名
			console.log('当前资源ID (兼容):', options.id)
			this.loadMatchClients(options.id)
		} else {
			uni.showToast({
				title: '缺少资源ID参数',
				icon: 'none'
			})
			setTimeout(() => {
				uni.navigateBack()
			}, 1500)
		}
	},
	methods: {
		// 返回上一页
		handleBack() {
			uni.navigateBack()
		},
		// 复制联系方式
		handleCopy(index) {
			console.log('=== 复制联系方式 ===')
			console.log('传入的index:', index)
			
			// 从matchClients数组中获取client对象
			if (index === undefined || index === null || index < 0 || index >= this.matchClients.length) {
				console.error('❌ index无效:', index)
				console.log('当前matchClients数组长度:', this.matchClients.length)
				uni.showToast({
					title: '数据错误',
					icon: 'none'
				})
				return
			}
			
			const client = this.matchClients[index]
			console.log('从数组获取的client:', client)
			
			if (!client) {
				console.error('❌ client对象为空')
				console.log('当前matchClients数组:', this.matchClients)
				uni.showToast({
					title: '数据错误',
					icon: 'none'
				})
				return
			}
			
			console.log('client.contact:', client.contact)
			console.log('client.originalPhone:', client.originalPhone)
			console.log('client.originalPhone类型:', typeof client.originalPhone)
			console.log('client的所有属性:', Object.keys(client))
			
			// 优先使用完整手机号（originalPhone），如果没有则使用脱敏的手机号
			let phoneToCopy = ''
			
			// 优先使用originalPhone（完整手机号）
			const originalPhone = client.originalPhone || client.original_phone || client.originalphone
			console.log('尝试获取originalPhone:', originalPhone)
			if (originalPhone && typeof originalPhone === 'string' && originalPhone.trim() !== '') {
				phoneToCopy = originalPhone.trim()
				console.log('✅ 使用originalPhone:', phoneToCopy.substring(0, 3) + '****')
			} else {
				console.log('❌ originalPhone为空或无效，尝试使用contact')
				// 如果没有originalPhone，尝试从脱敏的手机号中提取（但这样无法获取完整号码）
				if (client.contact) {
					try {
						const contactStr = String(client.contact || '')
						console.log('尝试从contact提取:', contactStr)
						if (contactStr && contactStr.trim() !== '') {
							// 去除星号（但这样只能得到部分号码，不是完整号码）
							const extracted = contactStr.replace(/\*+/g, '').trim()
							if (extracted.length >= 11) {
								phoneToCopy = extracted
								console.log('⚠️ 从脱敏号码提取:', phoneToCopy.substring(0, 3) + '****')
							} else {
								console.log('❌ 提取的号码长度不足:', extracted.length)
							}
						}
					} catch (e) {
						console.error('处理联系方式时出错:', e)
					}
				}
			}
			
			console.log('最终要复制的号码:', phoneToCopy ? phoneToCopy.substring(0, 3) + '****' : '空')
			
			// 检查是否为空
			if (!phoneToCopy || phoneToCopy === '') {
				console.error('❌ 联系方式为空，无法复制')
				uni.showToast({
					title: '联系方式为空',
					icon: 'none'
				})
				return
			}
			
			// 复制到剪贴板
			uni.setClipboardData({
				data: phoneToCopy,
				success: () => {
					console.log('✅ 复制成功:', phoneToCopy.substring(0, 3) + '****')
					uni.showToast({
						title: '复制成功',
						icon: 'success'
					})
				},
				fail: () => {
					console.error('❌ 复制失败')
					uni.showToast({
						title: '复制失败',
						icon: 'none'
					})
				}
			})
		},
		// 牵线聊聊
		handleChat(client) {
			// 跳转到聊天页面或打开聊天弹窗
			uni.showToast({
				title: '牵线成功',
				icon: 'success'
			})
		},
		// 从API加载匹配客户信息
		async loadMatchClients(resourceId) {
			if (!resourceId) {
				console.error('资源ID为空')
				return
			}
			
			this.resourceId = resourceId
			this.loading = true
			
			try {
				const baseUrl = process.env.NODE_ENV === 'development' 
					? 'http://localhost:8083/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) {
					console.error('加载匹配客户失败:', matchError)
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					})
					return
				}
				
				if (matchRes.statusCode === 200 && matchRes.data && matchRes.data.code === 200) {
					const matchList = matchRes.data.data || []
					
					console.log('=== 后端返回的匹配列表 ===')
					console.log('匹配列表长度:', matchList.length)
					if (matchList.length > 0) {
						console.log('第一个匹配项原始数据:', JSON.stringify(matchList[0], null, 2))
						console.log('第一个匹配项的phone字段:', matchList[0].phone)
						console.log('第一个匹配项的originalPhone字段:', matchList[0].originalPhone)
						console.log('第一个匹配项的所有字段:', Object.keys(matchList[0]))
					}
					
					// 转换数据格式
					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()
						}
						
						const mappedItem = {
							id: item.userId,
							name: item.nickname || '未知',
							gender: item.gender === 1 ? '男' : item.gender === 2 ? '女' : '未知',
							status: '未匹配',
							tags: item.tags || [],
							avatar: item.avatarUrl || 'https://via.placeholder.com/150',
							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
						}
						
						if (index === 0) {
							console.log('=== 第一个匹配项映射后 ===')
							console.log('contact:', mappedItem.contact)
							console.log('originalPhone:', mappedItem.originalPhone)
							console.log('originalPhone类型:', typeof mappedItem.originalPhone)
							console.log('originalPhone是否为空:', !mappedItem.originalPhone || mappedItem.originalPhone === '')
							console.log('映射后的完整对象:', mappedItem)
						}
						
						return mappedItem
					})
					
					console.log('匹配结果:', this.matchClients)
					
					if (this.matchClients.length === 0) {
						uni.showToast({
							title: '未找到匹配的用户',
							icon: 'none'
						})
					}
				} else {
					const errorMsg = matchRes.data?.message || '加载失败'
					console.error('加载匹配客户失败:', errorMsg)
					uni.showToast({
						title: errorMsg,
						icon: 'none'
					})
				}
			} catch (e) {
				this.loading = false
				console.error('加载匹配客户异常:', e)
				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>