"use client" import { useState, useEffect } from "react" import { motion, AnimatePresence } from "framer-motion" import { Users, X, CheckCircle, Loader2, Lock, Zap, Gift } from "lucide-react" import { Home, List, User } from "lucide-react" import { useRouter } from "next/navigation" import { useStore } from "@/lib/store" interface MatchUser { id: string nickname: string avatar: string tags: string[] matchScore: number concept: string wechat: string commonInterests: Array<{ icon: string; text: string }> } const matchTypes = [ { id: "partner", label: "创业合伙", matchLabel: "创业伙伴", icon: "⭐", color: "#00E5FF", matchFromDB: true, showJoinAfterMatch: false }, { id: "investor", label: "资源对接", matchLabel: "资源对接", icon: "👥", color: "#7B61FF", matchFromDB: false, showJoinAfterMatch: true }, { id: "mentor", label: "导师顾问", matchLabel: "商业顾问", icon: "❤️", color: "#E91E63", matchFromDB: false, showJoinAfterMatch: true }, { id: "team", label: "团队招募", matchLabel: "加入项目", icon: "🎮", color: "#4CAF50", matchFromDB: false, showJoinAfterMatch: true }, ] const FREE_MATCH_LIMIT = 1 // 每日免费匹配次数改为1次 const MATCH_UNLOCK_PRICE = 1 // 每次解锁需要购买1个小节 // 获取本地存储的联系方式 const getStoredContact = (): { phone: string; wechat: string } => { if (typeof window !== "undefined") { return { phone: localStorage.getItem("user_phone") || "", wechat: localStorage.getItem("user_wechat") || "", } } return { phone: "", wechat: "" } } // 获取今日匹配次数 const getTodayMatchCount = (): number => { if (typeof window !== "undefined") { const today = new Date().toISOString().split('T')[0] const stored = localStorage.getItem("match_count_data") if (stored) { const data = JSON.parse(stored) if (data.date === today) { return data.count } } } return 0 } // 保存今日匹配次数 const saveTodayMatchCount = (count: number) => { if (typeof window !== "undefined") { const today = new Date().toISOString().split('T')[0] localStorage.setItem("match_count_data", JSON.stringify({ date: today, count })) } } // 保存联系方式到本地存储 const saveContact = (phone: string, wechat: string) => { if (typeof window !== "undefined") { if (phone) localStorage.setItem("user_phone", phone) if (wechat) localStorage.setItem("user_wechat", wechat) } } export default function MatchPage() { const [mounted, setMounted] = useState(false) const [isMatching, setIsMatching] = useState(false) const [currentMatch, setCurrentMatch] = useState(null) const [matchAttempts, setMatchAttempts] = useState(0) const [selectedType, setSelectedType] = useState("partner") const [todayMatchCount, setTodayMatchCount] = useState(0) const router = useRouter() const { user, isLoggedIn, purchaseSection } = useStore() const [showJoinModal, setShowJoinModal] = useState(false) const [showUnlockModal, setShowUnlockModal] = useState(false) const [joinType, setJoinType] = useState(null) const [phoneNumber, setPhoneNumber] = useState("") const [wechatId, setWechatId] = useState("") const [contactType, setContactType] = useState<"phone" | "wechat">("phone") const [isJoining, setIsJoining] = useState(false) const [joinSuccess, setJoinSuccess] = useState(false) const [joinError, setJoinError] = useState("") const [isUnlocking, setIsUnlocking] = useState(false) // 检查用户是否有购买权限(购买过任意内容) const hasPurchased = user?.hasFullBook || (user?.purchasedSections && user.purchasedSections.length > 0) // 总共获得的匹配次数 = 每日免费(1) + 已购小节数量 // 如果购买了全书,则拥有无限匹配机会 const totalMatchesAllowed = user?.hasFullBook ? 999999 : FREE_MATCH_LIMIT + (user?.purchasedSections?.length || 0) // 剩余可用次数 const matchesRemaining = user?.hasFullBook ? 999999 : Math.max(0, totalMatchesAllowed - todayMatchCount) // 是否需要付费(总次数用完) const needPayToMatch = !user?.hasFullBook && matchesRemaining <= 0 // 初始化 useEffect(() => { setMounted(true) const storedContact = getStoredContact() if (storedContact.phone) { setPhoneNumber(storedContact.phone) } if (storedContact.wechat) { setWechatId(storedContact.wechat) } if (user?.phone) { setPhoneNumber(user.phone) } // 读取今日匹配次数 setTodayMatchCount(getTodayMatchCount()) }, [user]) if (!mounted) return null // 彻底解决 Hydration 错误 const handleJoinClick = (typeId: string) => { setJoinType(typeId) setShowJoinModal(true) setJoinSuccess(false) setJoinError("") } const handleJoinSubmit = async () => { const contact = contactType === "phone" ? phoneNumber : wechatId if (contactType === "phone" && (!phoneNumber || phoneNumber.length !== 11)) { setJoinError("请输入正确的11位手机号") return } if (contactType === "wechat" && (!wechatId || wechatId.length < 6)) { setJoinError("请输入正确的微信号(至少6位)") return } setIsJoining(true) setJoinError("") try { const response = await fetch("/api/ckb/join", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ type: joinType, phone: contactType === "phone" ? phoneNumber : "", wechat: contactType === "wechat" ? wechatId : "", userId: user?.id, }), }) const result = await response.json() if (result.success) { saveContact(phoneNumber, wechatId) setJoinSuccess(true) setTimeout(() => { setShowJoinModal(false) setJoinSuccess(false) }, 2000) } else { setJoinError(result.message || "加入失败,请稍后重试") } } catch (error) { setJoinError("网络错误,请检查网络后重试") } finally { setIsJoining(false) } } // 购买解锁匹配次数 const handleUnlockMatch = async () => { if (!isLoggedIn) { alert("请先登录") return } setIsUnlocking(true) try { // 模拟购买过程,实际应该调用支付API // 这里简化为直接购买成功 await new Promise((resolve) => setTimeout(resolve, 1500)) // 购买成功后重置今日匹配次数(增加3次) const newCount = Math.max(0, todayMatchCount - 3) saveTodayMatchCount(newCount) setTodayMatchCount(newCount) setShowUnlockModal(false) alert("解锁成功!已获得3次匹配机会") } catch (error) { alert("解锁失败,请重试") } finally { setIsUnlocking(false) } } // 上报匹配行为到CKB const reportMatchToCKB = async (matchedUser: MatchUser) => { try { await fetch("/api/ckb/match", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ matchType: selectedType, phone: phoneNumber || user?.phone || "", wechat: wechatId || user?.wechat || "", userId: user?.id || "", nickname: user?.nickname || "", matchedUser: { id: matchedUser.id, nickname: matchedUser.nickname, matchScore: matchedUser.matchScore, }, }), }) } catch (error) { console.error("上报匹配失败:", error) } } const startMatch = () => { // 检查是否有购买权限 if (!hasPurchased) { return } // 检查是否需要付费 if (needPayToMatch) { setShowUnlockModal(true) return } setIsMatching(true) setMatchAttempts(0) setCurrentMatch(null) const interval = setInterval(() => { setMatchAttempts((prev) => prev + 1) }, 1000) setTimeout( () => { clearInterval(interval) setIsMatching(false) const matchedUser = getMockMatch() setCurrentMatch(matchedUser) // 增加今日匹配次数 const newCount = todayMatchCount + 1 setTodayMatchCount(newCount) saveTodayMatchCount(newCount) // 上报匹配行为 reportMatchToCKB(matchedUser) // 如果是需要弹出加入弹窗的类型,自动弹出 const currentType = matchTypes.find(t => t.id === selectedType) if (currentType?.showJoinAfterMatch) { setJoinType(selectedType) setShowJoinModal(true) setJoinSuccess(false) setJoinError("") } }, Math.random() * 3000 + 3000, ) } const getMockMatch = (): MatchUser => { const nicknames = ["创业先锋", "资源整合者", "私域专家", "商业导师", "连续创业者"] const randomIndex = Math.floor(Math.random() * nicknames.length) const concepts = [ "专注私域流量运营5年,帮助100+品牌实现从0到1的增长。", "连续创业者,擅长商业模式设计和资源整合。", "在Soul分享真实创业故事,希望找到志同道合的合作伙伴。", ] const wechats = ["soul_partner_1", "soul_business_2024", "soul_startup_fan"] return { id: `user_${Date.now()}`, nickname: nicknames[randomIndex], avatar: `https://picsum.photos/200/200?random=${randomIndex}`, tags: ["创业者", "私域运营", matchTypes.find((t) => t.id === selectedType)?.label || ""], matchScore: Math.floor(Math.random() * 20) + 80, concept: concepts[randomIndex % concepts.length], wechat: wechats[randomIndex % wechats.length], commonInterests: [ { icon: "📚", text: "都在读《创业实验》" }, { icon: "💼", text: "对私域运营感兴趣" }, { icon: "🎯", text: "相似的创业方向" }, ], } } const nextMatch = () => { // 检查是否需要付费 if (needPayToMatch) { setShowUnlockModal(true) return } setCurrentMatch(null) setTimeout(() => startMatch(), 500) } const handleAddWechat = () => { if (!currentMatch) return navigator.clipboard .writeText(currentMatch.wechat) .then(() => { alert(`微信号已复制:${currentMatch.wechat}\n\n请打开微信添加好友,备注"创业合作"即可。`) }) .catch(() => { alert(`微信号:${currentMatch.wechat}\n\n请手动复制并添加好友。`) }) } const currentType = matchTypes.find((t) => t.id === selectedType) const currentTypeLabel = currentType?.label || "创业合伙" const currentMatchLabel = currentType?.matchLabel || "创业伙伴" const joinTypeLabel = matchTypes.find((t) => t.id === joinType)?.matchLabel || "" return (

找伙伴

{/* 今日匹配次数显示 - 仅在总次数用完时显示 */} {hasPurchased && (
{user?.hasFullBook ? "无限匹配机会" : matchesRemaining <= 0 ? "今日匹配机会已用完" : "剩余匹配机会"}
0 ? 'text-[#00E5FF]' : 'text-red-400'}`}> {user?.hasFullBook ? "无限" : `${matchesRemaining}/${totalMatchesAllowed}`} {matchesRemaining <= 0 && !user?.hasFullBook && ( )}
)} {!isMatching && !currentMatch && ( {/* 中央匹配圆环 */} {/* 外层光环 */} {/* 中间光环 */} {/* 内层渐变球 */} {/* 内部渐变光效 */}
{/* 中心图标 */} {hasPurchased ? ( needPayToMatch ? ( <>
需要解锁
今日免费次数已用完
) : ( <>
开始匹配
匹配{currentMatchLabel}
) ) : ( <>
购买后解锁
购买9.9元即可使用
)} {/* 当前模式显示 */}

当前模式: {currentTypeLabel}

{/* 购买提示 */} {!hasPurchased && (

购买书籍解锁匹配功能

仅需9.9元,每天3次免费匹配

)} {/* 分隔线 */}
{/* 选择匹配类型 */}

选择匹配类型

{matchTypes.map((type) => ( ))}
)} {isMatching && ( {/* 匹配动画 */}
{/* 扩散波纹 */} {[1, 2, 3].map((ring) => ( ))}

正在匹配{currentMatchLabel}...

已匹配 {matchAttempts} 次

)} {currentMatch && !isMatching && ( {/* 成功动画 */} {/* 用户卡片 */}
{currentMatch.nickname}

{currentMatch.nickname}

{currentMatch.tags.map((tag) => ( {tag} ))}
{currentMatch.matchScore}%
匹配度
{/* 共同兴趣 */}

共同兴趣

{currentMatch.commonInterests.map((interest, i) => (
{interest.icon} {interest.text}
))}
{/* 核心理念 */}

核心理念

{currentMatch.concept}

{/* 操作按钮 */}
)} {/* 解锁匹配次数弹窗 */} {showUnlockModal && ( !isUnlocking && setShowUnlockModal(false)} > e.stopPropagation()} className="bg-[#1c1c1e] rounded-2xl w-full max-w-sm overflow-hidden" >

匹配机会已用完

每购买一个小节内容即可额外获得1次匹配机会

解锁方式 购买任意小节
获得次数 +1次匹配
)}
{/* 加入类型弹窗 */} {showJoinModal && ( !isJoining && setShowJoinModal(false)} > e.stopPropagation()} className="bg-[#1c1c1e] rounded-2xl w-full max-w-sm overflow-hidden" > {/* 弹窗头部 */}

加入{joinTypeLabel}

{/* 弹窗内容 */}
{joinSuccess ? (

加入成功!

我们会尽快与您联系

) : ( <>

{user?.phone ? "已检测到您的绑定信息,可直接提交或修改" : "请填写您的联系方式以便我们联系您"}

{/* 联系方式类型切换 */}
{/* 联系方式输入 */}
{contactType === "phone" ? ( setPhoneNumber(e.target.value.replace(/\D/g, "").slice(0, 11))} placeholder="请输入11位手机号" className="w-full px-4 py-3 rounded-xl bg-black/30 border border-white/10 text-white placeholder-white/30 focus:outline-none focus:border-[#00E5FF]/50" disabled={isJoining} /> ) : ( setWechatId(e.target.value)} placeholder="请输入微信号" className="w-full px-4 py-3 rounded-xl bg-black/30 border border-white/10 text-white placeholder-white/30 focus:outline-none focus:border-[#07C160]/50" disabled={isJoining} /> )}
{/* 错误提示 */} {joinError &&

{joinError}

} {/* 提交按钮 */}

提交即表示同意我们的服务条款

)}
)}
) }