<template>
	<view class="match-container">
		<!-- 顶部导航栏 -->
		<view class="custom-navbar">
			<view class="navbar-back" @click="goBack">
				<text class="back-icon">←</text>
				<text class="back-text">返回</text>
			</view>
			<view class="navbar-title">智能匹配</view>
			<view class="navbar-placeholder"></view>
		</view>
		
		<!-- 顶部提示 -->
		<view class="tip-box">
			<text class="tip-icon">⚡</text>
			<text class="tip-text">智能匹配系统正在为您寻找最合适的TA</text>
		</view>

		<!-- 匹配动画区域 -->
		<view class="match-animation">
			<view class="heart-container" v-if="isMatching">
				<text class="heart">❤️</text>
				<text class="heart">❤️</text>
			</view>
			<text class="match-status">{{ matchStatus }}</text>
		</view>

		<!-- 匹配方式选择 -->
		<view class="match-modes">
			<view 
				class="mode-item" 
				:class="{ 'mode-item-active': selectedMode === 'smart' }"
				@tap="selectMode('smart')"
			>
				<view class="mode-icon">🎯</view>
				<view class="mode-title">智能算法</view>
				<view class="mode-desc">基于兴趣爱好、性格特征智能匹配</view>
				<view v-if="selectedMode === 'smart'" class="mode-selected">✓ 已选择</view>
			</view>

			<view 
				class="mode-item" 
				:class="{ 'mode-item-active': selectedMode === 'precise' }"
				@tap="selectMode('precise')"
			>
				<view class="mode-icon">💎</view>
				<view class="mode-title">精准推荐</view>
				<view class="mode-desc">根据您的偏好推荐最合适的对象</view>
				<view v-if="selectedMode === 'precise'" class="mode-selected">✓ 已选择</view>
			</view>
		</view>

		<!-- 开始匹配按钮 -->
		<view class="match-button-container" v-if="!isMatching">
			<button class="start-match-btn" @click="startMatch">
				<text class="btn-text">开始匹配</text>
			</button>
		</view>

		<!-- 取消匹配按钮 -->
		<view class="match-button-container" v-else>
			<button class="cancel-match-btn" @click="cancelMatch">
				<text class="btn-text">取消匹配</text>
			</button>
		</view>

		<!-- 匹配成功弹窗 -->
		<uni-popup ref="matchSuccessPopup" type="center">
			<view class="success-popup">
				<view class="success-icon">🎉</view>
				<view class="success-title">匹配成功！</view>
				<view class="success-score">匹配度：{{ matchScore }}%</view>
				
				<view class="matched-user-info">
					<image class="user-avatar" :src="matchedUser.avatarUrl || 'http://115.190.125.125:9001/static-images/default-avatar.svg'" mode="aspectFill"></image>
					<view class="user-name">{{ matchedUser.nickname }}</view>
					<view class="user-detail">{{ matchedUser.age }}岁 | {{ matchedUser.city }}</view>
					<view class="user-interests">
						<text class="interest-tag" v-for="(interest, index) in matchedUser.interests" :key="index">
							{{ interest }}
						</text>
					</view>
				</view>

				<view class="popup-buttons">
					<button class="btn-like" @click="likeMatchedUser">喜欢</button>
					<button class="btn-continue" @click="continueMatch">继续匹配</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import MATCH_API_CONFIG from '@/config/match-config.js'

export default {
	data() {
		return {
			isMatching: false,
			matchStatus: '点击下方按钮开始匹配',
			selectedMode: 'smart',
			matchScore: 0,
			matchedUser: {},
			userInfo: {},
			pollingTimer: null,
			isLiked: false
		}
	},
	
	onLoad() {
		this.loadUserInfo();
	},
	
	onUnload() {
		// 页面卸载时停止匹配
		if (this.isMatching) {
			this.cancelMatch();
		}
		if (this.pollingTimer) {
			clearInterval(this.pollingTimer);
		}
	},
	
	methods: {
		// 加载用户信息
		loadUserInfo() {
			// 从本地存储获取用户信息
			const userInfo = uni.getStorageSync('userInfo');
			if (userInfo) {
				this.userInfo = userInfo;
			} else {
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				});
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			}
		},
		
		// 选择匹配模式
		selectMode(mode) {
		
			this.selectedMode = mode;
			const modeNames = {
				'smart': '智能算法',
				'online': '实时在线',
				'precise': '精准推荐'
			};
			uni.showToast({
				title: `已选择：${modeNames[mode] || mode}`,
				icon: 'none',
				duration: 1500
			});
		},
		
		// 开始匹配
		async startMatch() {
			if (!this.userInfo.userId) {
				uni.showToast({
					title: '用户信息不完整',
					icon: 'none'
				});
				return;
			}
			
			this.isMatching = true;
			this.matchStatus = '正在匹配中...';
			
			try {
				// 构建匹配数据
				const matchData = {
					userId: String(this.userInfo.userId),
					nickname: this.userInfo.nickname || '用户',
					gender: this.userInfo.gender || 1,
					age: this.userInfo.age || 25,
					avatarUrl: this.userInfo.avatarUrl || '',
					interests: this.userInfo.interests || ['旅游', '美食'],
					city: this.userInfo.city || '未知',
					introduction: this.userInfo.introduction || '',
					latitude: this.userInfo.latitude || null,
					longitude: this.userInfo.longitude || null,
					matchMode: this.selectedMode || 'smart' // 添加匹配模式
				};
				
				
				
				// 调用匹配接口 - 使用配置文件中的地址
				const baseUrl = MATCH_API_CONFIG.BASE_URL;
				const url = `${baseUrl}${MATCH_API_CONFIG.ENDPOINTS.START_MATCH}`;
			
				
				const [error, res] = await uni.request({
					url: url,
					method: 'POST',
					header: {
						'Content-Type': 'application/json'
					},
					data: matchData,
					timeout: 10000
				});
				
			
				
				// 检查是否有错误或响应无效
				if (error || !res || !res.data) {
					this.isMatching = false;
					this.matchStatus = '点击下方按钮开始匹配';
					uni.showToast({
						title: '服务器连接失败，请确保后端服务已启动',
						icon: 'none',
						duration: 3000
					});
					return;
				}
				
				// 检查 HTTP 状态码
				if (res.statusCode !== 200) {
					this.isMatching = false;
					this.matchStatus = '点击下方按钮开始匹配';
					uni.showToast({
						title: `服务器错误 (${res.statusCode})，请联系管理员`,
						icon: 'none',
						duration: 3000
					});
					
					return;
				}
			
				
				if (res.data.code === 200) {
					if (res.data.status === 'success') {
						// 立即匹配成功
						const matchData = res.data.data;
						if (!matchData) {
							
							this.isMatching = false;
							this.matchStatus = '点击下方按钮开始匹配';
							uni.showToast({
								title: '匹配数据异常，请重试',
								icon: 'none'
							});
							return;
						}
						this.handleMatchSuccess(matchData);
					} else if (res.data.status === 'waiting') {
						// 等待匹配，开始轮询
						this.matchStatus = '正在寻找合适的对象...';
						this.startPolling();
					} else {
						this.isMatching = false;
						this.matchStatus = '点击下方按钮开始匹配';
						uni.showToast({
							title: res.data.msg || '匹配失败',
							icon: 'none'
						});
					}
				} else {
					this.isMatching = false;
					this.matchStatus = '点击下方按钮开始匹配';
					uni.showToast({
						title: res.data.msg || '匹配失败',
						icon: 'none'
					});
				}
			} catch (error) {
				
				this.isMatching = false;
				this.matchStatus = '点击下方按钮开始匹配';
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				});
			}
		},
		
		// 开始轮询匹配状态
		startPolling() {
			let pollCount = 0;
			const maxPolls = 15; // 最多轮询15次（30秒）
			
			// 每2秒检查一次匹配状态
			this.pollingTimer = setInterval(async () => {
				pollCount++;
			
				// 如果超过最大轮询次数，停止匹配
				if (pollCount >= maxPolls) {
					if (this.isMatching) {
						// 轮询超时，不显示取消匹配的提示，而是显示更合适的提示
						this.cancelMatch(false);
						uni.showToast({
							title: '暂无合适的匹配对象，请稍后再试',
							icon: 'none',
							duration: 2000
						});
					}
					return;
				}
				
				// 尝试查询匹配状态（如果后端有状态查询接口）
				try {
					const baseUrl = MATCH_API_CONFIG.BASE_URL;
					const userId = String(this.userInfo.userId);
					
					
				} catch (error) {
					
				}
			}, MATCH_API_CONFIG.CONFIG.POLLING_INTERVAL);
		},
		
		// 取消匹配
		// @param showToast 是否显示取消匹配的提示（默认true，轮询超时时传入false）
		async cancelMatch(showToast = true) {
			try {
				const baseUrl = MATCH_API_CONFIG.BASE_URL;
				const userId = String(this.userInfo.userId);
				const url = `${baseUrl}${MATCH_API_CONFIG.ENDPOINTS.CANCEL_MATCH}?userId=${userId}`;
			
				
				const [error, res] = await uni.request({
					url: url,
					method: 'POST',
					timeout: 5000
				});
				
				if (error) {
				
					if (showToast) {
						uni.showToast({
							title: '取消匹配失败',
							icon: 'none'
						});
					}
				} else {
					
					// 只有在需要显示提示时才显示
					if (showToast && res.data && res.data.code === 200) {
						uni.showToast({
							title: res.data.msg || '已取消匹配',
							icon: 'none'
						});
					}
				}
			} catch (error) {
			
				if (showToast) {
					uni.showToast({
						title: '取消匹配失败',
						icon: 'none'
					});
				}
			}
			
			this.isMatching = false;
			this.matchStatus = '点击下方按钮开始匹配';
			
			if (this.pollingTimer) {
				clearInterval(this.pollingTimer);
				this.pollingTimer = null;
			}
		},
		
		// 处理匹配成功
		handleMatchSuccess(data) {
		
			
			if (!data || typeof data !== 'object') {
				
				this.isMatching = false;
				this.matchStatus = '点击下方按钮开始匹配';
				uni.showToast({
					title: '匹配数据异常',
					icon: 'none'
				});
				return;
			}
			
			this.isMatching = false;
			this.matchStatus = '匹配成功！';
			
			if (this.pollingTimer) {
				clearInterval(this.pollingTimer);
				this.pollingTimer = null;
			}
			
			// 解析匹配数据 - 兼容不同的数据结构
			this.matchScore = Math.round(data.matchScore || (data.roomId ? 50 : 0));
			
			// 尝试多种可能的数据结构
			let matchedUserInfo = null;
			
			// 方式1: data.user2Info
			if (data.user2Info && typeof data.user2Info === 'object') {
				matchedUserInfo = data.user2Info;
			}
			// 方式2: data.matchedUser
			else if (data.matchedUser && typeof data.matchedUser === 'object') {
				matchedUserInfo = data.matchedUser;
			}
			// 方式3: data直接包含用户信息
			else if (data.userId || data.nickname) {
				matchedUserInfo = data;
			}
			// 方式4: 嵌套在matchPair中
			else if (data.matchPair) {
				matchedUserInfo = data.matchPair.matchedUser || data.matchPair.user2Info || data.matchPair;
			}
			
			
			// 设置匹配用户数据
			if (matchedUserInfo) {
				this.matchedUser = {
					userId: matchedUserInfo.userId || matchedUserInfo.user_id || '',
					nickname: matchedUserInfo.nickname || matchedUserInfo.name || '匹配用户',
					age: matchedUserInfo.age || 0,
					city: matchedUserInfo.city || '未知',
					avatarUrl: matchedUserInfo.avatarUrl || matchedUserInfo.avatar_url || 'http://115.190.125.125:9001/static-images/default-avatar.svg',
					interests: matchedUserInfo.interests || []
				};
			} else {
				// 如果完全无法提取，使用默认值
				
				this.matchedUser = {
					userId: '',
					nickname: '匹配用户',
					age: 0,
					city: '未知',
					avatarUrl: 'http://115.190.125.125:9001/static-images/default-avatar.svg',
					interests: []
				};
			}
			
		
			
			// 显示匹配成功弹窗
			this.$refs.matchSuccessPopup.open();
		},
		
		// 喜欢匹配的用户
		async likeMatchedUser() {
			if (!this.matchedUser || !this.matchedUser.userId) {
				uni.showToast({
					title: '用户信息错误',
					icon: 'none'
				});
				return;
			}
			
			const uid = parseInt(uni.getStorageSync('userId') || 1);
			const targetUserId = this.matchedUser.userId;
			
			try {
				// 导入 api 模块
				const api = require('@/utils/api.js').default;
				
				// 调用喜欢接口
				await api.recommend.feedback({ 
					userId: uid, 
					targetUserId: targetUserId, 
					type: 'like' 
				});
				
				this.isLiked = true;
				
				uni.showToast({ 
					title: '已喜欢', 
					icon: 'success' 
				});
				
				// 延迟关闭弹窗
				setTimeout(() => {
					this.$refs.matchSuccessPopup.close();
					this.matchStatus = '点击下方按钮开始匹配';
					this.matchedUser = {};
					this.isLiked = false;
				}, 1000);
			} catch(e) {
				console.error('喜欢失败', e);
				uni.showToast({
					title: '操作失败，请重试',
					icon: 'none'
				});
			}
		},
		
		// 继续匹配
		continueMatch() {
			this.$refs.matchSuccessPopup.close();
			this.matchStatus = '点击下方按钮开始匹配';
			this.matchedUser = {};
		},
		
		// 返回上一页
		goBack() {
			// 如果正在匹配中，先取消匹配
			if (this.isMatching) {
				uni.showModal({
					title: '提示',
					content: '正在匹配中，确定要退出吗？',
					success: (res) => {
						if (res.confirm) {
							this.cancelMatch();
							setTimeout(() => {
								uni.navigateBack();
							}, 500);
						}
					}
				});
			} else {
				uni.navigateBack();
			}
		}
	}
}
</script>

<style scoped>
.match-container {
	min-height: 100vh;
	background: linear-gradient(180deg, #FFF5F7 0%, #FFFFFF 100%);
	padding: 0;
}

/* 自定义导航栏 */
.custom-navbar {
	height: 88rpx;
	background: white;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 20rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	position: sticky;
	top: 0;
	z-index: 999;
}

.navbar-back {
	display: flex;
	align-items: center;
	padding: 10rpx 20rpx;
	cursor: pointer;
}

.navbar-back:active {
	opacity: 0.7;
}

.back-icon {
	font-size: 40rpx;
	color: #E91E63;
	font-weight: bold;
	margin-right: 8rpx;
}

.back-text {
	font-size: 28rpx;
	color: #333;
}

.navbar-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	position: absolute;
	left: 50%;
	transform: translateX(-50%);
}

.navbar-placeholder {
	width: 120rpx;
}

.tip-box {
	background: linear-gradient(135deg, #E3F2FD 0%, #F3E5F5 100%);
	border-left: 6rpx solid #2196F3;
	padding: 28rpx 24rpx;
	margin: 24rpx 20rpx;
	border-radius: 16rpx;
	display: flex;
	align-items: center;
	box-shadow: 0 2rpx 12rpx rgba(33, 150, 243, 0.1);
}

.tip-icon {
	font-size: 36rpx;
	margin-right: 16rpx;
}

.tip-text {
	font-size: 28rpx;
	color: #1976D2;
	flex: 1;
}

.match-animation {
	height: 320rpx;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	margin: 20rpx 0 30rpx 0;
}

.heart-container {
	position: relative;
	width: 200rpx;
	height: 200rpx;
	animation: pulse 1.5s ease-in-out infinite;
}

.heart {
	font-size: 100rpx;
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
}

.heart:nth-child(1) {
	animation: heart-beat 1.5s ease-in-out infinite;
}

.heart:nth-child(2) {
	animation: heart-beat 1.5s ease-in-out 0.75s infinite;
	opacity: 0.6;
}

.match-status {
	margin-top: 40rpx;
	font-size: 30rpx;
	color: #E91E63;
	font-weight: bold;
	text-align: center;
	padding: 0 40rpx;
}

.match-modes {
	margin: 20rpx 20rpx 180rpx 20rpx;
	padding-bottom: 20rpx;
}

.mode-item {
	background: white;
	border-radius: 20rpx;
	padding: 40rpx 32rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
	transition: all 0.3s;
	position: relative;
	cursor: pointer;
	-webkit-tap-highlight-color: transparent;
	border: 2rpx solid transparent;
}

.mode-item:active {
	transform: scale(0.98);
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.mode-item-active {
	background: linear-gradient(135deg, #FFF5F7 0%, #FFFFFF 100%);
	border: 3rpx solid #E91E63;
	box-shadow: 0 8rpx 24rpx rgba(233, 30, 99, 0.25);
	transform: translateY(-4rpx);
}

.mode-selected {
	position: absolute;
	top: 16rpx;
	right: 16rpx;
	background: #E91E63;
	color: white;
	padding: 8rpx 16rpx;
	border-radius: 20rpx;
	font-size: 24rpx;
	font-weight: bold;
}

.mode-icon {
	font-size: 72rpx;
	text-align: center;
	margin-bottom: 20rpx;
}

.mode-title {
	font-size: 34rpx;
	font-weight: bold;
	color: #333;
	text-align: center;
	margin-bottom: 16rpx;
}

.mode-desc {
	font-size: 26rpx;
	color: #999;
	text-align: center;
	line-height: 40rpx;
	padding: 0 20rpx;
}

.match-button-container {
	position: fixed;
	bottom: 80rpx;
	left: 30rpx;
	right: 30rpx;
	z-index: 100;
}

.start-match-btn {
	background: linear-gradient(135deg, #E91E63 0%, #C2185B 100%);
	color: white;
	border: none;
	border-radius: 50rpx;
	height: 100rpx;
	line-height: 100rpx;
	font-size: 36rpx;
	font-weight: bold;
	box-shadow: 0 8rpx 24rpx rgba(233, 30, 99, 0.4);
}

.start-match-btn:active {
	background: linear-gradient(135deg, #C2185B 0%, #AD1457 100%);
}

.cancel-match-btn {
	background: #FF9800;
	color: white;
	border: none;
	border-radius: 50rpx;
	height: 100rpx;
	line-height: 100rpx;
	font-size: 36rpx;
	font-weight: bold;
	box-shadow: 0 8rpx 24rpx rgba(255, 152, 0, 0.4);
}

.btn-text {
	color: white;
}

/* 匹配成功弹窗 */
.success-popup {
	width: 600rpx;
	background: white;
	border-radius: 24rpx;
	padding: 60rpx 40rpx;
	text-align: center;
}

.success-icon {
	font-size: 120rpx;
	margin-bottom: 20rpx;
}

.success-title {
	font-size: 40rpx;
	font-weight: bold;
	color: #E91E63;
	margin-bottom: 16rpx;
}

.success-score {
	font-size: 28rpx;
	color: #666;
	margin-bottom: 40rpx;
}

.matched-user-info {
	background: #F5F5F5;
	border-radius: 16rpx;
	padding: 32rpx;
	margin-bottom: 40rpx;
}

.user-avatar {
	width: 120rpx;
	height: 120rpx;
	border-radius: 60rpx;
	margin: 0 auto 20rpx;
	display: block;
}

.user-name {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 12rpx;
}

.user-detail {
	font-size: 28rpx;
	color: #999;
	margin-bottom: 20rpx;
}

.user-interests {
	display: flex;
	flex-wrap: wrap;
	justify-content: center;
	gap: 12rpx;
}

.interest-tag {
	background: #E91E63;
	color: white;
	padding: 8rpx 20rpx;
	border-radius: 20rpx;
	font-size: 24rpx;
}

.popup-buttons {
	display: flex;
	gap: 20rpx;
}

.btn-like,
.btn-continue {
	flex: 1;
	height: 80rpx;
	line-height: 80rpx;
	border-radius: 40rpx;
	font-size: 28rpx;
	border: none;
}

.btn-like {
	background: #E91E63;
	color: white;
}

.btn-continue {
	background: white;
	color: #E91E63;
	border: 2rpx solid #E91E63 !important;
}

/* 动画 */
@keyframes pulse {
	0%, 100% {
		transform: scale(1);
	}
	50% {
		transform: scale(1.1);
	}
}

@keyframes heart-beat {
	0%, 100% {
		transform: translate(-50%, -50%) scale(1);
		opacity: 1;
	}
	50% {
		transform: translate(-50%, -50%) scale(1.2);
		opacity: 0.8;
	}
}
</style>
