Files
monkey-ai-web/src/components/analytics/UserSurveyStats.jsx
T
zhanjunhao 8a48765a46 chore(repo): 移除重复版权文件头并纳入共享单测
集中保留原版权声明,移除文件头检查和全局测试忽略规则。验证:全量单测、受影响用例复测及静态检查通过。
2026-11-20 11:23:49 +08:00

590 lines
22 KiB
React

import { formatPercent, formatRatioPercent } from '../../helpers/safeDisplay';
import React, { useMemo, useState, useEffect, useCallback } from 'react';
import { Card, Spin, Tag, Progress } from '@/components/ui';
import CollapsibleHeader from './CollapsibleHeader';
import { VChart } from '@visactor/react-vchart';
import { API, showError } from '../../helpers';
import {
Briefcase,
Cpu,
Users,
TrendingUp,
BarChart3,
PieChart,
} from 'lucide-react';
// 职业类型标签配置
const JOB_TYPE_CONFIG = {
1: { label: '技术岗位', color: 'blue', icon: '💻', desc: '开发/测试/运维等' },
2: {
label: '技术周边',
color: 'green',
icon: '🎨',
desc: '产品/设计/运营等',
},
3: { label: '其他行业', color: 'orange', icon: '🏢', desc: '非IT行业' },
};
// AI工具使用标签配置
const AI_TOOL_CONFIG = {
1: { label: '正在使用', color: 'green', icon: '🚀', desc: '活跃用户' },
2: { label: '了解/尝试过', color: 'blue', icon: '🔍', desc: '潜在用户' },
3: { label: '有兴趣', color: 'orange', icon: '✨', desc: '待转化' },
4: { label: '暂不需要', color: 'grey', icon: '💤', desc: '观望用户' },
};
const UserSurveyStats = ({ title, icon, t }) => {
const [loading, setLoading] = useState(false);
const [surveyStats, setSurveyStats] = useState(null);
const [surveyTrend, setSurveyTrend] = useState([]);
const [collapsed, setCollapsed] = useState(true); // 默认折叠
// 获取统计数据
const fetchSurveyStats = useCallback(async () => {
try {
const res = await API.get('/api/analytics/survey/stats');
if (res.data.success) {
setSurveyStats(res.data.data);
} else {
showError(res.data.message);
}
} catch (error) {
console.error('获取问卷统计失败:', error);
}
}, []);
// 获取趋势数据
const fetchSurveyTrend = useCallback(async () => {
try {
const res = await API.get('/api/analytics/survey/trend');
if (res.data.success) {
setSurveyTrend(res.data.data || []);
}
} catch (error) {
console.error('获取问卷趋势失败:', error);
}
}, []);
// 初始加载
useEffect(() => {
const loadData = async () => {
setLoading(true);
await Promise.all([fetchSurveyStats(), fetchSurveyTrend()]);
setLoading(false);
};
loadData();
}, [fetchSurveyStats, fetchSurveyTrend]);
// 职业分布饼图配置
const jobTypePieSpec = useMemo(() => {
if (!surveyStats?.job_type_stats || surveyStats.job_type_stats.length === 0)
return null;
const chartData = surveyStats.job_type_stats.map((item) => ({
name: t(JOB_TYPE_CONFIG[item.job_type]?.label || '未知'),
value: item.count,
percentage: item.percentage,
}));
return {
type: 'pie',
data: [{ id: 'jobType', values: chartData }],
valueField: 'value',
categoryField: 'name',
outerRadius: 0.8,
innerRadius: 0.5,
padAngle: 0.02,
pie: {
style: {
cornerRadius: 4,
},
},
tooltip: {
mark: {
content: [
{
key: (datum) => datum?.name,
value: (datum) =>
t('{{n}} 人', {
n: datum?.value || 0,
count: datum?.value || 0,
}),
},
{
key: () => t('占比'),
value: (datum) => formatPercent(datum?.percentage || 0, 1),
},
],
},
},
legends: {
visible: true,
position: 'bottom',
orient: 'horizontal',
},
label: {
visible: true,
position: 'outside',
content: '{name}',
},
color: ['#3b82f6', '#10b981', '#f59e0b'],
};
}, [surveyStats, t]);
// AI工具使用饼图配置
const aiToolPieSpec = useMemo(() => {
if (!surveyStats?.ai_tool_stats || surveyStats.ai_tool_stats.length === 0)
return null;
const chartData = surveyStats.ai_tool_stats.map((item) => ({
name: t(AI_TOOL_CONFIG[item.ai_tool_usage]?.label || '未知'),
value: item.count,
percentage: item.percentage,
}));
return {
type: 'pie',
data: [{ id: 'aiTool', values: chartData }],
valueField: 'value',
categoryField: 'name',
outerRadius: 0.8,
innerRadius: 0.5,
padAngle: 0.02,
pie: {
style: {
cornerRadius: 4,
},
},
tooltip: {
mark: {
content: [
{
key: (datum) => datum?.name,
value: (datum) =>
t('{{n}} 人', {
n: datum?.value || 0,
count: datum?.value || 0,
}),
},
{
key: () => t('占比'),
value: (datum) => formatPercent(datum?.percentage || 0, 1),
},
],
},
},
legends: {
visible: true,
position: 'bottom',
orient: 'horizontal',
},
label: {
visible: true,
position: 'outside',
content: '{name}',
},
color: ['#10b981', '#3b82f6', '#f59e0b', '#9ca3af'],
};
}, [surveyStats, t]);
// 趋势图配置
const trendSpec = useMemo(() => {
if (!surveyTrend || surveyTrend.length === 0) return null;
const chartData = [...surveyTrend].reverse().map((item) => ({
date: item.date,
count: item.count,
}));
return {
type: 'bar',
data: [{ id: 'trend', values: chartData }],
xField: 'date',
yField: 'count',
bar: {
style: {
cornerRadius: [4, 4, 0, 0],
fill: {
gradient: 'linear',
x0: 0,
y0: 0,
x1: 0,
y1: 1,
stops: [
{ offset: 0, color: '#8b5cf6' },
{ offset: 1, color: '#6366f1' },
],
},
},
},
tooltip: {
mark: {
content: [
{
key: () => t('日期'),
value: (datum) => datum?.date,
},
{
key: () => t('新增'),
value: (datum) =>
t('{{n}} 人', {
n: datum?.count || 0,
count: datum?.count || 0,
}),
},
],
},
},
axes: [
{
orient: 'bottom',
label: {
autoRotate: true,
autoRotateAngle: [0, 45],
},
},
{
orient: 'left',
label: {
formatMethod: (v) => Math.round(v),
},
},
],
};
}, [surveyTrend, t]);
// 计算统计数据
const totalUsers = surveyStats?.total || 0;
const techUsers =
surveyStats?.job_type_stats?.find((s) => s.job_type === 1)?.count || 0;
const activeAIUsers =
surveyStats?.ai_tool_stats?.find((s) => s.ai_tool_usage === 1)?.count || 0;
const interestedUsers =
surveyStats?.ai_tool_stats?.find((s) => s.ai_tool_usage === 3)?.count || 0;
return (
<div className='analytics-fold-panel'>
<CollapsibleHeader
icon={icon}
title={title}
isOpen={!collapsed}
onToggle={() => setCollapsed((value) => !value)}
extra={
<>
{totalUsers > 0 && (
<Tag color='purple' size='small'>
{t('{{n}} 人已填写', { n: totalUsers, count: totalUsers })}
</Tag>
)}
</>
}
/>
<div className={collapsed ? 'hidden' : ''}>
<Card
className='analytics-fold-content shadow-sm'
styles={{ body: { padding: '16px' } }}
>
{!collapsed && (
<Spin spinning={loading}>
{totalUsers === 0 ? (
<div className='h-[300px] flex items-center justify-center text-gray-400'>
{t('暂无数据')}
</div>
) : (
<div className='space-y-6'>
{/* 概览统计卡片 */}
<div className='grid grid-cols-2 sm:grid-cols-4 gap-4'>
<div className='p-4 bg-gradient-to-br from-brand-from/5 to-brand-to/5 dark:from-brand-from/20 dark:to-brand-to/20 rounded-xl'>
<div className='flex items-center gap-2 mb-2'>
<Users className='w-4 h-4 text-brand' />
<span className='text-xs text-gray-500 dark:text-gray-400'>
{t('总填写')}
</span>
</div>
<div className='text-2xl font-bold text-brand-deep dark:text-brand-from'>
{totalUsers}
</div>
</div>
<div className='p-4 bg-gradient-to-br from-blue-50 to-cyan-50 dark:from-blue-900/20 dark:to-cyan-900/20 rounded-xl'>
<div className='flex items-center gap-2 mb-2'>
<Briefcase className='w-4 h-4 text-blue-500' />
<span className='text-xs text-gray-500 dark:text-gray-400'>
{t('技术岗位')}
</span>
</div>
<div className='text-2xl font-bold text-blue-600 dark:text-blue-400'>
{techUsers}
</div>
<div className='text-xs text-gray-400 mt-1'>
{formatRatioPercent(techUsers, totalUsers, 1, '0.0%')}
</div>
</div>
<div className='p-4 bg-gradient-to-br from-green-50 to-emerald-50 dark:from-green-900/20 dark:to-emerald-900/20 rounded-xl'>
<div className='flex items-center gap-2 mb-2'>
<Cpu className='w-4 h-4 text-green-500' />
<span className='text-xs text-gray-500 dark:text-gray-400'>
{t('正在使用AI')}
</span>
</div>
<div className='text-2xl font-bold text-green-600 dark:text-green-400'>
{activeAIUsers}
</div>
<div className='text-xs text-gray-400 mt-1'>
{formatRatioPercent(
activeAIUsers,
totalUsers,
1,
'0.0%',
)}
</div>
</div>
<div className='p-4 bg-gradient-to-br from-orange-50 to-amber-50 dark:from-orange-900/20 dark:to-amber-900/20 rounded-xl'>
<div className='flex items-center gap-2 mb-2'>
<TrendingUp className='w-4 h-4 text-orange-500' />
<span className='text-xs text-gray-500 dark:text-gray-400'>
{t('有兴趣尝试')}
</span>
</div>
<div className='text-2xl font-bold text-orange-600 dark:text-orange-400'>
{interestedUsers}
</div>
<div className='text-xs text-gray-400 mt-1'>
{formatRatioPercent(
interestedUsers,
totalUsers,
1,
'0.0%',
)}
</div>
</div>
</div>
{/* 图表区域 */}
<div className='grid grid-cols-1 lg:grid-cols-2 gap-6'>
{/* 职业分布 */}
<div className='bg-gray-50 dark:bg-gray-800/50 rounded-xl p-4'>
<div className='flex items-center gap-2 mb-4'>
<PieChart className='w-4 h-4 text-blue-500' />
<span className='font-medium text-gray-700 dark:text-gray-300'>
{t('职业分布')}
</span>
</div>
{jobTypePieSpec ? (
<>
<VChart
spec={jobTypePieSpec}
option={{ mode: 'desktop-browser' }}
style={{ height: 180 }}
/>
<div className='mt-3 space-y-2'>
{surveyStats?.job_type_stats?.map((item) => {
const config = JOB_TYPE_CONFIG[item.job_type];
return (
<div
key={item.job_type}
className='flex items-center justify-between'
>
<div className='flex items-center gap-2'>
<span className='text-lg'>
{config?.icon}
</span>
<span className='text-sm text-gray-600 dark:text-gray-400'>
{t(config?.label || '')}
</span>
</div>
<div className='flex items-center gap-2'>
<Progress
percent={item.percentage}
size='small'
style={{ width: 60 }}
showInfo={false}
stroke={
config?.color === 'blue'
? '#3b82f6'
: config?.color === 'green'
? '#10b981'
: '#f59e0b'
}
/>
<span className='text-sm font-medium w-12 text-right'>
{item.count}
</span>
</div>
</div>
);
})}
</div>
</>
) : (
<div className='h-[200px] flex items-center justify-center text-gray-400'>
{t('暂无数据')}
</div>
)}
</div>
{/* AI工具使用情况 */}
<div className='bg-gray-50 dark:bg-gray-800/50 rounded-xl p-4'>
<div className='flex items-center gap-2 mb-4'>
<PieChart className='w-4 h-4 text-green-500' />
<span className='font-medium text-gray-700 dark:text-gray-300'>
{t('AI工具使用情况')}
</span>
</div>
{aiToolPieSpec ? (
<>
<VChart
spec={aiToolPieSpec}
option={{ mode: 'desktop-browser' }}
style={{ height: 180 }}
/>
<div className='mt-3 space-y-2'>
{surveyStats?.ai_tool_stats?.map((item) => {
const config = AI_TOOL_CONFIG[item.ai_tool_usage];
const colors = {
green: '#10b981',
blue: '#3b82f6',
orange: '#f59e0b',
grey: '#9ca3af',
};
return (
<div
key={item.ai_tool_usage}
className='flex items-center justify-between'
>
<div className='flex items-center gap-2'>
<span className='text-lg'>
{config?.icon}
</span>
<span className='text-sm text-gray-600 dark:text-gray-400'>
{t(config?.label || '')}
</span>
</div>
<div className='flex items-center gap-2'>
<Progress
percent={item.percentage}
size='small'
style={{ width: 60 }}
showInfo={false}
stroke={
colors[config?.color] || '#9ca3af'
}
/>
<span className='text-sm font-medium w-12 text-right'>
{item.count}
</span>
</div>
</div>
);
})}
</div>
</>
) : (
<div className='h-[200px] flex items-center justify-center text-gray-400'>
{t('暂无数据')}
</div>
)}
</div>
</div>
{/* 填写趋势 */}
<div className='bg-gray-50 dark:bg-gray-800/50 rounded-xl p-4'>
<div className='flex items-center gap-2 mb-4'>
<BarChart3 className='w-4 h-4 text-brand' />
<span className='font-medium text-gray-700 dark:text-gray-300'>
{t('近30天填写趋势')}
</span>
</div>
{trendSpec ? (
<VChart
spec={trendSpec}
option={{ mode: 'desktop-browser' }}
style={{ height: 200 }}
/>
) : (
<div className='h-[200px] flex items-center justify-center text-gray-400'>
{t('暂无数据')}
</div>
)}
</div>
{/* 交叉分析表格 */}
{surveyStats?.cross_analysis &&
surveyStats.cross_analysis.length > 0 && (
<div className='bg-gray-50 dark:bg-gray-800/50 rounded-xl p-4'>
<div className='flex items-center gap-2 mb-4'>
<BarChart3 className='w-4 h-4 text-brand' />
<span className='font-medium text-gray-700 dark:text-gray-300'>
{t('交叉分析')}
</span>
</div>
<div className='overflow-x-auto'>
<table className='w-full text-sm'>
<thead>
<tr className='border-b border-gray-200 dark:border-gray-700'>
<th className='text-left py-2 px-3 font-medium text-gray-600 dark:text-gray-400'>
{t('职业类型')}
</th>
<th className='text-left py-2 px-3 font-medium text-gray-600 dark:text-gray-400'>
{t('AI工具使用')}
</th>
<th className='text-right py-2 px-3 font-medium text-gray-600 dark:text-gray-400'>
{t('人数')}
</th>
</tr>
</thead>
<tbody>
{surveyStats.cross_analysis.map((item, index) => (
<tr
key={index}
className='border-b border-gray-100 dark:border-gray-700/50 last:border-0'
>
<td className='py-2 px-3'>
<div className='flex items-center gap-2'>
<span>
{JOB_TYPE_CONFIG[item.job_type]?.icon}
</span>
<span className='text-gray-700 dark:text-gray-300'>
{t(
JOB_TYPE_CONFIG[item.job_type]
?.label || '',
)}
</span>
</div>
</td>
<td className='py-2 px-3'>
<Tag
color={
AI_TOOL_CONFIG[item.ai_tool_usage]
?.color
}
size='small'
>
{t(
AI_TOOL_CONFIG[item.ai_tool_usage]
?.label || '',
)}
</Tag>
</td>
<td className='py-2 px-3 text-right font-medium'>
{item.count}
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
</div>
)}
</Spin>
)}
</Card>
</div>
</div>
);
};
export default UserSurveyStats;