import React, { useState, useEffect, useRef } from 'react';
import {
User,
ChevronRight,
Loader2,
BrainCircuit,
BarChart3,
Heart,
ShieldAlert,
Briefcase,
Share2,
Copy,
RefreshCcw,
Plus,
ArrowRight,
MessageSquare,
Sparkles
} from 'lucide-react';
const apiKey = ""; // 运行时由环境自动填充
const App = () => {
const [step, setStep] = useState('welcome'); // welcome, profile, quiz, loading, report
const [profile, setProfile] = useState({
name: 'Reese',
age: '',
gender: '',
job: '',
extra: ''
});
const [questions, setQuestions] = useState([]);
const [answers, setAnswers] = useState([]);
const [currentQuestion, setCurrentQuestion] = useState(null);
const [loading, setLoading] = useState(false);
const [report, setReport] = useState(null);
const [shareImage, setShareImage] = useState(null);
const [showMenu, setShowMenu] = useState(false);
// 模拟重试机制的 API 调用函数
const fetchGemini = async (payload, endpoint = 'generateContent', model = 'gemini-2.5-flash-preview-09-2025') => {
let delay = 1000;
for (let i = 0; i < 5; i++) {
try {
const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${model}:${endpoint}?key=${apiKey}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (!response.ok) throw new Error('API Error');
return await response.json();
} catch (err) {
if (i === 4) throw err;
await new Promise(resolve => setTimeout(resolve, delay));
delay *= 2;
}
}
};
// 生成下一道题
const generateNextQuestion = async (history) => {
setLoading(true);
const questionIndex = history.length + 1;
const systemPrompt = `你是一位资深心理学专家。正在为用户 ${profile.name} 进行EQ评估。
当前进度:[第${questionIndex}/20题]。
要求:
1. 必须是封闭式情境选择题,提供A,B,C,D四个选项。
2. 题目要根据之前的回答动态调整深度(之前的记录:${JSON.stringify(history)})。
3. 维度覆盖:情绪感知、管理、社交直觉、人际处理、抗压能力。
4. 输出JSON格式:{ "question": "...", "options": { "A": "...", "B": "...", "C": "...", "D": "..." }, "dimension": "..." }`;
try {
const data = await fetchGemini({
contents: [{ parts: [{ text: `为 ${JSON.stringify(profile)} 生成第 ${questionIndex} 道情商测试题。` }] }],
systemInstruction: { parts: [{ text: systemPrompt }] },
generationConfig: { responseMimeType: "application/json" }
});
const q = JSON.parse(data.candidates[0].content.parts[0].text);
setCurrentQuestion(q);
setLoading(false);
} catch (error) {
console.error(error);
setLoading(false);
}
};
// 生成最终报告
const generateFullReport = async (finalAnswers) => {
setStep('loading');
const systemPrompt = `你是一位资深心理学专家。请根据用户 ${JSON.stringify(profile)} 的20道EQ测试回答:${JSON.stringify(finalAnswers)},撰写一份不少于1000字的《深度心理评估报告》。
报告结构必须包含:
1. EQ雷达图维度分析(情绪颗粒度,共情力,社交手腕等)。
2. 真实性格画像(挖掘面具下的潜意识性格)。
3. 亲密关系/婚姻模式预判。
4. 未来走向建议(职业瓶颈突破与人生关键决策建议)。
请使用专业、优雅且深刻的中文。输出格式为JSON:{"title": "...", "radarData": {"情绪感知": 80, ...}, "content": "Markdown格式的详细正文"}`;
try {
const data = await fetchGemini({
contents: [{ parts: [{ text: "生成完整评估报告" }] }],
systemInstruction: { parts: [{ text: systemPrompt }] },
generationConfig: { responseMimeType: "application/json" }
});
const result = JSON.parse(data.candidates[0].content.parts[0].text);
setReport(result);
setStep('report');
} catch (error) {
console.error(error);
}
};
// 生成分享图片
const generateImage = async () => {
setLoading(true);
const prompt = `A high-end psychological profile card for a user named ${profile.name} who scored high in EQ. Minimalist, professional, abstract psychological art style, teal and gold accents, clear typography.`;
try {
const result = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/imagen-4.0-generate-001:predict?key=${apiKey}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ instances: { prompt: prompt }, parameters: { sampleCount: 1 } })
}).then(res => res.json());
if (result.predictions?.[0]?.bytesBase64Encoded) {
setShareImage(`data:image/png;base64,${result.predictions[0].bytesBase64Encoded}`);
}
} catch (err) {
console.error(err);
}
setLoading(false);
};
const handleAnswer = (option) => {
const newAnswers = [...answers, { question: currentQuestion.question, answer: option, dimension: currentQuestion.dimension }];
setAnswers(newAnswers);
if (newAnswers.length < 20) {
generateNextQuestion(newAnswers);
} else {
generateFullReport(newAnswers);
}
};
const startQuiz = () => {
setStep('quiz');
generateNextQuestion([]);
};
return (
{/* Header */}
{/* Welcome Screen */}
{step === 'welcome' && (
你好, Reese
我是你的专属心理学专家。我们将通过20轮深度交互,探索你潜意识中的情商边界,揭示那些你甚至未曾察觉的自我特质。
)}
{/* Profile Info */}
{step === 'profile' && (
)}
{/* Quiz Step */}
{step === 'quiz' && (
{loading || !currentQuestion ? (
) : (
{currentQuestion.dimension || "情商评估"}
[第{answers.length + 1}/20题]
{currentQuestion.question}
{Object.entries(currentQuestion.options).map(([key, value]) => (
))}
)}
{/* Progress Bar */}
)}
{/* Loading Report */}
{step === 'loading' && (
深度报告生成中
专家正在梳理您的20条交互数据,构建全维度人格模型...
正在计算:情绪颗粒度、共情共振指数、压力代偿机制...
)}
{/* Final Report */}
{step === 'report' && report && (
ASSESSMENT COMPLETE
{report.title || "深度心理评估报告"}
评估对象: {profile.name} | 日期: {new Date().toLocaleDateString()}
{/* Radar Analysis */}
EQ全维度模型
{Object.entries(report.radarData).map(([key, val]) => (
))}
{/* Main Content */}
') }} />
{/* Share Card (Imagen) */}
{shareImage && (
这是根据您的评估结果生成的专属灵魂画像
)}
{/* Bottom Actions */}
)}
{/* Floating Plus Menu */}
{step === 'report' && (
{showMenu && (
)}
)}
{/* Custom Keyframes for Shimmer */}
);
};
export default App;