添加日期选择器

This commit is contained in:
yy
2025-05-26 12:19:08 +08:00
parent 7e8d7d3409
commit fa577431b8

View File

@@ -1,76 +1,122 @@
import React, { useEffect, useState, useMemo } from 'react'; import React, { useEffect, useState, useMemo } from 'react';
import { Card, Select, Button, Space, Spin, Empty, Row, Col, message } from 'antd'; import { Card, Select, Button, Space, Spin, Empty, Row, Col, message, DatePicker } from 'antd';
import { Line } from '@ant-design/charts'; import { Line } from '@ant-design/charts';
import { getIndustryTrend } from '@/services/analysis/industry'; import { getIndustryTrend } from '@/services/analysis/industry';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import { useRequest } from '@umijs/max'; import { useRequest } from '@umijs/max';
const { Option } = Select; const { Option } = Select;
const { RangePicker } = DatePicker;
type IndustryDataItem = { type IndustryDataItem = {
date: string; date: string;
category: string; category: string;
value: number; value: number;
}; };
const formatDateForDisplay = (dateStr: string, dimension: string): string => {
try {
if (dimension === '年') {
return dateStr.split('-')[0];
}
if (dimension === '季度') {
const [year, quarter] = dateStr.split('-Q');
return `${year}年Q${quarter}`;
}
// 默认按月显示
const [year, month] = dateStr.split('-');
return `${year}${month}`;
} catch (e) {
console.error('日期格式化错误:', e);
return dateStr;
}
};
const IndustryTrendPage: React.FC = () => { const IndustryTrendPage: React.FC = () => {
const [params, setParams] = useState({ const [params, setParams] = useState({
timeDimension: '月' as '月' | '季度' | '年', timeDimension: '月' as '月' | '季度' | '年',
type: '岗位发布数量' as '岗位发布数量' | '招聘增长率', type: '岗位发布数量' as '岗位发布数量' | '招聘增长率',
startTime: dayjs().subtract(6, 'month').format('YYYY-MM'), startTime: dayjs().subtract(5, 'month').format('YYYY-MM'),
endTime: dayjs().format('YYYY-MM'), endTime: dayjs().format('YYYY-MM'),
selectedIndustry: '' selectedIndustry: ''
}); });
const [allData, setAllData] = useState<IndustryDataItem[]>([]); const [allData, setAllData] = useState<IndustryDataItem[]>([]);
const [prevSelectedIndustry, setPrevSelectedIndustry] = useState(''); const [availableIndustries, setAvailableIndustries] = useState<string[]>([]);
const { loading, run } = useRequest( const { loading, run: fetchData } = useRequest(
() => getIndustryTrend({ async () => {
...params, try {
const resp = await getIndustryTrend({
timeDimension: params.timeDimension,
type: params.type,
startTime: formatTimeParam(params.startTime, params.timeDimension), startTime: formatTimeParam(params.startTime, params.timeDimension),
endTime: formatTimeParam(params.endTime, params.timeDimension) endTime: formatTimeParam(params.endTime, params.timeDimension)
}), });
return resp;
} catch (error) {
message.error('数据加载失败');
throw error;
}
},
{ {
manual: true, manual: true,
onError: (error) => message.error('数据加载失败: ' + error.message), onSuccess: (data) => {
onSuccess: (responseData) => { const formattedData = convertApiData(data);
const formattedData = convertApiData(responseData);
setAllData(formattedData); setAllData(formattedData);
const industryToSelect = prevSelectedIndustry || const industries = Array.from(
(formattedData.length > 0 ? formattedData[0].category : ''); new Set(formattedData.map(item => item.category))
setParams(prev => ({ ...prev, selectedIndustry: industryToSelect })); ).filter(Boolean).sort();
setAvailableIndustries(industries);
if (industries.length > 0 && !industries.includes(params.selectedIndustry)) {
setParams(p => ({ ...p, selectedIndustry: industries[0] }));
}
} }
} }
); );
const formatTimeParam = (dateStr: string, dimension: string): string => {
try {
const date = dayjs(dateStr);
switch (dimension) {
case '季度':
return `${date.year()}-Q${Math.ceil((date.month() + 1) / 3)}`;
case '年':
return `${date.year()}`;
default:
return date.format('YYYY-MM');
}
} catch (e) {
console.error('日期参数格式化错误:', e);
return dateStr;
}
};
const convertApiData = (apiData: any): IndustryDataItem[] => { const convertApiData = (apiData: any): IndustryDataItem[] => {
if (!apiData) return []; if (!apiData) return [];
try { try {
const result: IndustryDataItem[] = []; if (Array.isArray(apiData)) {
if (typeof apiData === 'object' && !Array.isArray(apiData)) { return apiData.map(item => ({
Object.entries(apiData).forEach(([month, monthData]) => { date: item.time || item.date,
if (Array.isArray(monthData)) { category: item.name || item.category || '未知行业',
(monthData as any[]).forEach(item => {
const convertedItem = {
date: month,
category: item.name || item.category,
value: Number(item.data || item.value) || 0 value: Number(item.data || item.value) || 0
}; }));
console.log('转换后的数据项:', convertedItem); }
result.push(convertedItem); if (typeof apiData === 'object') {
const result: IndustryDataItem[] = [];
Object.entries(apiData).forEach(([date, items]) => {
if (Array.isArray(items)) {
items.forEach((item: any) => {
result.push({
date,
category: item.name || item.category || '未知行业',
value: Number(item.data || item.value) || 0
});
}); });
} }
}); });
return result; return result;
} }
if (Array.isArray(apiData)) {
return apiData.map(item => {
const convertedItem = {
date: item.time || item.date,
category: item.name || item.category,
value: Number(item.data || item.value) || 0
};
console.log('转换后的数据项:', convertedItem);
return convertedItem;
});
}
return []; return [];
} catch (error) { } catch (error) {
@@ -78,40 +124,65 @@ const IndustryTrendPage: React.FC = () => {
return []; return [];
} }
}; };
const industries = useMemo(() => { const handleTimeDimensionChange = (value: '月' | '季度' | '年') => {
if (allData.length === 0) return []; const now = dayjs();
const categories = new Set<string>(); let newStartTime = '';
allData.forEach(item => categories.add(item.category)); switch (value) {
return Array.from(categories).sort(); case '月':
}, [allData]); newStartTime = now.subtract(6, 'month').format('YYYY-MM');
const formatTimeParam = (dateStr: string, dimension: string) => { break;
const date = dayjs(dateStr); case '季度':
switch (dimension) { newStartTime = now.subtract(6, 'quarter').format('YYYY-Q');
case '季度': return `${date.year()}-Q${Math.ceil((date.month() + 1) / 3)}`; break;
case '年': return `${date.year()}`; case '年':
default: return date.format('YYYY-MM'); default:
newStartTime = now.subtract(5, 'year').format('YYYY');
}
setParams(p => ({
...p,
timeDimension: value,
startTime: newStartTime,
endTime: value === '月' ? now.format('YYYY-MM') :
value === '季度' ? now.format('YYYY-Q') :
now.format('YYYY'),
selectedIndustry: ''
}));
};
const handleDateRangeChange = (dates: any, dateStrings: [string, string]) => {
if (dates && dates[0] && dates[1]) {
setParams(p => ({
...p,
startTime: dateStrings[0],
endTime: dateStrings[1]
}));
} }
}; };
const handleIndustryChange = (value: string) => {
setPrevSelectedIndustry(value);
setParams(p => ({ ...p, selectedIndustry: value }));
};
const currentIndustryData = useMemo(() => { const currentIndustryData = useMemo(() => {
if (!params.selectedIndustry) return []; if (!params.selectedIndustry || allData.length === 0) return [];
const filteredData = allData return allData
.filter(item => item.category === params.selectedIndustry) .filter(item => item.category === params.selectedIndustry)
.map(item => ({ .map(item => ({
date: item.date, ...item,
category: item.category, date: formatDateForDisplay(item.date, params.timeDimension)
value: item.value ?? 0,
})) }))
.sort((a, b) => dayjs(a.date).valueOf() - dayjs(b.date).valueOf()); .sort((a, b) => dayjs(a.date).valueOf() - dayjs(b.date).valueOf());
console.log("当前行业数据 (过滤后):", filteredData); }, [allData, params.selectedIndustry, params.timeDimension]);
return filteredData; const getPickerValue = () => {
}, [allData, params.selectedIndustry]); try {
console.log("最终图表数据:", currentIndustryData); return [
dayjs(params.startTime, params.timeDimension === '年' ? 'YYYY' :
params.timeDimension === '季度' ? 'YYYY-Q' : 'YYYY-MM'),
dayjs(params.endTime, params.timeDimension === '年' ? 'YYYY' :
params.timeDimension === '季度' ? 'YYYY-Q' : 'YYYY-MM')
];
} catch (e) {
console.error('日期解析错误:', e);
return null;
}
};
// 图表配置
const chartConfig = { const chartConfig = {
data: currentIndustryData, data: currentIndustryData,
height: 180, height: 180,
@@ -120,13 +191,8 @@ const IndustryTrendPage: React.FC = () => {
seriesField: 'category', seriesField: 'category',
xAxis: { xAxis: {
type: 'cat', type: 'cat',
tickCount: 5,
label: { label: {
formatter: (text: string) => { formatter: (text: string) => text,
if (params.timeDimension === '年') return text.split('-')[0];
if (params.timeDimension === '季度') return text.split('-')[1];
return text.split('-')[1];
},
}, },
}, },
yAxis: { yAxis: {
@@ -145,36 +211,35 @@ const IndustryTrendPage: React.FC = () => {
duration: 1000, duration: 1000,
}, },
}, },
smooth: true,
}; };
// 初始化加载数据
useEffect(() => { useEffect(() => {
run(); fetchData();
}, [params.timeDimension, params.startTime, params.endTime]); }, [params.timeDimension, params.startTime, params.endTime, params.type]);
return ( return (
<div style={{ padding: 16 }}> <div style={{ padding: 16 }}>
<Card <Card title="行业趋势分析" style={{ marginBottom: 24 }}>
title="行业趋势分析" <div style={{ marginBottom: 24 }}>
style={{ marginBottom: 24 }}
>
<div style={{ marginBottom: 16 }}>
<Space size="middle" wrap> <Space size="middle" wrap>
<Select <Select
value={params.selectedIndustry} value={params.selectedIndustry}
onChange={handleIndustryChange} onChange={(value) => setParams(p => ({ ...p, selectedIndustry: value }))}
style={{ width: 180 }} style={{ width: 150 }}
loading={loading} loading={loading}
placeholder="选择行业" placeholder="选择行业"
disabled={availableIndustries.length === 0}
> >
{industries.map(industry => ( {availableIndustries.map(industry => (
<Option key={industry} value={industry}>{industry}</Option> <Option key={industry} value={industry}>{industry}</Option>
))} ))}
</Select> </Select>
<Select <Select
value={params.timeDimension} value={params.timeDimension}
onChange={value => setParams(p => ({ ...p, timeDimension: value }))} onChange={handleTimeDimensionChange}
style={{ width: 100 }} style={{ width: 100 }}
> >
<Option value="月"></Option> <Option value="月"></Option>
@@ -182,10 +247,20 @@ const IndustryTrendPage: React.FC = () => {
<Option value="年"></Option> <Option value="年"></Option>
</Select> </Select>
<RangePicker
picker={params.timeDimension === '月' ? 'month' :
params.timeDimension === '季度' ? 'quarter' : 'year'}
value={getPickerValue()}
onChange={handleDateRangeChange}
style={{ width: 180 }}
disabled={loading}
allowClear={false}
/>
<Select <Select
value={params.type} value={params.type}
onChange={value => setParams(p => ({ ...p, type: value }))} onChange={(value) => setParams(p => ({ ...p, type: value }))}
style={{ width: 120 }} style={{ width: 100 }}
> >
<Option value="岗位发布数量"></Option> <Option value="岗位发布数量"></Option>
<Option value="招聘增长率"></Option> <Option value="招聘增长率"></Option>
@@ -193,90 +268,53 @@ const IndustryTrendPage: React.FC = () => {
<Button <Button
type="primary" type="primary"
onClick={() => run()} onClick={() => fetchData()}
loading={loading} loading={loading}
size="middle"
> >
</Button> </Button>
</Space> </Space>
</div> </div>
<Card <Card
title={`${params.selectedIndustry || '行业'}趋势`} title={`${params.selectedIndustry || '请选择行业'}趋势 (${params.type})`}
style={{ marginBottom: 24 }} style={{ marginBottom: 24 }}
bodyStyle={{ bodyStyle={{ padding: '20px 12px' }}
padding: 12,
height: 180,
display: 'flex',
justifyContent: 'center',
alignItems: 'center'
}}
> >
<Spin spinning={loading}> <Spin spinning={loading}>
{currentIndustryData.length > 0 ? ( {currentIndustryData.length > 0 ? (
<Line {...chartConfig} /> <Line {...chartConfig} />
) : ( ) : (
<Empty description={loading ? '数据加载中...' : '请选择行业'} /> <Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
description={
loading ? '数据加载中...' :
params.selectedIndustry ? '当前时间段无数据' : '请先选择行业'
}
/>
)} )}
</Spin> </Spin>
</Card> </Card>
<Row gutter={[16, 16]}> <Row gutter={[16, 16]}>
<Col xs={24} sm={12} md={8} lg={8} xl={6}> <Col span={6}>
<Card <Card title="区域分析" bordered={false}>
title="区域分析"
bodyStyle={{
padding: 12,
height: 300,
display: 'flex',
justifyContent: 'center',
alignItems: 'center'
}}
>
<Empty description="热力地图预留位置" /> <Empty description="热力地图预留位置" />
</Card> </Card>
</Col> </Col>
<Col xs={24} sm={12} md={8} lg={8} xl={6}> <Col span={6}>
<Card <Card title="薪资趋势" bordered={false}>
title="薪资趋势"
bodyStyle={{
padding: 12,
height: 300,
display: 'flex',
justifyContent: 'center',
alignItems: 'center'
}}
>
<Empty description="薪资分析预留位置" /> <Empty description="薪资分析预留位置" />
</Card> </Card>
</Col> </Col>
<Col xs={24} sm={12} md={8} lg={8} xl={6}> <Col span={6}>
<Card <Card title="经验要求" bordered={false}>
title="经验要求"
bodyStyle={{
padding: 12,
height: 300,
display: 'flex',
justifyContent: 'center',
alignItems: 'center'
}}
>
<Empty description="经验分析预留位置" /> <Empty description="经验分析预留位置" />
</Card> </Card>
</Col> </Col>
<Col xs={24} sm={12} md={8} lg={8} xl={6}> <Col span={6}>
<Card <Card title="技能需求" bordered={false}>
title="技能需求"
bodyStyle={{
padding: 12,
height: 300,
display: 'flex',
justifyContent: 'center',
alignItems: 'center'
}}
>
<Empty description="技能分析预留位置" /> <Empty description="技能分析预留位置" />
</Card> </Card>
</Col> </Col>