fix:新增岗位分析五个图表

This commit is contained in:
yy
2025-06-09 11:18:07 +08:00
parent 4136170101
commit 1bb796b5ef
6 changed files with 1042 additions and 389 deletions

View File

@@ -0,0 +1,215 @@
import React from 'react';
import { Card, Select, Spin, Empty, Row, Col } from 'antd';
import { Line, Bar, Pie, Heatmap } from '@ant-design/charts';
export const IndustryTrendCard = ({
loading,
currentIndustryData,
config,
availableIndustries,
selectedIndustry,
onIndustryChange,
}) => (
<Card
title="行业趋势分析"
style={{ marginBottom: 16 }}
bodyStyle={{ padding: '12px', height: 250 }}
extra={
<Select
value={selectedIndustry}
onChange={onIndustryChange}
style={{ width: 180 }}
loading={loading}
placeholder="选择行业"
disabled={availableIndustries.length === 0}
>
{availableIndustries.map((industry: any) => (
<Option key={industry} value={industry}>
{industry}
</Option>
))}
</Select>
}
>
<Spin spinning={loading}>
{currentIndustryData.length > 0 ? (
<Line {...config} />
) : (
<Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
description={
loading
? '数据加载中...'
: selectedIndustry
? '当前时间段无数据'
: '请先选择行业'
}
/>
)}
</Spin>
</Card>
);
export const AreaAnalysisCard = ({ loading, areaData, config }) => (
<Card
title="区域分析"
style={{ marginBottom: 16 }}
bodyStyle={{
padding: 12,
height: 250,
position: 'relative',
}}
>
{loading ? (
<Spin tip="数据加载中..." size="large" />
) : areaData.length > 0 ? (
<div style={{ height: '100%', width: '100%', minHeight: 300 }}>
<Heatmap {...config} />
</div>
) : (
<Empty description="暂无区域数据" />
)}
</Card>
);
export const SalaryTrendCard = ({
loading,
currentSalaryData,
config,
availableSalaryRanges,
selectedSalaryRange,
onSalaryRangeChange,
}) => (
<Card
title="薪资区间趋势分析"
style={{ marginBottom: 16 }}
bodyStyle={{ padding: '12px', height: 250 }}
extra={
<Select
value={selectedSalaryRange}
onChange={onSalaryRangeChange}
style={{ width: 180 }}
loading={loading}
placeholder="选择薪资区间"
disabled={availableSalaryRanges.length === 0}
>
{availableSalaryRanges.map((range) => (
<Option key={range} value={range}>
{range}
</Option>
))}
</Select>
}
>
<Spin spinning={loading}>
{currentSalaryData.length > 0 ? (
<Line {...config} />
) : (
<Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
description={
loading
? '数据加载中...'
: selectedSalaryRange
? '当前时间段无数据'
: '请先选择薪资区间'
}
/>
)}
</Spin>
</Card>
);
export const WorkYearCard = ({
loading,
workYearData,
config,
availableWorkYearRanges,
selectedWorkYearRange,
onWorkYearRangeChange,
}) => (
<Card
title="工作经验要求分布"
style={{ marginBottom: 16 }}
bodyStyle={{
padding: '12px',
height: 250,
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
overflow: 'hidden',
}}
extra={
<Select
value={selectedWorkYearRange}
onChange={onWorkYearRangeChange}
style={{ width: 180 }}
loading={loading}
placeholder="选择经验要求"
disabled={availableWorkYearRanges.length === 0}
>
{availableWorkYearRanges.map((range: any) => (
<Option key={range} value={range}>
{range}
</Option>
))}
</Select>
}
>
<Spin spinning={loading}>
{workYearData && workYearData.length > 0 ? (
<div style={{ width: '100%', height: '100%', padding: 8 }}>
<Pie {...config} />
</div>
) : (
<Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
description={loading ? '数据加载中...' : '暂无工作经验数据'}
/>
)}
</Spin>
</Card>
);
export const EducationCard = ({
loading,
educationData,
config,
availableEducationLevels,
selectedEducationLevel,
onEducationLevelChange,
}) => (
<Card
title="学历要求分布"
style={{ marginBottom: 16 }}
bodyStyle={{ padding: '12px', height: 250 }}
extra={
<Select
value={selectedEducationLevel}
onChange={onEducationLevelChange}
style={{ width: 180 }}
loading={loading}
placeholder="选择学历要求"
disabled={availableEducationLevels.length === 0}
>
<Option value=""></Option>
{availableEducationLevels.map((level) => (
<Option key={level} value={level}>
{level}
</Option>
))}
</Select>
}
>
<Spin spinning={loading}>
{educationData.length > 0 ? (
<Bar {...config} />
) : (
<Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
description={loading ? '数据加载中...' : '暂无学历数据'}
/>
)}
</Spin>
</Card>
);

View File

@@ -0,0 +1,456 @@
import { ChartConfig } from '@/types/analysis/industry';
import dayjs from 'dayjs';
import { formatDateForDisplay } from '../utils';
export const getHeatmapConfig = (areaData: any[], timeDimension: string) => {
const sortedData = [...areaData].sort((a, b) => {
if (timeDimension === '年') {
return parseInt(a.time) - parseInt(b.time);
} else if (timeDimension === '季度') {
const [yearA, quarterA] = a.time.split('-Q');
const [yearB, quarterB] = b.time.split('-Q');
return yearA === yearB
? parseInt(quarterA) - parseInt(quarterB)
: parseInt(yearA) - parseInt(yearB);
} else {
return dayjs(a.time).valueOf() - dayjs(b.time).valueOf();
}
});
return {
data: sortedData,
height: 240,
autoFit: true,
xField: 'name',
yField: 'time',
colorField: 'value',
shapeField: 'square',
sizeField: 'value',
xAxis: {
title: {
text: '区域',
style: { fontSize: 12 },
},
label: {
style: {
fontSize: 10,
fill: '#666',
},
formatter: (text: string) => {
return text.length > 4 ? `${text.substring(0, 3)}...` : text;
},
},
},
yAxis: {
title: {
text: '时间',
style: { fontSize: 12 },
},
label: {
formatter: (text: string) => {
if (timeDimension === '年') return `${text}`;
if (timeDimension === '季度') return text.replace('-Q', '年Q');
return text.replace('-', '年').replace('-', '月');
},
style: {
fontSize: 10,
fill: '#666',
},
},
},
label: {
text: (d: { value: number }) => d.value.toString(),
position: 'inside',
style: {
fill: '#fff',
pointerEvents: 'none',
},
},
scale: {
size: { range: [14, 14] },
color: { range: ['#dddddd', '#9ec8e0', '#5fa4cd', '#2e7ab6', '#114d90'] },
},
tooltip: {
title: (d: { name: any; time: any }) => `${d.name} - ${d.time}`,
field: 'value',
valueFormatter: (v: number) => v.toString(),
domStyles: {
'g2-tooltip': {
padding: '8px 12px',
borderRadius: '4px',
},
},
},
interactions: [{ type: 'element-active' }],
responsive: true,
};
};
export const getIndustryChartConfig = (currentIndustryData: any[], type: string): ChartConfig => ({
data: currentIndustryData,
height: 200,
xField: 'date',
yField: 'value',
seriesField: 'category',
xAxis: {
type: 'cat',
label: {
formatter: (text: string) => text,
},
},
yAxis: {
label: {
formatter: (val: string) => `${val}${type === '招聘增长率' ? '%' : ''}`,
},
},
point: {
size: 4,
shape: 'circle',
},
animation: {
appear: {
animation: 'path-in',
duration: 1000,
},
},
smooth: true,
interactions: [
{
type: 'tooltip',
cfg: {
render: (e, { title, items }) => {
const list = items.filter((item) => item.value);
return (
<div key={title} style={{ padding: '8px 12px' }}>
<h4 style={{ marginBottom: 8 }}>{title}</h4>
{list.map((item, index) => {
const { name, value, color } = item;
return (
<div
key={index}
style={{ margin: '4px 0', display: 'flex', justifyContent: 'space-between' }}
>
<div style={{ display: 'flex', alignItems: 'center' }}>
<span
style={{
display: 'inline-block',
width: 8,
height: 8,
borderRadius: '50%',
backgroundColor: color,
marginRight: 8,
}}
></span>
<span>{name}</span>
</div>
<b>
{value}
{type === '招聘增长率' ? '%' : ''}
</b>
</div>
);
})}
</div>
);
},
},
},
],
legend: false,
tooltip: {
showTitle: undefined,
title: undefined,
customContent: undefined,
},
});
export const getSalaryChartConfig = (currentSalaryData: any[]): ChartConfig => ({
data: currentSalaryData,
height: 240,
xField: 'date',
yField: 'value',
seriesField: 'category',
xAxis: {
type: 'cat',
label: {
formatter: (text: string) => text,
},
},
yAxis: {
label: {
formatter: (val: string) => `${val}`,
},
},
point: {
size: 4,
shape: 'circle',
},
animation: {
appear: {
animation: 'path-in',
duration: 1000,
},
},
smooth: true,
interactions: [
{
type: 'tooltip',
cfg: {
render: (e, { title, items }) => {
const list = items.filter((item) => item.value);
return (
<div key={title} style={{ padding: '8px 12px' }}>
<h4 style={{ marginBottom: 8 }}>{title}</h4>
{list.map((item, index) => {
const { name, value, color } = item;
return (
<div
key={index}
style={{ margin: '4px 0', display: 'flex', justifyContent: 'space-between' }}
>
<div style={{ display: 'flex', alignItems: 'center' }}>
<span
style={{
display: 'inline-block',
width: 8,
height: 8,
borderRadius: '50%',
backgroundColor: color,
marginRight: 8,
}}
></span>
<span>{name}</span>
</div>
<b>{value}</b>
</div>
);
})}
</div>
);
},
},
},
],
legend: false,
tooltip: {
showTitle: undefined,
title: undefined,
customContent: undefined,
},
});
export const getWorkYearPieConfig = (workYearData: any[], selectedWorkYearRange: string) => {
const filteredData = workYearData
.filter((item) => item.category === selectedWorkYearRange)
.map((item) => ({
...item,
date: formatDateForDisplay(item.date, '月'),
value: item.value || 0,
type: `${formatDateForDisplay(item.date, '月')} ${item.category}`,
}));
return {
data: filteredData,
angleField: 'value',
colorField: 'type',
radius: 0.2,
innerRadius: 0.5,
label: {
text: (d: { type: any; value: any }) => `${d.type}\n ${d.value}`,
position: 'spider',
},
legend: false,
tooltip: {
showTitle: true,
title: '工作经验分布',
fields: ['type', 'value'],
formatter: (datum: { type: any; value: any }) => ({
name: datum.type,
value: datum.value,
}),
},
interactions: [{ type: 'element-active' }],
padding: 'auto',
autoFit: true,
};
};
export const getEducationBarConfig = (educationData: any[], selectedEducationLevel: string) => {
const educationLevelOrder = [
'不限',
'初中及以下',
'中专/中技',
'高中',
'大专',
'本科',
'硕士',
'博士',
'MBA/EMBA',
'留学-学士',
'留学-硕士',
'留学-博士',
];
const educationColorMap: Record<string, string> = {
: '#8884d8',
: '#82ca9d',
'中专/中技': '#ffc658',
: '#ff8042',
: '#0088FE',
: '#00C49F',
: '#FFBB28',
: '#FF8042',
'MBA/EMBA': '#8884d8',
'留学-学士': '#82ca9d',
'留学-硕士': '#ffc658',
'留学-博士': '#ff8042',
};
const cleanEducationData = educationData
.filter((item) => item && item.category && item.date && !isNaN(item.value))
.map((item) => ({
...item,
date: formatDateForDisplay(item.date, '月'),
category: item.category || '不限',
value: Number(item.value) || 0,
}));
if (!selectedEducationLevel) {
const educationSummary: Record<string, number> = {};
cleanEducationData.forEach((item) => {
if (!educationSummary[item.category]) {
educationSummary[item.category] = 0;
}
educationSummary[item.category] += item.value;
});
const barData = Object.entries(educationSummary)
.filter(([_, value]) => value > 0)
.map(([name, value]) => ({
name,
value,
color: educationColorMap[name] || '#999',
}))
.sort((a, b) => educationLevelOrder.indexOf(a.name) - educationLevelOrder.indexOf(b.name));
return {
data: barData,
height: 200,
xField: 'value',
yField: 'name',
seriesField: 'name',
color: ({ name }: { name: string }) => educationColorMap[name] || '#999',
meta: {
name: { alias: '学历要求' },
value: { alias: '岗位数量' },
},
xAxis: {
label: {
formatter: (val: string) => `${val}`,
},
grid: {
line: {
style: {
stroke: '#f0f0f0',
lineDash: [4, 4],
},
},
},
},
yAxis: {
label: {
formatter: (text: string) => text,
},
},
barStyle: {
radius: [2, 2, 0, 0],
},
tooltip: {
showTitle: true,
title: '学历要求分布',
fields: ['name', 'value'],
formatter: (datum: { name: any; value: any }) => ({
name: datum.name,
value: datum.value,
}),
domStyles: {
'g2-tooltip': {
background: 'rgba(255, 255, 255, 0.9)',
boxShadow: '0 2px 8px rgba(0, 0, 0, 0.15)',
borderRadius: '4px',
},
},
},
interactions: [{ type: 'element-active' }],
legend: false,
animation: {
appear: {
animation: 'scale-in-y',
duration: 1000,
},
},
};
}
const timeData = cleanEducationData
.filter((item) => item.category === selectedEducationLevel)
.sort((a, b) => {
const dateA = dayjs(a.date, 'YYYY年MM月').valueOf();
const dateB = dayjs(b.date, 'YYYY年MM月').valueOf();
return dateA - dateB;
});
return {
data: timeData,
height: 200,
xField: 'date',
yField: 'value',
seriesField: 'category',
color: educationColorMap[selectedEducationLevel] || '#999',
meta: {
date: {
alias: '时间',
type: 'cat',
values: timeData
.map((item) => item.date)
.sort((a, b) => {
const dateA = dayjs(a, 'YYYY年MM月').valueOf();
const dateB = dayjs(b, 'YYYY年MM月').valueOf();
return dateA - dateB;
}),
},
value: { alias: '岗位数量' },
},
barStyle: {
radius: [2, 2, 0, 0],
},
tooltip: {
showTitle: true,
title: `${selectedEducationLevel}趋势`,
fields: ['date', 'value'],
formatter: (datum: { date: any; value: any }) => ({ name: datum.date, value: datum.value }),
domStyles: {
'g2-tooltip': {
background: 'rgba(255, 255, 255, 0.9)',
boxShadow: '0 2px 8px rgba(0, 0, 0, 0.15)',
borderRadius: '4px',
},
},
},
interactions: [{ type: 'element-active' }],
legend: false,
animation: {
appear: {
animation: 'scale-in-y',
duration: 1000,
},
},
xAxis: {
type: 'cat',
label: {
formatter: (text: string) => text,
},
},
};
};

View File

@@ -1,7 +1,13 @@
import React, { useEffect, useState, useMemo, useRef } from 'react'; import React, { useEffect, useState, useMemo, useRef } from 'react';
import { Card, Select, Button, Space, Spin, Empty, Row, Col, message, DatePicker, Tabs } from 'antd'; import { Card, Select, Button, Space, Spin, Empty, Row, Col, message, DatePicker } from 'antd';
import { Line, Heatmap } from '@ant-design/charts'; import { Line, Bar, Pie, Heatmap } from '@ant-design/charts';
import { getIndustryTrend, getIndustryAreaTrend, getSalaryTrend } from '@/services/analysis/industry'; import {
getIndustryTrend,
getIndustryAreaTrend,
getSalaryTrend,
getWorkYearTrend,
getEducationTrend,
} from '@/services/analysis/industry';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import { useRequest } from '@umijs/max'; import { useRequest } from '@umijs/max';
import { import {
@@ -11,24 +17,44 @@ import {
IndustryDataItem, IndustryDataItem,
ChartConfig, ChartConfig,
} from '@/types/analysis/industry'; } from '@/types/analysis/industry';
import { formatQuarter, formatDateForDisplay, convertApiData, convertSalaryData } from './utils'; import {
formatQuarter,
formatDateForDisplay,
convertApiData,
convertSalaryData,
convertWorkYearData,
convertEducationData,
} from './utils';
import {
getHeatmapConfig,
getIndustryChartConfig,
getSalaryChartConfig,
getWorkYearPieConfig,
getEducationBarConfig,
} from './components/chartconfigs';
import {
IndustryTrendCard,
AreaAnalysisCard,
SalaryTrendCard,
WorkYearCard,
EducationCard,
} from './components/chartcards';
const { Option } = Select; const { Option } = Select;
const { RangePicker } = DatePicker; const { RangePicker } = DatePicker;
const { TabPane } = Tabs;
const flattenAreaData = (apiResponse: any) => { const flattenAreaData = (apiResponse: any) => {
if (!apiResponse || typeof apiResponse !== 'object') { if (!apiResponse || typeof apiResponse !== 'object') {
return []; return [];
} }
const flattenedData = []; const flattenedData: { name: any; time: any; value: number }[] = [];
for (const month in apiResponse) { for (const month in apiResponse) {
if (apiResponse.hasOwnProperty(month)) { if (apiResponse.hasOwnProperty(month)) {
const areas = apiResponse[month]; const areas = apiResponse[month];
areas.forEach((area) => { areas.forEach((area: { name: any; time: any; data: string }) => {
flattenedData.push({ flattenedData.push({
name: area.name, name: area.name,
time: area.time, time: area.time,
@@ -49,7 +75,7 @@ const IndustryTrendPage: React.FC = () => {
endTime: dayjs().format('YYYY-MM'), endTime: dayjs().format('YYYY-MM'),
selectedIndustry: '', selectedIndustry: '',
selectedSalaryRange: '', selectedSalaryRange: '',
analysisCategory: 'industry', // 默认显示行业分析 selectedWorkYearRange: '',
}); });
const [allData, setAllData] = useState<IndustryDataItem[]>([]); const [allData, setAllData] = useState<IndustryDataItem[]>([]);
@@ -58,6 +84,12 @@ const IndustryTrendPage: React.FC = () => {
const [availableIndustries, setAvailableIndustries] = useState<string[]>([]); const [availableIndustries, setAvailableIndustries] = useState<string[]>([]);
const [availableSalaryRanges, setAvailableSalaryRanges] = useState<string[]>([]); const [availableSalaryRanges, setAvailableSalaryRanges] = useState<string[]>([]);
const heatmapRef = useRef(null); const heatmapRef = useRef(null);
const containerRef = useRef<HTMLDivElement>(null);
const [workYearData, setWorkYearData] = useState<any[]>([]);
const [availableWorkYearRanges, setAvailableWorkYearRanges] = useState<string[]>([]);
const [educationData, setEducationData] = useState<any[]>([]);
const [availableEducationLevels, setAvailableEducationLevels] = useState<string[]>([]);
const [selectedEducationLevel, setSelectedEducationLevel] = useState<string>('');
// 获取行业趋势数据 // 获取行业趋势数据
const { loading: industryLoading, run: fetchIndustryData } = useRequest( const { loading: industryLoading, run: fetchIndustryData } = useRequest(
@@ -130,16 +162,14 @@ const IndustryTrendPage: React.FC = () => {
// 获取薪资趋势数据 // 获取薪资趋势数据
const { loading: salaryLoading, run: fetchSalaryData } = useRequest( const { loading: salaryLoading, run: fetchSalaryData } = useRequest(
async () => { async () => {
let { startTime, endTime, timeDimension, type } = params; const now = dayjs();
let startTime = now.subtract(1, 'year').format('YYYY-MM');
if (timeDimension === '季度') { let endTime = now.format('YYYY-MM');
startTime = formatQuarter(startTime); const timeDimension = '月';
endTime = formatQuarter(endTime);
}
return await getSalaryTrend({ return await getSalaryTrend({
timeDimension, timeDimension,
type, type: '岗位发布数量',
startTime, startTime,
endTime, endTime,
}); });
@@ -152,7 +182,10 @@ const IndustryTrendPage: React.FC = () => {
const ranges = Array.from(new Set(formattedData.map((item: any) => item.category))) const ranges = Array.from(new Set(formattedData.map((item: any) => item.category)))
.filter(Boolean) .filter(Boolean)
.sort(); .sort((a, b) => {
const extractNumber = (str: string) => parseInt(str.replace(/[^0-9]/g, '') || 0);
return extractNumber(a) - extractNumber(b);
});
setAvailableSalaryRanges(ranges); setAvailableSalaryRanges(ranges);
@@ -166,183 +199,180 @@ const IndustryTrendPage: React.FC = () => {
}, },
); );
// 根据分析类别获取当前数据 // 获取工作年限数据
const currentData = useMemo(() => { const { loading: workYearLoading, run: fetchWorkYearData } = useRequest(
if (params.analysisCategory === 'industry') { async () => {
return allData const now = dayjs();
.filter((item) => item.category === params.selectedIndustry) let startTime = now.subtract(1, 'year').format('YYYY-MM');
.map((item) => ({ let endTime = now.format('YYYY-MM');
...item, const timeDimension = '月';
originalDate: item.date,
date: formatDateForDisplay(item.date, params.timeDimension),
}))
.sort((a, b) => {
if (params.timeDimension === '季度') {
const [yearA, quarterA] = a.originalDate.split('-');
const [yearB, quarterB] = b.originalDate.split('-');
const quarterToNumber = (q: string) => { return await getWorkYearTrend({
if (q.includes('第一')) return 1; timeDimension,
if (q.includes('第二')) return 2; type: '岗位发布数量',
if (q.includes('第三')) return 3; startTime,
if (q.includes('第四')) return 4; endTime,
return 0; });
}; },
{
manual: true,
onSuccess: (data) => {
const formattedData = convertWorkYearData(data);
setWorkYearData(formattedData);
return yearA === yearB const ranges = Array.from(new Set(formattedData.map((item: any) => item.category)))
? quarterToNumber(quarterA) - quarterToNumber(quarterB) .filter(Boolean)
: parseInt(yearA) - parseInt(yearB); .sort((a, b) => {
} else if (params.timeDimension === '年') { const order = ['应届', '1-3年', '3-5年', '5年以上'];
return parseInt(a.originalDate) - parseInt(b.originalDate); return order.indexOf(a) - order.indexOf(b);
} else { });
return dayjs(a.originalDate).valueOf() - dayjs(b.originalDate).valueOf();
}
});
} else if (params.analysisCategory === 'salary') {
return salaryData
.filter((item) => item.category === params.selectedSalaryRange)
.map((item) => ({
...item,
originalDate: item.date,
date: formatDateForDisplay(item.date, params.timeDimension),
}))
.sort((a, b) => {
if (params.timeDimension === '季度') {
const [yearA, quarterA] = a.originalDate.split('-');
const [yearB, quarterB] = b.originalDate.split('-');
const quarterToNumber = (q: string) => { setAvailableWorkYearRanges(ranges);
if (q.includes('第一')) return 1; if (ranges.length > 0 && !ranges.includes(params.selectedWorkYearRange)) {
if (q.includes('第二')) return 2; setParams((p) => ({ ...p, selectedWorkYearRange: ranges[0] }));
if (q.includes('第三')) return 3; }
if (q.includes('第四')) return 4;
return 0;
};
return yearA === yearB
? quarterToNumber(quarterA) - quarterToNumber(quarterB)
: parseInt(yearA) - parseInt(yearB);
} else if (params.timeDimension === '年') {
return parseInt(a.originalDate) - parseInt(b.originalDate);
} else {
return dayjs(a.originalDate).valueOf() - dayjs(b.originalDate).valueOf();
}
});
}
return [];
}, [allData, salaryData, params]);
// 热力图配置
const heatmapConfig = useMemo(() => {
const sortedData = [...areaData].sort((a, b) => {
if (params.timeDimension === '年') {
return parseInt(a.time) - parseInt(b.time);
} else if (params.timeDimension === '季度') {
const [yearA, quarterA] = a.time.split('-Q');
const [yearB, quarterB] = b.time.split('-Q');
return yearA === yearB
? parseInt(quarterA) - parseInt(quarterB)
: parseInt(yearA) - parseInt(yearB);
} else {
return dayjs(a.time).valueOf() - dayjs(b.time).valueOf();
}
});
// 计算最大值和阈值
const maxValue = Math.max(...sortedData.map((item) => item.value), 1);
const hotThreshold = maxValue * 0.8; // 热门阈值(前20%)
const growthThreshold = maxValue * 0.5; // 增长阈值(前50%)
return {
data: sortedData,
height: 300,
autoFit: false,
xField: 'name',
yField: 'time',
colorField: 'value',
mark: 'cell',
style: {
inset: 1,
fillOpacity: 0.9,
}, },
cellSize: [100, 40], onError: (error) => {
color: ['#5B8FF9', '#5AD8A6', '#5D7092', '#F6BD16', '#E8684A'], message.error('工作经验数据加载失败');
label: {
text: (d: { value: number }) => {
if (d.value >= 10000) return (d.value / 10000).toFixed(0) + 'w';
if (d.value >= 1000) return (d.value / 1000).toFixed(0) + 'k';
return d.value;
},
style: {
fill: '#fff',
fontSize: 12,
fontWeight: 'bold',
textShadow: '0 0 3px rgba(0,0,0,0.7)',
},
position: 'inside',
}, },
xAxis: { },
title: { );
text: '区域',
style: { fontSize: 12 }, // 获取学历数据
}, const { loading: educationLoading, run: fetchEducationData } = useRequest(
label: { async () => {
autoRotate: true, const now = dayjs();
style: { let startTime = now.subtract(1, 'year').format('YYYY-MM');
fontSize: 11, let endTime = now.format('YYYY-MM');
fill: '#666', const timeDimension = '月';
},
}, return await getEducationTrend({
timeDimension,
type: '岗位发布数量',
startTime,
endTime,
});
},
{
manual: true,
onSuccess: (data) => {
const formattedData = convertEducationData(data);
setEducationData(formattedData);
const levels = Array.from(new Set(formattedData.map((item: any) => item.category)))
.filter(Boolean)
.sort((a, b) => {
const order = ['不限', '初中及以下', '中专/中技', '大专', '本科', '硕士', '博士'];
return order.indexOf(a) - order.indexOf(b);
});
setAvailableEducationLevels(levels);
if (levels.length > 0 && !levels.includes(selectedEducationLevel)) {
setSelectedEducationLevel(levels[0]);
}
}, },
yAxis: { onError: (error) => {
title: { message.error('学历数据加载失败');
text: '时间',
style: { fontSize: 12 },
},
label: {
formatter: (text) => {
if (params.timeDimension === '年') return `${text}`;
if (params.timeDimension === '季度') return text.replace('-Q', '年Q');
return text.replace('-', '年').replace('-', '月');
},
style: {
fontSize: 11,
fill: '#666',
},
},
sortable: false,
}, },
tooltip: { },
title: (d) => `${d.name} - ${d.time}`, );
field: 'value',
valueFormatter: (v) => { const currentWorkYearData = useMemo(() => {
if (v >= 10000) return (v / 10000).toFixed(1) + '万'; if (!params.selectedWorkYearRange || workYearData.length === 0) return [];
if (v >= 1000) return (v / 1000).toFixed(1) + '千';
return v; return workYearData
}, .filter((item) => item.category === params.selectedWorkYearRange)
pointerEvents: 'none', .map((item) => ({
domStyles: { ...item,
'g2-tooltip': { originalDate: item.date,
padding: '8px 12px', date: formatDateForDisplay(item.date, '月'),
borderRadius: '4px', }))
}, .sort((a, b) => dayjs(a.originalDate).valueOf() - dayjs(b.originalDate).valueOf());
}, }, [workYearData, params.selectedWorkYearRange]);
},
interactions: [{ type: 'element-active' }], const currentIndustryData = useMemo(() => {
legend: { if (!params.selectedIndustry || allData.length === 0) return [];
position: 'bottom',
layout: 'horizontal', return allData
slidable: true, .filter((item) => item.category === params.selectedIndustry)
title: false, .map((item) => ({
itemName: { ...item,
style: { originalDate: item.date,
fill: '#666', date: formatDateForDisplay(item.date, params.timeDimension),
fontSize: 12, }))
}, .sort((a, b) => {
}, if (params.timeDimension === '季度') {
}, const [yearA, quarterA] = a.originalDate.split('-');
}; const [yearB, quarterB] = b.originalDate.split('-');
}, [areaData, params.timeDimension]);
const quarterToNumber = (q: string) => {
if (q.includes('第一')) return 1;
if (q.includes('第二')) return 2;
if (q.includes('第三')) return 3;
if (q.includes('第四')) return 4;
return 0;
};
return yearA === yearB
? quarterToNumber(quarterA) - quarterToNumber(quarterB)
: parseInt(yearA) - parseInt(yearB);
} else if (params.timeDimension === '年') {
return parseInt(a.originalDate) - parseInt(b.originalDate);
} else {
return dayjs(a.originalDate).valueOf() - dayjs(b.originalDate).valueOf();
}
});
}, [allData, params.selectedIndustry, params.timeDimension]);
const currentSalaryData = useMemo(() => {
if (!params.selectedSalaryRange || salaryData.length === 0) return [];
return salaryData
.filter((item) => item.category === params.selectedSalaryRange)
.map((item) => ({
...item,
originalDate: item.date,
date: formatDateForDisplay(item.date, '月'),
}))
.sort((a, b) => dayjs(a.originalDate).valueOf() - dayjs(b.originalDate).valueOf());
}, [salaryData, params.selectedSalaryRange]);
const currentEducationData = useMemo(() => {
if (!selectedEducationLevel || educationData.length === 0) return [];
return educationData
.filter((item) => item.category === selectedEducationLevel)
.map((item) => ({
...item,
originalDate: item.date,
date: formatDateForDisplay(item.date, '月'),
}))
.sort((a, b) => dayjs(a.originalDate).valueOf() - dayjs(b.originalDate).valueOf());
}, [educationData, selectedEducationLevel]);
const heatmapConfig = useMemo(
() => getHeatmapConfig(areaData, params.timeDimension),
[areaData, params.timeDimension],
);
const industryChartConfig = useMemo(
() => getIndustryChartConfig(currentIndustryData, params.type),
[currentIndustryData, params.type],
);
const salaryChartConfig = useMemo(
() => getSalaryChartConfig(currentSalaryData),
[currentSalaryData],
);
const workYearPieConfig = useMemo(
() => getWorkYearPieConfig(workYearData, params.selectedWorkYearRange),
[workYearData, params.selectedWorkYearRange],
);
const educationBarConfig = useMemo(
() => getEducationBarConfig(educationData, selectedEducationLevel),
[educationData, selectedEducationLevel],
);
const handleTimeDimensionChange = (value: TimeDimension) => { const handleTimeDimensionChange = (value: TimeDimension) => {
const now = dayjs(); const now = dayjs();
@@ -366,8 +396,7 @@ const IndustryTrendPage: React.FC = () => {
: value === '季度' : value === '季度'
? now.format('YYYY-Q') ? now.format('YYYY-Q')
: now.format('YYYY'), : now.format('YYYY'),
selectedIndustry: params.analysisCategory === 'industry' ? '' : p.selectedIndustry, selectedIndustry: '',
selectedSalaryRange: params.analysisCategory === 'salary' ? '' : p.selectedSalaryRange,
})); }));
}; };
@@ -418,146 +447,19 @@ const IndustryTrendPage: React.FC = () => {
} }
}; };
const chartConfig: ChartConfig = {
data: currentData,
height: 180,
xField: 'date',
yField: 'value',
seriesField: 'category',
xAxis: {
type: 'cat',
label: {
formatter: (text: string) => text,
},
},
yAxis: {
label: {
formatter: (val: string) => `${val}${params.type === '招聘增长率' ? '%' : ''}`,
},
},
point: {
size: 4,
shape: 'circle',
},
animation: {
appear: {
animation: 'path-in',
duration: 1000,
},
},
smooth: true,
interactions: [
{
type: 'tooltip',
cfg: {
render: (e, { title, items }) => {
const list = items.filter((item) => item.value);
return (
<div key={title} style={{ padding: '8px 12px' }}>
<h4 style={{ marginBottom: 8 }}>{title}</h4>
{list.map((item, index) => {
const { name, value, color } = item;
return (
<div
key={index}
style={{ margin: '4px 0', display: 'flex', justifyContent: 'space-between' }}
>
<div style={{ display: 'flex', alignItems: 'center' }}>
<span
style={{
display: 'inline-block',
width: 8,
height: 8,
borderRadius: '50%',
backgroundColor: color,
marginRight: 8,
}}
></span>
<span>{name}</span>
</div>
<b>
{value}
{params.type === '招聘增长率' ? '%' : ''}
</b>
</div>
);
})}
</div>
);
},
},
},
],
legend: false,
tooltip: {
showTitle: undefined,
title: undefined,
customContent: undefined,
},
};
useEffect(() => { useEffect(() => {
if (params.analysisCategory === 'industry') { fetchIndustryData();
fetchIndustryData(); fetchAreaData();
fetchAreaData(); fetchSalaryData();
} else if (params.analysisCategory === 'salary') { fetchWorkYearData();
fetchSalaryData(); fetchEducationData();
fetchAreaData(); }, [params.timeDimension, params.startTime, params.endTime, params.type]);
}
}, [params.timeDimension, params.startTime, params.endTime, params.type, params.analysisCategory]);
return ( return (
<div style={{ padding: 16 }}> <div style={{ padding: 16 }} ref={containerRef}>
<Card title="趋势分析" style={{ marginBottom: 24 }}> <Card title="趋势分析" style={{ marginBottom: 24 }}>
<Tabs
activeKey={params.analysisCategory}
onChange={(key) => setParams(p => ({
...p,
analysisCategory: key as 'industry' | 'salary' | 'area',
selectedIndustry: key === 'industry' && availableIndustries.length > 0 ? availableIndustries[0] : p.selectedIndustry,
selectedSalaryRange: key === 'salary' && availableSalaryRanges.length > 0 ? availableSalaryRanges[0] : p.selectedSalaryRange
}))}
>
<TabPane tab="行业趋势" key="industry" />
<TabPane tab="薪资趋势" key="salary" />
</Tabs>
<div style={{ marginBottom: 24 }}> <div style={{ marginBottom: 24 }}>
<Space size="middle" wrap> <Space size="middle" wrap>
{params.analysisCategory === 'industry' && (
<Select
value={params.selectedIndustry}
onChange={(value) => setParams((p) => ({ ...p, selectedIndustry: value }))}
style={{ width: 150 }}
loading={industryLoading}
placeholder="选择行业"
disabled={availableIndustries.length === 0}
>
{availableIndustries.map((industry) => (
<Option key={industry} value={industry}>
{industry}
</Option>
))}
</Select>
)}
{params.analysisCategory === 'salary' && (
<Select
value={params.selectedSalaryRange}
onChange={(value) => setParams((p) => ({ ...p, selectedSalaryRange: value }))}
style={{ width: 150 }}
loading={salaryLoading}
placeholder="选择薪资区间"
disabled={availableSalaryRanges.length === 0}
>
{availableSalaryRanges.map((range) => (
<Option key={range} value={range}>
{range}
</Option>
))}
</Select>
)}
<Select <Select
value={params.timeDimension} value={params.timeDimension}
onChange={handleTimeDimensionChange} onChange={handleTimeDimensionChange}
@@ -579,7 +481,7 @@ const IndustryTrendPage: React.FC = () => {
value={getPickerValue()} value={getPickerValue()}
onChange={handleDateRangeChange} onChange={handleDateRangeChange}
style={{ width: 180 }} style={{ width: 180 }}
disabled={industryLoading || areaLoading || salaryLoading} disabled={industryLoading || areaLoading}
allowClear={false} allowClear={false}
disabledDate={disabledDate} disabledDate={disabledDate}
/> />
@@ -596,15 +498,10 @@ const IndustryTrendPage: React.FC = () => {
<Button <Button
type="primary" type="primary"
onClick={() => { onClick={() => {
if (params.analysisCategory === 'industry') { fetchIndustryData();
fetchIndustryData(); fetchAreaData();
fetchAreaData();
} else if (params.analysisCategory === 'salary') {
fetchSalaryData();
fetchAreaData();
}
}} }}
loading={industryLoading || areaLoading || salaryLoading} loading={industryLoading || areaLoading}
> >
</Button> </Button>
@@ -612,60 +509,57 @@ const IndustryTrendPage: React.FC = () => {
</div> </div>
<Row gutter={[16, 16]}> <Row gutter={[16, 16]}>
{params.analysisCategory !== 'area' && ( {/* 行业趋势图表 - 全宽显示 */}
<Col span={24}> <Col xs={24} lg={24}>
<Card <IndustryTrendCard
title={ loading={industryLoading}
params.analysisCategory === 'industry' currentIndustryData={currentIndustryData}
? `${params.selectedIndustry || '请选择行业'}趋势 (${params.type})` config={industryChartConfig}
: `${params.selectedSalaryRange || '请选择薪资区间'}趋势 (${params.type})` availableIndustries={availableIndustries}
} selectedIndustry={params.selectedIndustry}
style={{ marginBottom: 24 }} onIndustryChange={(value) => setParams((p) => ({ ...p, selectedIndustry: value }))}
bodyStyle={{ padding: '24px 12px', height: 210 }} />
> </Col>
<Spin spinning={params.analysisCategory === 'industry' ? industryLoading : salaryLoading}>
{currentData.length > 0 ? (
<Line {...chartConfig} />
) : (
<Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
description={
industryLoading || salaryLoading
? '数据加载中...'
: params.analysisCategory === 'industry'
? params.selectedIndustry
? '当前时间段无数据'
: '请先选择行业'
: params.selectedSalaryRange
? '当前时间段无数据'
: '请先选择薪资区间'
}
/>
)}
</Spin>
</Card>
</Col>
)}
<Col span={24}> {/* 区域分析和薪资趋势 - 中等屏幕下分成两列 */}
<Card <Col xs={24} md={12} lg={12}>
title="区域分析" <AreaAnalysisCard loading={areaLoading} areaData={areaData} config={heatmapConfig} />
bodyStyle={{ </Col>
padding: 12, <Col xs={24} md={12} lg={12}>
height: 400, <SalaryTrendCard
position: 'relative', loading={salaryLoading}
}} currentSalaryData={currentSalaryData}
> config={salaryChartConfig}
{areaLoading ? ( availableSalaryRanges={availableSalaryRanges}
<Spin tip="数据加载中..." size="large" /> selectedSalaryRange={params.selectedSalaryRange}
) : areaData.length > 0 ? ( onSalaryRangeChange={(value) =>
<div style={{ height: '100%', width: '100%' }}> setParams((p) => ({ ...p, selectedSalaryRange: value }))
<Heatmap {...heatmapConfig} /> }
</div> />
) : ( </Col>
<Empty description="暂无区域数据" />
)} {/* 工作经验和学历要求 - 中等屏幕下分成两列 */}
</Card> <Col xs={24} md={12} lg={12}>
<WorkYearCard
loading={workYearLoading}
workYearData={workYearData}
config={workYearPieConfig}
availableWorkYearRanges={availableWorkYearRanges}
selectedWorkYearRange={params.selectedWorkYearRange}
onWorkYearRangeChange={(value) =>
setParams((p) => ({ ...p, selectedWorkYearRange: value }))
}
/>
</Col>
<Col xs={24} md={12} lg={12}>
<EducationCard
loading={educationLoading}
educationData={educationData}
config={educationBarConfig}
availableEducationLevels={availableEducationLevels}
selectedEducationLevel={selectedEducationLevel}
onEducationLevelChange={setSelectedEducationLevel}
/>
</Col> </Col>
</Row> </Row>
</Card> </Card>

View File

@@ -159,3 +159,74 @@ export const convertSalaryData: ApiDataConverter = (apiData: any) => {
return []; return [];
} }
}; };
export const convertWorkYearData: ApiDataConverter = (apiData: any) => {
if (!apiData) return [];
try {
if (Array.isArray(apiData)) {
return apiData.map(item => ({
date: item.time || item.date || '',
category: item.name || item.category || '未知经验要求',
value: Number(item.data || item.value || 0) // 确保数值不为null/undefined
}));
}
if (typeof apiData === 'object') {
const result: IndustryDataItem[] = [];
Object.entries(apiData).forEach(([date, items]) => {
if (Array.isArray(items)) {
items.forEach((item: any) => {
result.push({
date: date || '',
category: item.name || item.category || '未知经验要求',
value: Number(item.data || item.value || 0) // 确保数值不为null/undefined
});
});
}
});
return result;
}
return [];
} catch (error) {
console.error('工作经验数据转换错误:', error);
return [];
}
};
export const convertEducationData: ApiDataConverter = (apiData: any) => {
if (!apiData) return [];
try {
const result: any[] = [];
// 处理嵌套的月份数据
if (typeof apiData === 'object' && !Array.isArray(apiData)) {
Object.entries(apiData).forEach(([date, items]) => {
if (Array.isArray(items)) {
items.forEach((item: any) => {
if (!item) return; // 跳过空项
result.push({
date: date || '', // 确保日期不为undefined
category: item.name || item.category || '不限', // 默认值
value: Number(item.data || item.value || 0), // 确保数值有效
originalData: item
});
});
}
});
return result;
}
// 处理数组格式的响应
if (Array.isArray(apiData)) {
return apiData.map(item => ({
date: item.time || item.date || '',
category: item.name || item.category || '不限',
value: Number(item.data || item.value || 0),
originalData: item
}));
}
return [];
} catch (error) {
console.error('学历数据转换错误:', error);
return [];
}
};

View File

@@ -1,11 +1,12 @@
import { request } from '@umijs/max'; import { request } from '@umijs/max';
// 行业
export async function getIndustryTrend(params?: API.Analysis.IndustryParams) { export async function getIndustryTrend(params?: API.Analysis.IndustryParams) {
return request<API.Analysis.IndustryResult>('/api/cms/statics/industry', { return request<API.Analysis.IndustryResult>('/api/cms/statics/industry', {
method: 'GET', method: 'GET',
params params
}); });
} }
// 区域热力图
export async function getIndustryAreaTrend(params: any) { export async function getIndustryAreaTrend(params: any) {
try { try {
const response = await request('/api/cms/statics/industryArea', { const response = await request('/api/cms/statics/industryArea', {
@@ -23,10 +24,24 @@ export async function getIndustryAreaTrend(params: any) {
throw error; throw error;
} }
} }
// 薪资
export async function getSalaryTrend(params?: API.Analysis.IndustryParams) { export async function getSalaryTrend(params?: API.Analysis.IndustryParams) {
return request<API.Analysis.IndustryResult>('/api/cms/statics/salary', { return request<API.Analysis.IndustryResult>('/api/cms/statics/salary', {
method: 'GET', method: 'GET',
params params
}); });
} }
// 工作年限
export async function getWorkYearTrend(params?: API.Analysis.IndustryParams) {
return request<API.Analysis.IndustryResult>('/api/cms/statics/workYear', {
method: 'GET',
params
});
}
// 学历趋势
export async function getEducationTrend(params?: API.Analysis.IndustryParams) {
return request<API.Analysis.IndustryResult>('/api/cms/statics/education', {
method: 'GET',
params
});
}

View File

@@ -6,7 +6,8 @@ export type AnalysisType = '岗位发布数量' | '招聘增长率';
export type QuarterFormat = `${number}-${'Q1'|'Q2'|'Q3'|'Q4'|'第一季度'|'第二季度'|'第三季度'|'第四季度'}`; export type QuarterFormat = `${number}-${'Q1'|'Q2'|'Q3'|'Q4'|'第一季度'|'第二季度'|'第三季度'|'第四季度'}`;
export type AnalysisCategory = 'industry' | 'area' | 'salary'; export type AnalysisCategory = 'industry' | 'area' | 'salary';
export type SalaryRange = '3k-5k' | '5k-8k' | '8k-10k' | '10k+'; export type SalaryRange = '3k-5k' | '5k-8k' | '8k-10k' | '10k+';
export type WorkYearRange = '应届' | '1-3年' | '3-5年' | '5年以上';
export type EducationLevel = '大专' | '本科' | '硕士' | '博士' | '不限';
export interface IndustryDataItem { export interface IndustryDataItem {
date: string; date: string;
category: string; category: string;
@@ -26,6 +27,7 @@ export interface IndustryTrendParams {
} }
export interface IndustryTrendState extends IndustryTrendParams { export interface IndustryTrendState extends IndustryTrendParams {
selectedWorkYearRange(): unknown;
selectedIndustry: string; selectedIndustry: string;
} }