<template>
	<view class="recommend-page">
		<view class="toolbar">
			<button size="mini" class="tool-btn refresh-btn" @click="refresh"><text class="icon">⟳</text><text>换一批</text></button>
			<button size="mini" class="tool-btn filter-btn" @click="openFilter"><text class="icon">🔍</text><text>筛选</text></button>
		</view>
		
		<!-- 推荐/匹配选项卡 -->
		<view class="tab-container">
			<view :class="['tab-item', currentTab === 'recommend' ? 'active' : '']" @click="switchToTab('recommend')">
				<text class="tab-icon">💕</text>
				<text class="tab-text">推荐</text>
			</view>
			<view :class="['tab-item', currentTab === 'match' ? 'active' : '']" @click="switchToTab('match')">
				<text class="tab-icon">⚡</text>
				<text class="tab-text">匹配</text>
			</view>
		</view>
		<uni-popup ref="filterPopup" type="bottom" :mask-click="true">
			<view class="filter-sheet">
				<view class="sheet-handle"></view>
				<view class="sheet-title">精确筛选</view>
				<view class="sheet-body">
					<view class="field">
						<text class="field-label">性别</text>
						<view class="seg">
							<view :class="['seg-item', query.gender===null?'active':'']" @click="setGender(null)">不限</view>
							<view :class="['seg-item', query.gender===1?'active':'']" @click="setGender(1)">男</view>
							<view :class="['seg-item', query.gender===2?'active':'']" @click="setGender(2)">女</view>
						</view>
					</view>
					<view class="field two">
						<text class="field-label">年龄</text>
						<input class="ipt" type="number" v-model.number="query.ageMin" placeholder="最小" />
						<text class="dash">-</text>
						<input class="ipt" type="number" v-model.number="query.ageMax" placeholder="最大" />
					</view>
					<view class="field two">
						<text class="field-label">身高(cm)</text>
						<input class="ipt" type="number" v-model.number="query.heightMin" placeholder="最小" />
						<text class="dash">-</text>
						<input class="ipt" type="number" v-model.number="query.heightMax" placeholder="最大" />
					</view>
					<view class="field">
						<text class="field-label">地区</text>
						<picker
							mode="multiSelector"
							:range="multiAreaData"
							range-key="name"
							:value="multiAreaIndex"
							@change="onMultiAreaChange"
							@columnchange="onMultiAreaColumnChange">
							<view class="ipt full picker">{{ areaDisplayText || '选择省市区' }}</view>
						</picker>
					</view>
					<view class="field two">
						<text class="field-label">学历/收入</text>
						<picker mode="selector" :range="educationOptions" range-key="label" @change="onEduChange">
							<view class="ipt picker">{{ currentEduText || '不限学历' }}</view>
						</picker>
						<picker mode="selector" :range="salaryOptions" range-key="label" @change="onSalaryChange">
							<view class="ipt picker">{{ currentSalaryText || '不限收入' }}</view>
						</picker>
					</view>
					<view class="field two">
						<text class="field-label">星座/生肖</text>
						<picker mode="selector" :range="starOptions" range-key="label" @change="onStarChange">
							<view class="ipt picker">{{ currentStarText || '不限星座' }}</view>
						</picker>
						<picker mode="selector" :range="animalOptions" range-key="label" @change="onAnimalChange">
							<view class="ipt picker">{{ currentAnimalText || '不限生肖' }}</view>
						</picker>
					</view>
					<view class="field">
						<text class="field-label">兴趣</text>
						<input class="ipt full" v-model="hobbyInput" placeholder="用逗号分隔，如：旅行,音乐" />
					</view>
				</view>
				<view class="sheet-actions">
					<button class="btn ghost" @click="resetFilter">重置</button>
					<button class="btn primary" @click="applyFilter">确定</button>
				</view>
			</view>
		</uni-popup>
		<!-- 用户详情弹窗 -->
		<uni-popup ref="userDetailPopup" type="center" :isMaskClick="true">
			<view class="user-detail-popup">
				<view class="popup-header">
					<text class="popup-title">用户详情</text>
					<text class="popup-close" @click="closeUserDetail">✕</text>
				</view>
				<scroll-view scroll-y class="popup-content" v-if="userDetail">
					<!-- 用户照片 -->
					<view class="detail-section photos-section" v-if="userDetail.photos && Array.isArray(userDetail.photos) && userDetail.photos.length > 0">
						<view class="section-title">📷 照片</view>
						<view class="photos-grid">
							<image
								v-for="(photo, pIdx) in userDetail.photos"
								:key="pIdx"
								:src="photo || '/static/close.png'"
								class="photo-item"
								mode="aspectFill"
								@click="previewPhoto(pIdx)"
								@error="onPhotoError"
							/>
						</view>
					</view>

					<!-- 基本信息 -->
					<view class="detail-section">
						<view class="section-title">基本信息</view>
						<view class="detail-info-grid">
							<view class="info-item" v-if="userDetail.nickname">
								<text class="info-label">昵称</text>
								<text class="info-value">{{ userDetail.nickname }}</text>
							</view>
							<view class="info-item" v-if="userDetail.genderText">
								<text class="info-label">性别</text>
								<text class="info-value">{{ userDetail.genderText }}</text>
							</view>
							<view class="info-item" v-if="userDetail.age">
								<text class="info-label">年龄</text>
								<text class="info-value">{{ userDetail.age }}岁</text>
							</view>
							<view class="info-item" v-if="userDetail.height">
								<text class="info-label">身高</text>
								<text class="info-value">{{ userDetail.height }}cm</text>
							</view>
							<view class="info-item" v-if="userDetail.weight">
								<text class="info-label">体重</text>
								<text class="info-value">{{ userDetail.weight }}kg</text>
							</view>
							<view class="info-item" v-if="userDetail.educationText">
								<text class="info-label">学历</text>
								<text class="info-value">{{ userDetail.educationText }}</text>
							</view>
							<view class="info-item" v-if="userDetail.salaryText">
								<text class="info-label">收入</text>
								<text class="info-value">{{ userDetail.salaryText }}</text>
							</view>
							<view class="info-item" v-if="userDetail.star">
								<text class="info-label">星座</text>
								<text class="info-value">{{ userDetail.star }}</text>
							</view>
							<view class="info-item" v-if="userDetail.animal">
								<text class="info-label">生肖</text>
								<text class="info-value">{{ userDetail.animal }}</text>
							</view>
							<view class="info-item" v-if="userDetail.jobTitle">
								<text class="info-label">职业</text>
								<text class="info-value">{{ userDetail.jobTitle }}</text>
							</view>
							<view class="info-item" v-if="userDetail.schoolName">
								<text class="info-label">毕业院校</text>
								<text class="info-value">{{ userDetail.schoolName }}</text>
							</view>
							<view class="info-item" v-if="userDetail.company">
								<text class="info-label">工作单位</text>
								<text class="info-value">{{ userDetail.company }}</text>
							</view>
							<view class="info-item" v-if="userDetail.maritalText">
								<text class="info-label">婚姻状况</text>
								<text class="info-value">{{ userDetail.maritalText }}</text>
							</view>
							<view class="info-item" v-if="userDetail.houseText">
								<text class="info-label">房产</text>
								<text class="info-value">{{ userDetail.houseText }}</text>
							</view>
							<view class="info-item" v-if="userDetail.carText">
								<text class="info-label">车产</text>
								<text class="info-value">{{ userDetail.carText }}</text>
							</view>
						</view>
					</view>

					<!-- 兴趣爱好 -->
					<view class="detail-section" v-if="userDetail.hobby">
						<view class="section-title">兴趣爱好</view>
						<view class="hobby-tags">
							<text
								v-for="(h, hIdx) in parseHobby(userDetail.hobby)"
								:key="hIdx"
								class="hobby-tag"
							>{{ h }}</text>
						</view>
					</view>

					<!-- 自我简介 -->
					<view class="detail-section" v-if="userDetail.introduction">
						<view class="section-title">自我简介</view>
						<view class="introduction-content">
							<text>{{ userDetail.introduction }}</text>
						</view>
					</view>
				</scroll-view>
				<view class="popup-loading" v-else>
					<text>加载中...</text>
				</view>
			</view>
		</uni-popup>
		<scroll-view scroll-y class="list">
			<view v-if="loading" class="skeleton">加载中...</view>
			<view v-else>
				<view v-for="(u, idx) in list" :key="u.userId || idx" class="card">
					<image :src="u.avatarUrl || '/static/close.png'" class="avatar" mode="aspectFill" @error="onImgErr(idx)"/>
					<view class="main" @click="showUserDetailByIndex(idx)">
						<view class="row">
							<text class="name">{{ u.nickname || '-' }}</text>
							<text class="score-badge">{{ fmtScore(u.compatibilityScore) }}</text>
						</view>
						<view class="meta">
							<text>{{ fmtGender(u.gender) }}</text>
							<text v-if="u.height">{{ u.height }}cm</text>
							<text v-if="u.educationLevel">{{ fmtEdu(u.educationLevel) }}</text>
							<text v-if="u.salaryRange">{{ fmtSalary(u.salaryRange) }}</text>
						</view>
						<view class="tags">
							<text v-if="u.star" class="tag">{{ u.star }}</text>
							<text v-if="u.animal" class="tag">{{ u.animal }}</text>
							<text v-if="u.jobTitle" class="tag">{{ u.jobTitle }}</text>
							<text v-for="t in parseHobby(u.hobby)" :key="t" class="tag">{{ t }}</text>
						</view>
					</view>
					<view class="actions">
						<button size="mini" class="act-btn ghost" @click.stop="dislike(idx)">不喜欢</button>
						<button size="mini" class="act-btn primary" @click.stop="like(idx)">喜欢</button>
					</view>
				</view>
				<view v-if="!list.length" class="empty">暂无推荐</view>
			</view>
		</scroll-view>
		<!-- 底部导航栏 -->
		<view class="tabbar">
			<view class="tabbar-item" @click="switchTab('index')">
				<text class="tabbar-icon">🏠</text>
				<text class="tabbar-text">首页</text>
			</view>
			<view class="tabbar-item" @click="switchTab('plaza')">
				<text class="tabbar-icon">💕</text>
				<text class="tabbar-text">广场</text>
			</view>
			<view class="tabbar-item active" @click="switchTab('recommend')">
				<text class="tabbar-icon">👍</text>
				<text class="tabbar-text">推荐</text>
			</view>
			<view class="tabbar-item" @click="switchTab('message')">
				<text class="tabbar-icon">💬</text>
				<text class="tabbar-text">消息</text>
			</view>
			<view class="tabbar-item" @click="switchTab('mine')">
				<text class="tabbar-icon">👤</text>
				<text class="tabbar-text">我的</text>
			</view>
		</view>
	</view>
</template>

<script>
import api from '@/utils/api.js'
import uniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue'
export default {
  components: { uniPopup },
	data() {
		return { 
			currentTab: 'recommend', // 当前选中的选项卡
			list: [], 
			loading: false, 
			oppoOnly: 1,
			userDetail: null, // 用户详细信息
		  query: { userId: null, gender: null, ageMin: null, ageMax: null, heightMin: null, heightMax: null, provinceId: null, cityId: null, areaId: null, educationMin: null, salaryMin: null, star: null, animal: null, hobbyTags: [], limit: 20, offset: 0 },
      hobbyInput: '',
      genderOptions: [{label:'不限', value:null},{label:'男', value:1},{label:'女', value:2}],
      educationOptions: [
        {label:'不限', value:null},{label:'高中及以下', value:1},{label:'大专', value:2},{label:'本科', value:3},{label:'硕士', value:4},{label:'博士', value:5}
      ],
      salaryOptions: [
        {label:'不限', value:null},{label:'<5k', value:1},{label:'5-10k', value:2},{label:'10-20k', value:3},{label:'20-50k', value:4},{label:'50k+', value:5}
      ],
		  starOptions: [
		    {label:'不限', value:null},{label:'白羊座', value:'白羊座'},{label:'金牛座', value:'金牛座'},{label:'双子座', value:'双子座'},{label:'巨蟹座', value:'巨蟹座'},{label:'狮子座', value:'狮子座'},{label:'处女座', value:'处女座'},{label:'天秤座', value:'天秤座'},{label:'天蝎座', value:'天蝎座'},{label:'射手座', value:'射手座'},{label:'摩羯座', value:'摩羯座'},{label:'水瓶座', value:'水瓶座'},{label:'双鱼座', value:'双鱼座'}
		  ],
		  animalOptions: [
		    {label:'不限', value:null},{label:'鼠', value:'鼠'},{label:'牛', value:'牛'},{label:'虎', value:'虎'},{label:'兔', value:'兔'},{label:'龙', value:'龙'},{label:'蛇', value:'蛇'},{label:'马', value:'马'},{label:'羊', value:'羊'},{label:'猴', value:'猴'},{label:'鸡', value:'鸡'},{label:'狗', value:'狗'},{label:'猪', value:'猪'}
		  ],
		  currentEduText: '', currentSalaryText: '', currentStarText: '', currentAnimalText: '',
      provinceList: [], cityList: [], areaList: [],
      multiAreaData: [[], [], []], // 多列选择器数据：[省份列表, 城市列表, 区域列表]
      multiAreaIndex: [0, 0, 0], // 多列选择器当前选中的索引
      areaDisplayText: '选择省市区' // 显示的省市区文本
    }
	},
	computed: {
	    unreadCount() {
	      return this.$store.getters.getTotalUnread || 0;
	    }
	  },

	onLoad() { this.refresh() },
	methods: {
		// 切换选项卡
		switchToTab(tab) {
			this.currentTab = tab
			if (tab === 'recommend') {
				// 保持在当前推荐页面，刷新推荐列表
				console.log('切换到推荐页面')
				this.refresh()
			} else if (tab === 'match') {
				// 跳转到匹配页面
				console.log('切换到在线匹配')
				uni.navigateTo({ 
					url: '/pages/match/index',
					fail: () => {
						uni.showToast({
							title: '在线匹配功能开发中...',
							icon: 'none'
						})
					}
				})
			}
		},
		
		switchTab(tab) {
			if (tab === 'recommend') return
			const tabPages = {
				index: '/pages/index/index',
				plaza: '/pages/plaza/index',
				message: '/pages/message/index',
				mine: '/pages/mine/index'
			}
			if (tabPages[tab]) {
				uni.redirectTo({ url: tabPages[tab] })
			}
		},
    async refresh() {
			this.loading = true
			try {
        const storedUserId = uni.getStorageSync('userId'); const userId = storedUserId ? parseInt(storedUserId) : 1
        // 如果没有筛选，走默认接口；有筛选，调用 search
        if (!this.hasFilter()) {
          const data = await api.recommend.getUsers({ userId, oppoOnly: this.oppoOnly, limit: 20 })
          const seen = new Set(); const merged = []
          for (const it of (data || [])) { if (!seen.has(it.userId)) { seen.add(it.userId); merged.push(it) } }
          this.list = merged.map(it=>({ ...it, avatarUrl: this.getSafeAvatar(it.avatarUrl) }))
        } else {
          this.query.userId = userId; this.query.limit = 20; this.query.offset = 0
          const payload = this.buildQueryPayload()
          const data = await api.recommend.search(payload)
          const arr = Array.isArray(data) ? data : []
          this.list = arr.map(it=>({ ...it, avatarUrl: this.getSafeAvatar(it.avatarUrl) }))
        }
			} catch (e) {
        const msg = (e && (e.message || e.msg)) ? String(e.message || e.msg) : '获取推荐失败'
        console.error('recommend/search error:', e)
        uni.showToast({ title: msg, icon: 'none' })
			} finally { this.loading = false }
		},
		openFilter(){ this.ensureAreaData(); this.$refs.filterPopup.open('bottom') },
		closeFilter(){ this.$refs.filterPopup.close() },
		applyFilter(){ this.$refs.filterPopup.close(); this.refresh() },
		hasFilter(){
		  const q=this.query
		  return !!(q.gender||q.ageMin||q.ageMax||q.heightMin||q.heightMax||q.provinceId||q.cityId||q.areaId||q.educationMin||q.salaryMin||q.star||q.animal||this.hobbyInput)
		},
		genderText(v){ if(v===1)return '男'; if(v===2)return '女'; return '不限' },
		setGender(v){ this.query.gender=v },
		onEduChange(e){
			const item = this.educationOptions[e.detail.value];
			this.query.educationMin = item.value;
			this.currentEduText = item.label;
		},
		onSalaryChange(e){
			const item = this.salaryOptions[e.detail.value];
			this.query.salaryMin = item.value;
			this.currentSalaryText = item.label;
		},
		onStarChange(e){
		  const item = this.starOptions[e.detail.value];
		  this.query.star = item.value || null;
		  this.currentStarText = item.label;
		},
		onAnimalChange(e){
		  const item = this.animalOptions[e.detail.value];
		  this.query.animal = item.value || null;
		  this.currentAnimalText = item.label;
		},
		buildQueryPayload(){
			const q = { ...this.query };
			if (this.hobbyInput) {
				q.hobbyTags = this.hobbyInput.split(',').map(s=>s.trim()).filter(Boolean)
			} else {
				delete q.hobbyTags
			}
			// 清理空值/空字符串/NaN，避免后端收到无效条件
			Object.keys(q).forEach(k => {
				const v = q[k];
				if (v === null || v === undefined || v === '' || (typeof v === 'number' && Number.isNaN(v))) {
					delete q[k]
				}
			})
			return q
		},
		resetFilter(){
		  this.query={...this.query, gender:null, ageMin:null, ageMax:null, heightMin:null, heightMax:null, provinceId:null, cityId:null, areaId:null, educationMin:null, salaryMin:null, star:null, animal:null};
		  this.hobbyInput=''; this.currentStarText=''; this.currentAnimalText='';
		  this.areaDisplayText='';
		  this.multiAreaIndex=[0, 0, 0];
		  this.cityList=[]; this.areaList=[]
		  // 重置多列选择器数据，保留省份列表
		  if(this.provinceList.length > 0){
		    this.multiAreaData[0] = this.provinceList
		    this.multiAreaData[1] = []
		    this.multiAreaData[2] = []
		  }
		},
		async ensureAreaData(){
		  // 加载省份列表
		  if(!this.provinceList.length){
		    try{
		      this.provinceList = await api.area.getProvinces()
		      // 初始化多列选择器的省份数据
		      this.multiAreaData[0] = this.provinceList
		      // 如果有省份，加载第一个省份的城市
		      if(this.provinceList.length > 0){
		        await this.loadCitiesForProvince(0)
		      }
		    }catch(e){
		      console.error('加载省份失败:', e)
		    }
		  }
		},
		// 加载指定省份的城市
		async loadCitiesForProvince(provinceIndex){
		  if(provinceIndex < 0 || provinceIndex >= this.provinceList.length) return
		  const province = this.provinceList[provinceIndex]
		  if(!province || !province.id) return

		  try{
		    const cities = await api.area.getCities(province.id)
		    this.multiAreaData[1] = cities || []
		    this.cityList = cities || []
		    // 重置区域
		    this.multiAreaData[2] = []
		    this.areaList = []
		    this.multiAreaIndex[1] = 0
		    this.multiAreaIndex[2] = 0

		    // 如果有城市，加载第一个城市的区域
		    if(cities && cities.length > 0){
		      await this.loadAreasForCity(0, cities)
		    }
		  }catch(err){
		    console.error('加载城市失败:', err)
		    this.multiAreaData[1] = []
		    this.cityList = []
		    this.multiAreaData[2] = []
		    this.areaList = []
		  }
		},
		// 加载指定城市的区域
		async loadAreasForCity(cityIndex, cities = null){
		  const cityList = cities || this.cityList
		  if(cityIndex < 0 || cityIndex >= cityList.length) return
		  const city = cityList[cityIndex]
		  if(!city || !city.id) return

		  try{
		    const areas = await api.area.getAreas(city.id)
		    this.multiAreaData[2] = areas || []
		    this.areaList = areas || []
		    this.multiAreaIndex[2] = 0
		  }catch(err){
		    console.error('加载区域失败:', err)
		    this.multiAreaData[2] = []
		    this.areaList = []
		  }
		},
		// 多列选择器列变化事件（滑动某一列时触发）
		async onMultiAreaColumnChange(e){
			const column = e.detail.column // 改变的列索引：0-省份，1-城市，2-区域
			const row = e.detail.value // 新选中的行索引

			if(column === 0){
				// 选择了省份，需要加载该省份的城市
				this.multiAreaIndex[0] = row
				await this.loadCitiesForProvince(row)
			}else if(column === 1){
				// 选择了城市，需要加载该城市的区域
				this.multiAreaIndex[1] = row
				await this.loadAreasForCity(row)
			}else if(column === 2){
				// 选择了区域
				this.multiAreaIndex[2] = row
			}
		},
		// 多列选择器确认选择事件
		onMultiAreaChange(e){
			const values = e.detail.value // [省份索引, 城市索引, 区域索引]
			this.multiAreaIndex = values

			// 从 multiAreaData 中获取选中的数据
			const provinceIndex = values[0]
			const cityIndex = values[1]
			const areaIndex = values[2]

			const province = this.multiAreaData[0] && this.multiAreaData[0][provinceIndex]
			const city = this.multiAreaData[1] && this.multiAreaData[1][cityIndex]
			const area = this.multiAreaData[2] && this.multiAreaData[2][areaIndex]

			// 更新查询参数
			this.query.provinceId = province?.id || null
			this.query.cityId = city?.id || null
			this.query.areaId = area?.id || null

			// 同步到单独的列表（用于兼容）
			if(province) {
				const pIdx = this.provinceList.findIndex(p => p.id === province.id)
				if(pIdx >= 0) {
					this.cityList = this.multiAreaData[1] || []
					if(city) {
						const cIdx = this.cityList.findIndex(c => c.id === city.id)
						if(cIdx >= 0) {
							this.areaList = this.multiAreaData[2] || []
						}
					}
				}
			}

			// 更新显示文本
			const parts = []
			if(province) parts.push(province.name)
			if(city) parts.push(city.name)
			if(area) parts.push(area.name)
			this.areaDisplayText = parts.length > 0 ? parts.join(' ') : '选择省市区'
		},
		getSafeAvatar(url){
			if(!url) return '/static/close.png'
			const u = String(url)
			if(u.includes('example.com')) return '/static/close.png'
			return u
		},
		fmtScore(s){ return s ? Number(s).toFixed(1) : '0.0' },
		fmtGender(g){ return g===1?'男':g===2?'女':'-' },
		fmtEdu(v){ const map={1:'高中',2:'大专',3:'本科',4:'硕士',5:'博士'}; return map[v]||'-' },
		fmtSalary(v){ const map={1:'<5k',2:'5-10k',3:'10-20k',4:'20-50k',5:'50k+'}; return map[v]||'-' },
		parseHobby(h){ try{ const arr = typeof h === 'string' ? JSON.parse(h) : h; return Array.isArray(arr)?arr.slice(0,6):[] }catch{return []} },
		async like(i){ 
			const u=this.list[i]; 
			if(!u) return; 
			
			const uid = parseInt(uni.getStorageSync('userId')||1); 
			
			// 调用 API 记录喜欢
			if(u.userId){ 
				try {
					await api.recommend.feedback({ userId: uid, targetUserId: u.userId, type: 'like' });
				} catch(e) {
					console.error('反馈失败', e);
				}
			}
			
			// 显示选择弹窗
			uni.showModal({
				title: '已喜欢 ❤️',
				content: `你喜欢了 ${u.nickname || '该用户'}，要立即发消息吗？`,
				confirmText: '发消息',
				cancelText: '继续浏览',
				success: (res) => {
					if (res.confirm) {
						// 跳转到聊天页面
						this.openChat(u);
					} else {
						// 继续浏览，显示成功提示
						uni.showToast({ title:'已记录', icon:'success' });
					}
				}
			});
		},
		
		async openChat(user) {
			// 验证必要参数
			if (!user || !user.userId) {
				uni.showToast({
					title: '用户信息错误',
					icon: 'none'
				});
				return;
			}

			const targetUserId = parseInt(user.userId);
			const targetUserName = user.nickname || '用户';
			const targetUserAvatar = user.avatarUrl || '/static/close.png';

			console.log('准备打开聊天，参数：', {
				targetUserId,
				targetUserName,
				targetUserAvatar
			});

			// 先导入用户到腾讯云IM（防止消息发送失败）
			uni.showLoading({ title: '准备中...' });

			try {
				// 获取当前用户ID
				const currentUserId = uni.getStorageSync('userId');

				console.log('📥 开始导入用户到TIM...');
				console.log('   - 当前用户:', currentUserId);
				console.log('   - 目标用户:', targetUserId);

				// 导入当前用户
				await uni.request({
					url: 'http://localhost:1004/api/im/importUser',
					method: 'POST',
					data: {
						userId: String(currentUserId),
						nickname: '用户' + currentUserId
					},
					header: {
						'Content-Type': 'application/json'
					}
				});

				// 导入目标用户
				await uni.request({
					url: 'http://localhost:1004/api/im/importUser',
					method: 'POST',
					data: {
						userId: String(targetUserId),
						nickname: targetUserName
					},
					header: {
						'Content-Type': 'application/json'
					}
				});

				console.log('✅ 用户导入完成');

				// 等待一小段时间确保导入生效
				await new Promise(resolve => setTimeout(resolve, 500));

				uni.hideLoading();

				// 跳转到聊天页面
				uni.navigateTo({
					url: `/pages/message/chat?targetUserId=${targetUserId}&targetUserName=${encodeURIComponent(targetUserName)}&targetUserAvatar=${encodeURIComponent(targetUserAvatar)}`
				});

			} catch (error) {
				console.error('❌ 导入用户失败:', error);
				uni.hideLoading();

				// 即使导入失败也尝试打开聊天（用户可能已存在）
				uni.navigateTo({
					url: `/pages/message/chat?targetUserId=${targetUserId}&targetUserName=${encodeURIComponent(targetUserName)}&targetUserAvatar=${encodeURIComponent(targetUserAvatar)}`
				});
			}
		},
		dislike(i){
			const u=this.list[i];
			if(!u) return;
			this.list.splice(i,1);
			uni.showToast({ title:'已隐藏', icon:'none' });
			const uid = parseInt(uni.getStorageSync('userId')||1);
			if(u.userId){
				api.recommend.feedback({ userId: uid, targetUserId: u.userId, type: 'dislike' })
			}
		},
		onImgErr(idx){
			this.$set(this.list[idx], 'avatarUrl', '/static/close.png')
		},
		// 通过索引显示用户详情（跳转到新页面）
		showUserDetailByIndex(index) {
			if (index < 0 || index >= this.list.length) {
				uni.showToast({
					title: '用户索引无效',
					icon: 'none'
				})
				return
			}
			const user = this.list[index]
			if (!user || !user.userId) {
				uni.showToast({
					title: '用户信息不存在',
					icon: 'none'
				})
				return
			}
			// 跳转到用户详情页面
			const score = user.compatibilityScore ? user.compatibilityScore : ''
			uni.navigateTo({
				url: `/pages/recommend/user-detail?userId=${user.userId}&score=${score}`
			})
		},
		// 显示用户详情
		async showUserDetail(user) {
			console.log('showUserDetail 被调用，user:', user)

			if (!user || !user.userId) {
				console.error('用户信息无效:', user)
				uni.showToast({
					title: '用户信息错误',
					icon: 'none'
				})
				return
			}

			// 确保userId是数字类型
			const userId = parseInt(user.userId)
			if (!userId || isNaN(userId)) {
				uni.showToast({
					title: '用户ID无效',
					icon: 'none'
				})
				return
			}

			// 先打开弹窗
			this.userDetail = null
			try {
				if (this.$refs.userDetailPopup) {
					this.$refs.userDetailPopup.open('center')
				} else {
					console.error('弹窗组件引用不存在')
					uni.showToast({
						title: '弹窗初始化失败',
						icon: 'none'
					})
					return
				}
			} catch (err) {
				console.error('打开弹窗失败:', err)
				uni.showToast({
					title: '打开弹窗失败',
					icon: 'none'
				})
				return
			}

			// 加载用户详情
			try {
				uni.showLoading({ title: '加载中...' })
				console.log('开始请求用户详情，userId:', userId)
				const detail = await api.user.getDetailInfo(userId)
				console.log('获取到的用户详情:', detail)

				if (detail) {
					// 确保photos是数组，如果没有photos但有avatar，使用avatar
					if (!detail.photos || !Array.isArray(detail.photos)) {
						detail.photos = []
						if (detail.avatar) {
							detail.photos.push(detail.avatar)
						}
					}
					// 确保所有字段都有默认值，避免显示undefined
					if (!detail.nickname) detail.nickname = '未设置'
					this.userDetail = detail
				} else {
					uni.showToast({
						title: '用户信息为空',
						icon: 'none'
					})
					if (this.$refs.userDetailPopup) {
						this.$refs.userDetailPopup.close()
					}
				}
			} catch (e) {
				console.error('获取用户详情失败:', e)
				const errorMsg = e && e.message ? e.message : '获取用户信息失败'
				uni.showToast({
					title: errorMsg,
					icon: 'none',
					duration: 2000
				})
				// 如果加载失败，关闭弹窗
				if (this.$refs.userDetailPopup) {
					this.$refs.userDetailPopup.close()
				}
			} finally {
				uni.hideLoading()
			}
		},
		// 关闭用户详情
		closeUserDetail() {
			try {
				if (this.$refs.userDetailPopup) {
					this.$refs.userDetailPopup.close()
				}
			} catch (e) {
				console.error('关闭弹窗失败:', e)
			}
			this.userDetail = null
		},
		// 预览照片
		previewPhoto(index) {
			if (!this.userDetail || !this.userDetail.photos || !Array.isArray(this.userDetail.photos) || this.userDetail.photos.length === 0) {
				return
			}
			uni.previewImage({
				urls: this.userDetail.photos,
				current: index
			})
		},
		// 照片加载错误处理
		onPhotoError(e) {
			console.error('照片加载失败:', e)
		}
	}
}
</script>

<style lang="scss" scoped>
	/* 扁平化设计风格 */
	.recommend-page { 
		min-height: 100vh; 
		background-color: #F5F5F5; 
		padding-bottom: 120rpx; 
	}
	
	.toolbar{ 
		display: flex; 
		justify-content: space-between; 
		align-items: center; 
		padding: 16rpx 20rpx;
		background: #FFFFFF;
		border-bottom: 2rpx solid #E0E0E0;
	}
	
	/* 选项卡样式 - 扁平化 */
	.tab-container {
		display: flex;
		margin: 20rpx;
		background: #FFFFFF;
		border-radius: 8rpx;
		border: 2rpx solid #E0E0E0;
		overflow: hidden;
	}
	
	.tab-item {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 18rpx 20rpx;
		transition: all 0.2s ease;
		border-right: 2rpx solid #E0E0E0;
		
		&:last-child {
			border-right: none;
		}
		
		.tab-icon {
			font-size: 28rpx;
			margin-right: 8rpx;
		}
		
		.tab-text {
			font-size: 28rpx;
			font-weight: 500;
		}
		
		&.active {
			background: #FFE5F1;
			
			.tab-icon {
				color: #E91E63;
			}
			
			.tab-text {
				color: #E91E63;
				font-weight: 600;
			}
		}
		
		&:not(.active) {
			background: #FFFFFF;
			
			.tab-icon {
				color: #999;
			}
			
			.tab-text {
				color: #666;
			}
		}
	}
	
	.tool-text{ 
		font-size: 26rpx; 
		color: #666; 
	}
	
	.tool-btn{ 
		height: 64rpx; 
		padding: 0 24rpx; 
		border-radius: 8rpx; 
		display: flex; 
		align-items: center; 
		gap: 10rpx; 
		font-size: 26rpx; 
		background: #FFFFFF; 
		border: 2rpx solid #E0E0E0; 
		color: #333;
		transition: all 0.2s ease;
		
		&:active {
			opacity: 0.8;
		}
	}
	
	.tool-btn .icon{ 
		font-size: 28rpx; 
	}
	
	.refresh-btn{ 
		background: #FFE5F1; 
		border-color: #E91E63; 
		color: #E91E63;
	}
	
	.filter-btn{ 
		background: #FFFFFF; 
		border-color: #E0E0E0; 
		color: #333;
	}
	
	.list{ 
		height: calc(100vh - 260rpx); 
		padding: 0 20rpx;
	}
	
	.skeleton{ 
		padding: 40rpx; 
		text-align: center; 
		color: #999;
	}
	
	.empty{ 
		padding: 60rpx 20rpx; 
		text-align: center; 
		color: #999; 
		font-size: 26rpx;
	}
	
	/* 用户卡片 - 扁平化 */
	.card{ 
		display: flex; 
		background: #FFFFFF; 
		border-radius: 12rpx; 
		padding: 20rpx; 
		margin: 16rpx 0; 
		border: 2rpx solid #E0E0E0;
		transition: all 0.2s ease;
		
		&:active {
			background: #F5F5F5;
		}
	}
	
	.avatar{ 
		width: 140rpx; 
		height: 140rpx; 
		border-radius: 12rpx; 
		background: #F5F5F5;
		border: 2rpx solid #E0E0E0;
	}
	
	.main{ 
		flex: 1; 
		padding: 0 16rpx;
	}
	
	.row{ 
		display: flex; 
		align-items: center; 
		justify-content: space-between;
	}
	
	.name{ 
		font-size: 32rpx; 
		font-weight: 600; 
		color: #333;
	}
	
	.score{ 
		font-size: 28rpx; 
		color: #E91E63;
	}
	
	.score-badge{ 
		min-width: 80rpx; 
		text-align: center; 
		padding: 6rpx 16rpx; 
		border-radius: 8rpx; 
		background: #FFE5F1; 
		color: #E91E63; 
		font-size: 26rpx; 
		font-weight: 600;
	}
	
	.meta{ 
		display: flex; 
		gap: 16rpx; 
		font-size: 24rpx; 
		color: #666; 
		margin-top: 8rpx;
	}
	
	.tags{ 
		display: flex; 
		flex-wrap: wrap; 
		gap: 10rpx; 
		margin-top: 10rpx;
	}
	
	.tag{ 
		background: #F5F5F5; 
		color: #666; 
		padding: 6rpx 12rpx; 
		border-radius: 6rpx; 
		font-size: 22rpx;
		border: 1rpx solid #E0E0E0;
	}
	
	.actions{ 
		display: flex; 
		flex-direction: column; 
		gap: 10rpx; 
		justify-content: center;
	}
	
	.act-btn{ 
		border-radius: 8rpx; 
		padding: 0 20rpx; 
		height: 56rpx; 
		line-height: 56rpx; 
		font-size: 24rpx;
		transition: all 0.2s ease;
		
		&:active {
			opacity: 0.8;
		}
	}
	.tabbar-badge {
	  position: absolute;
	  top: 8rpx;
	  right: 25%;
	  min-width: 36rpx;
	  height: 36rpx;
	  line-height: 36rpx;
	  padding: 0 8rpx;
	  background: #FF6B6B;
	  color: #FFFFFF;
	  font-size: 20rpx;
	  font-weight: bold;
	  border-radius: 18rpx;
	  text-align: center;
	}
	.act-btn.ghost{ 
		background: #F5F5F5; 
		color: #666;
		border: 2rpx solid #E0E0E0;
	}
	
	.act-btn.primary{ 
		background: #E91E63; 
		color: #FFFFFF;
		border: none;
	}

	/* 底部导航栏 - 扁平化 */
	.tabbar {
				position: fixed;
				bottom: 0;
				left: 0;
				right: 0;
				display: flex;
				background-color: #FFFFFF;
				border-top: 1rpx solid #F0F0F0;
				padding-bottom: constant(safe-area-inset-bottom);
				padding-bottom: env(safe-area-inset-bottom);
				z-index: 999;
				box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

				.tabbar-item {
					flex: 1;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					padding: 15rpx 0;
					position: relative;

					.tabbar-icon {
						font-size: 44rpx;
						margin-bottom: 5rpx;
					}

					.tabbar-text {
						font-size: 22rpx;
						color: #666666;
					}

					&.active {
						.tabbar-text {
							color: #E91E63;
							font-weight: bold;
						}
					}
				}
			}
	
	.tabbar-item { 
		flex: 1; 
		display: flex; 
		flex-direction: column; 
		align-items: center; 
		justify-content: center; 
		padding: 18rpx 0;
		transition: all 0.2s ease;
		
		&:active {
			background: #F5F5F5;
		}
	}
	
	.tabbar-icon { 
		font-size: 46rpx; 
		margin-bottom: 8rpx;
	}
	
	.tabbar-text { 
		font-size: 22rpx; 
		color: #666666;
		font-weight: 500;
	}
	
	.tabbar-item.active {
		background: #FFE5F1;
		
		.tabbar-text { 
			color: #E91E63; 
			font-weight: 700;
		}
	}

	/* 筛选抽屉 - 扁平化 */
	.filter-sheet{ 
		background: #FFFFFF; 
		border-top-left-radius: 16rpx; 
		border-top-right-radius: 16rpx; 
		padding-bottom: env(safe-area-inset-bottom);
		border-top: 2rpx solid #E0E0E0;
	}
	
	.sheet-handle{ 
		width: 120rpx; 
		height: 8rpx; 
		background: #E0E0E0; 
		border-radius: 4rpx; 
		margin: 16rpx auto;
	}
	
	.sheet-title{ 
		text-align: center; 
		font-size: 32rpx; 
		font-weight: 600; 
		color: #333; 
		margin-bottom: 10rpx;
		padding: 0 28rpx;
		border-bottom: 2rpx solid #E0E0E0;
		padding-bottom: 16rpx;
	}
	
	.sheet-body{ 
		padding: 20rpx 28rpx; 
		max-height: 60vh; 
		overflow: auto;
	}
	
	.field{ 
		margin: 18rpx 0;
	}
	
	.field.two{ 
		display: flex; 
		align-items: center;
	}
	
	.field-label{ 
		width: 160rpx; 
		color: #666; 
		font-size: 26rpx;
		font-weight: 500;
	}
	
	.ipt{ 
		flex: 1; 
		height: 70rpx; 
		line-height: 70rpx; 
		background: #F5F5F5; 
		border-radius: 8rpx; 
		padding: 0 20rpx; 
		margin-right: 12rpx; 
		font-size: 26rpx; 
		display: flex; 
		align-items: center;
		border: 2rpx solid #E0E0E0;
	}
	
	.ipt.full{ 
		width: 100%; 
		margin-right: 0;
	}
	
	.dash{ 
		color: #999; 
		margin-right: 12rpx;
	}
	
	.seg{ 
		display: flex; 
		gap: 14rpx;
	}
	
	.seg-item{ 
		flex: 1; 
		text-align: center; 
		padding: 14rpx 0; 
		border-radius: 8rpx; 
		background: #F5F5F5; 
		color: #666; 
		font-size: 26rpx;
		border: 2rpx solid #E0E0E0;
		transition: all 0.2s ease;
	}
	
	.seg-item.active{ 
		background: #FFE5F1; 
		color: #E91E63; 
		font-weight: 600;
		border-color: #E91E63;
	}
	
	.sheet-actions{ 
		display: flex; 
		gap: 16rpx; 
		padding: 16rpx 28rpx 28rpx;
		border-top: 2rpx solid #E0E0E0;
	}
	
	.btn{ 
		flex: 1; 
		height: 80rpx; 
		border-radius: 8rpx; 
		display: flex; 
		align-items: center; 
		justify-content: center; 
		font-size: 28rpx;
		font-weight: 600;
		transition: all 0.2s ease;
		
		&:active {
			opacity: 0.8;
		}
	}
	
	.btn.ghost{ 
		background: #F5F5F5; 
		color: #666;
		border: 2rpx solid #E0E0E0;
	}
	
	.btn.primary{ 
		background: #E91E63; 
		color: #FFFFFF;
		border: none;
	}

	/* 用户详情弹窗样式 */
	.user-detail-popup {
		width: 600rpx;
		max-height: 70vh;
		background: #FFFFFF;
		border-radius: 16rpx;
		overflow: hidden;
		display: flex;
		flex-direction: column;
	}

	.popup-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 24rpx;
		border-bottom: 2rpx solid #E0E0E0;
		background: #FFFFFF;
	}

	.popup-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
	}

	.popup-close {
		font-size: 40rpx;
		color: #999;
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 50%;
		transition: all 0.2s ease;
	}

	.popup-close:active {
		background: #F5F5F5;
	}

	.popup-content {
		flex: 1;
		padding: 20rpx 24rpx;
		max-height: calc(70vh - 120rpx);
	}

	.popup-loading {
		padding: 60rpx 20rpx;
		text-align: center;
		color: #999;
		font-size: 26rpx;
	}

	.detail-section {
		margin-bottom: 32rpx;
	}

	.section-title {
		font-size: 28rpx;
		font-weight: 600;
		color: #333;
		margin-bottom: 16rpx;
		padding-bottom: 12rpx;
		border-bottom: 2rpx solid #F0F0F0;
	}

	/* 照片区域 */
	.photos-section {
		margin-bottom: 32rpx;
	}

	.photos-grid {
		display: grid;
		grid-template-columns: repeat(3, 1fr);
		gap: 12rpx;
	}

	.photo-item {
		width: 100%;
		height: 200rpx;
		border-radius: 8rpx;
		background: #F5F5F5;
		border: 2rpx solid #E0E0E0;
	}

	/* 信息网格 */
	.detail-info-grid {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 16rpx;
	}

	.info-item {
		display: flex;
		flex-direction: column;
		padding: 16rpx;
		background: #F8F9FA;
		border-radius: 8rpx;
		border: 1rpx solid #E0E0E0;
	}

	.info-label {
		font-size: 22rpx;
		color: #999;
		margin-bottom: 8rpx;
	}

	.info-value {
		font-size: 26rpx;
		color: #333;
		font-weight: 500;
	}

	/* 兴趣爱好标签 */
	.hobby-tags {
		display: flex;
		flex-wrap: wrap;
		gap: 12rpx;
	}

	.hobby-tag {
		background: #FFE5F1;
		color: #E91E63;
		padding: 10rpx 18rpx;
		border-radius: 20rpx;
		font-size: 24rpx;
		border: 1rpx solid #FFD0DC;
	}

	/* 自我简介 */
	.introduction-content {
		background: #F8F9FA;
		padding: 20rpx;
		border-radius: 8rpx;
		border-left: 4rpx solid #E91E63;
		line-height: 1.8;
	}

	.introduction-content text {
		font-size: 26rpx;
		color: #666;
		line-height: 1.8;
	}


	.tabbar-badge {
	      position: absolute;
	      top: 8rpx;
	      right: 50%;
	      margin-right: -40rpx;
	      min-width: 32rpx;
	      height: 32rpx;
	      line-height: 32rpx;
	      padding: 0 6rpx;
	      background-color: #FA5151;
	      border-radius: 16rpx;
	      font-size: 20rpx;
	      color: #FFFFFF;
	      text-align: center;
	    }

</style>

