feat: 重新优化首页布局结构

- 将景区订单数量统计移至分账计算栏右侧
- 左侧显示分账统计,右侧显示景区订单数量条形图
- 订单趋势折线图单独占据一整列,充分利用空间
- 优化折线图尺寸和响应式布局
- 增加年视图显示标签数量,避免数据密集问题
- 调整图表坐标系以适应新布局

🤖 Generated with Claude Code

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2025-10-21 16:48:35 +08:00
co-authored by Claude
parent cf12bc56cd
commit 57ce4301fa
+528 -36
View File
@@ -1,7 +1,7 @@
import React, { useEffect, useRef, useState } from 'react';
import { Card, Space, Typography, Row, Col, Button, message, DatePicker, Segmented, List, Tag, Statistic, Grid, Slider, InputNumber } from 'antd';
import { Card, Space, Typography, Row, Col, Button, message, DatePicker, Segmented, List, Tag, Statistic, Grid, Slider, InputNumber, Tooltip } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import { Line, Pie } from '@ant-design/plots';
import { Line, Pie, Column } from '@ant-design/plots';
import TenantScopeFilter from '@/components/TenantScopeFilter';
import { dashboardApi } from '@/services/dashboard';
import { ordersApi } from '@/services/orders';
@@ -56,6 +56,12 @@ const Welcome: React.FC = () => {
const [aggLoading, setAggLoading] = useState<boolean>(false);
const [orderLineSeries, setOrderLineSeries] = useState<{ date: string; value: number; type: string }[]>([]);
// 景区订单数量条形图数据
const [scenicOrderData, setScenicOrderData] = useState<{ tourismName: string; orderCount: number }[]>([]);
// 折线图Tooltip状态
const [tooltipData, setTooltipData] = useState<{ x: number; y: number; content: string; lineX: number } | null>(null);
const getTimeParams = () => {
const [start, end] = range || makeDefaultToday();
return { startTime: start.format('YYYY-MM-DD HH:mm:ss'), endTime: end.format('YYYY-MM-DD HH:mm:ss') };
@@ -116,6 +122,7 @@ const Welcome: React.FC = () => {
}
try { await loadAggregations(); } catch {}
try { await loadScenicOrderData(); } catch {}
} catch (e) {
message.error('加载统计失败');
} finally {
@@ -132,13 +139,27 @@ const Welcome: React.FC = () => {
setAggLoading(true);
try {
const { startTime, endTime } = getTimeParams();
const unit: 'hour' | 'day' | 'month' = (rangeType === 'date') ? 'hour' : (rangeType === 'year' ? 'month' : 'day');
// 根据rangeType确定显示粒度,但年维度也按天显示
let unit: 'hour' | 'day' | 'month';
let fmtLabel: (m: moment.Moment) => string;
let apiStatType: string;
if (rangeType === 'date') {
unit = 'hour';
fmtLabel = (m: moment.Moment) => m.format('HH:00');
apiStatType = 'hour';
} else {
// 月、年、周都按天显示
unit = 'day';
fmtLabel = (m: moment.Moment) => m.format('YYYY-MM-DD');
apiStatType = 'day';
}
const start = (range?.[0] || moment()).clone().startOf(unit as any);
const end = (range?.[1] || moment()).clone().endOf(unit as any);
// 生成所有时间点标签
const labels: string[] = [];
const fmtLabel = (m: moment.Moment) => (unit === 'hour' ? m.format('HH:00') : unit === 'day' ? m.format('YYYY-MM-DD') : m.format('YYYY-MM'));
{
const cursor = start.clone();
while (cursor.isSameOrBefore(end)) {
@@ -147,32 +168,42 @@ const Welcome: React.FC = () => {
}
}
const seriesRes: any = await ordersApi.getOrderSeries({ tenantId, includeChildren, startTime, endTime, statType: rangeType, includeTestQrcodes: false });
const seriesRes: any = await ordersApi.getOrderSeries({ tenantId, includeChildren, startTime, endTime, statType: apiStatType, includeTestQrcodes: false });
const seriesData: any[] = seriesRes?.data || [];
// 构建数据映射
const dataMap: Record<string, Record<string, number>> = {
'订单创建': {},
'完成': {},
'退款': {}
const typeAlias: Record<string, string> = {
'订单创建': '订单创建',
'订单完成': '订单完成',
'完成': '订单完成',
'退款': '退款',
'退款完成': '退款',
};
const targetTypes = ['订单创建', '订单完成', '退款'];
// 构建数据映射
const dataMap: Record<string, Record<string, number>> = {};
targetTypes.forEach((key) => { dataMap[key] = {}; });
// 将后端数据填充到映射
seriesData.forEach((item: any) => {
const date = item.date || '';
const type = item.type || '';
const rawType = item.type || '';
const type = typeAlias[rawType] || rawType || '订单创建';
const value = Number(item.value || 0);
if (dataMap[type]) {
dataMap[type][date] = value;
}
if (!dataMap[type]) dataMap[type] = {};
dataMap[type][date] = value;
});
// 填充所有时间点,缺失的补 0
const lineSeries: { date: string; value: number; type: string }[] = [];
labels.forEach((label) => {
lineSeries.push({ date: label, type: '订单创建', value: dataMap['订单创建'][label] || 0 });
lineSeries.push({ date: label, type: '完成', value: dataMap['完成'][label] || 0 });
lineSeries.push({ date: label, type: '退款', value: dataMap['退款'][label] || 0 });
targetTypes.forEach((type) => {
lineSeries.push({
date: label,
type,
value: dataMap[type]?.[label] || 0,
});
});
});
setOrderLineSeries(lineSeries);
@@ -183,28 +214,101 @@ const Welcome: React.FC = () => {
}
};
// 折线图配置(按 type 分组,不同颜色显示)
const getColorByType = (type: string) => {
const colorMapping: Record<string, string> = {
'订单创建': '#1890ff',
'完成': '#52c41a',
'退款': '#ff4d4f'
};
return colorMapping[type] || '#1890ff';
const loadScenicOrderData = async () => {
if (!tenantId) return;
try {
const { startTime, endTime } = getTimeParams();
const scenicStats: any = await dashboardApi.getScenicOrderStats({
tenantId,
includeChildren,
startTime,
endTime,
includeTestQrcodes: false
});
const data = scenicStats?.data || scenicStats || [];
const formattedData = Array.isArray(data) ? data.map((item: any) => ({
tourismName: item.tourismName || item.name || '未知景区',
orderCount: Number(item.orderCount || item.count || 0)
})).sort((a, b) => b.orderCount - a.orderCount) : [];
setScenicOrderData(formattedData);
} catch (error) {
console.error('加载景区订单数据失败:', error);
setScenicOrderData([]);
}
};
const screens = Grid.useBreakpoint();
const isMobile = !screens.md; // 小于 md 视为移动端
const orderLineConfig: any = {
// 折线图配置 - 最基础的配置确保颜色正确
const orderLineConfig = {
data: orderLineSeries,
xField: 'date',
yField: 'value',
seriesField: 'type',
smooth: true,
height: 350,
// 直接指定颜色映射
color: ({
'订单创建': '#1677FF',
'订单完成': '#52C41A',
'退款': '#FF4D4F'
}),
// 确保折点也使用对应颜色
point: {
size: 5,
},
lineStyle: {
lineWidth: 3,
},
legend: {
position: 'top',
},
};
// 景区订单数量条形图配置
const scenicOrderConfig: any = {
data: scenicOrderData,
xField: 'tourismName',
yField: 'orderCount',
autoFit: true,
height: isMobile ? 180 : 220,
legend: { position: 'top' },
color: (datum: any) => getColorByType(datum.type),
height: isMobile ? 240 : 400,
padding: isMobile ? [24, 16, 40, 60] : [32, 24, 48, 80],
color: '#1668DC',
columnStyle: {
radius: [4, 4, 0, 0],
},
label: {
position: 'top',
style: {
fill: '#666',
fontSize: 12,
},
formatter: (text: any, item: any) => `${item.orderCount}`,
},
xAxis: {
label: {
autoRotate: true,
rotate: isMobile ? 45 : 0,
style: {
fontSize: isMobile ? 10 : 12,
},
},
tickCount: isMobile ? 5 : undefined,
},
yAxis: {
minTickInterval: 1,
nice: true,
label: {
formatter: (val: string) => `${Number(val)}`,
},
},
interactions: [{ type: 'active-region' }],
};
// 饼图配置
@@ -339,9 +443,9 @@ const Welcome: React.FC = () => {
</Col>
</Row>
{/* 分账计算(基于净收入) */}
{/* 分账计算 + 景区订单数量统计 */}
<Row gutter={[16, 16]} style={{ marginTop: 16 }}>
<Col xs={24}>
<Col xs={24} lg={12}>
<Card className="modern-card">
<Space direction="vertical" style={{ width: '100%' }} size={12}>
<Row align="middle" justify="space-between" gutter={[8, 8]}>
@@ -391,15 +495,403 @@ const Welcome: React.FC = () => {
</Space>
</Card>
</Col>
<Col xs={24} lg={12}>
<Card title="景区订单数量统计" loading={pageLoading} style={{ height: '100%' }}>
<Column {...scenicOrderConfig} />
</Card>
</Col>
</Row>
{/* 订单趋势 - 单独一列 */}
<Row gutter={[16, 16]} style={{ marginTop: 16 }}>
<Col xs={24}>
<Card title="订单状态趋势" loading={pageLoading || aggLoading}>
<div
style={{
width: '100%',
height: rangeType === 'year' ? 600 : 500,
padding: '10px 0',
position: 'relative'
}}
onMouseLeave={() => setTooltipData(null)}
>
<svg width="100%" height="100%" viewBox={`0 0 ${rangeType === 'year' ? 1200 : 1100} ${rangeType === 'year' ? 600 : 500}`}>
{/* 绘制坐标轴 */}
<line
x1="60"
y1={rangeType === 'year' ? 520 : 430}
x2={rangeType === 'year' ? 1150 : 1050}
y2={rangeType === 'year' ? 520 : 430}
stroke="#e8e8e8"
strokeWidth="1"
/>
<line
x1="60"
y1="40"
x2="60"
y2={rangeType === 'year' ? 520 : 430}
stroke="#e8e8e8"
strokeWidth="1"
/>
{/* 图例 */}
<g transform="translate(60, 10)">
<circle cx="0" cy="5" r="4" fill="#1677FF"/>
<text x="10" y="8" fontSize="12" fill="#666">订单创建</text>
<circle cx="100" cy="5" r="4" fill="#52C41A"/>
<text x="110" y="8" fontSize="12" fill="#666">订单完成</text>
<circle cx="200" cy="5" r="4" fill="#FF4D4F"/>
<text x="210" y="8" fontSize="12" fill="#666">退款</text>
</g>
{/* 获取所有日期和最大值 */}
{(() => {
const allDates = [...new Set(orderLineSeries.map(item => item.date))].sort();
const maxValue = Math.max(...orderLineSeries.map(item => item.value), 1);
const chartRight = rangeType === 'year' ? 1150 : 1050;
const xStep = (chartRight - 60) / Math.max(allDates.length - 1, 1);
// Y轴刻度和标签
const ySteps = 5;
const yStepValue = Math.ceil(maxValue / ySteps);
return (
<>
{/* Y轴刻度和标签 */}
{Array.from({ length: ySteps + 1 }, (_, i) => {
const value = i * yStepValue;
const chartBottom = rangeType === 'year' ? 520 : 430;
const chartTop = 40;
const chartHeight = chartBottom - chartTop;
const y = chartBottom - (value / maxValue) * chartHeight;
return (
<g key={i}>
<line
x1="55" y1={y} x2="60" y2={y}
stroke="#e8e8e8" strokeWidth="1"
/>
<text
x="45" y={y + 4}
fontSize="10" fill="#666" textAnchor="end"
>
{value}
</text>
<line
x1="60" y1={y} x2={chartRight - 50} y2={y}
stroke="#f0f0f0" strokeWidth="1" strokeDasharray="3,3"
/>
</g>
);
})}
{/* X轴标签 - 智能处理重叠问题 */}
{(() => {
// 根据日期数量和时间范围计算显示策略
let maxLabels = 12;
if (rangeType === 'year') {
maxLabels = 20; // 年视图时可以显示更多标签,因为有更宽的空间
} else if (rangeType === 'month') {
maxLabels = 15;
} else if (rangeType === 'week') {
maxLabels = 10;
}
const labelInterval = Math.ceil(allDates.length / maxLabels);
return allDates.map((date, index) => {
// 判断是否显示此标签
const shouldShow = index === 0 ||
index === allDates.length - 1 ||
index % labelInterval === 0;
if (!shouldShow) return null;
const x = 60 + index * xStep;
// 智能格式化日期显示
let displayText = date;
if (date.length > 10) {
displayText = date.substring(0, 10);
}
// 根据不同时间范围简化显示
if (date.includes('-')) {
const parts = date.split('-');
if (parts.length >= 3) {
if (rangeType === 'year') {
displayText = `${parts[1]}-${parts[2]}`; // 月-日
} else if (rangeType === 'month') {
displayText = `${parts[1]}-${parts[2]}`; // 月-日
} else {
displayText = `${parts[1]}-${parts[2]}`; // 月-日
}
}
}
const chartBottom = rangeType === 'year' ? 520 : 430;
return (
<g key={index}>
<text
x={x}
y={chartBottom + 15}
fontSize="8" fill="#666" textAnchor="middle"
style={{ userSelect: 'none' }}
>
{displayText}
</text>
<line
x1={x} y1={chartBottom} x2={x} y2={chartBottom + 5}
stroke="#e8e8e8" strokeWidth="1"
/>
</g>
);
});
})()}
{/* 垂直交互区域 - 只为有数据的日期创建 */}
{(() => {
// 获取有数据的日期集合
const datesWithData = [...new Set(orderLineSeries.map(item => item.date))];
return datesWithData.map((date, dateIndex) => {
const actualDateIndex = allDates.indexOf(date);
const x = 60 + actualDateIndex * xStep;
const chartBottom = rangeType === 'year' ? 520 : 430;
const chartTop = 40;
const chartHeight = chartBottom - chartTop;
return (
<rect
key={dateIndex}
x={x - 20}
y={chartTop}
width="40"
height={chartHeight}
fill="transparent"
style={{ cursor: 'pointer' }}
onMouseEnter={(e: any) => {
const svgRect = e.currentTarget.closest('svg').getBoundingClientRect();
const svgWidth = rangeType === 'year' ? 1200 : 1100;
const svgHeight = rangeType === 'year' ? 600 : 500;
const tooltipX = (e.clientX - svgRect.left) * (svgWidth / svgRect.width);
const tooltipY = (e.clientY - svgRect.top) * (svgHeight / svgRect.height);
// 获取这个日期的所有数据
const allDataForDate = orderLineSeries.filter(item => item.date === date);
if (allDataForDate.length > 0) {
const contentLines = allDataForDate.map(item => {
const colorMap = {
'订单创建': '#1677FF',
'订单完成': '#52C41A',
'退款': '#FF4D4F'
};
const color = colorMap[item.type] || '#666';
return `<span style="color: ${color}">●</span> ${item.type}: ${item.value}`;
}).join('<br>');
// 格式化tooltip中的日期显示
let tooltipDate = date;
if (rangeType === 'month' && date.includes('-')) {
const parts = date.split('-');
if (parts.length >= 3) {
tooltipDate = `${parts[0]}年${parts[1]}月${parts[2]}日`;
}
} else if (date.length > 15) {
tooltipDate = date.substring(0, 15) + '...';
}
setTooltipData({
x: tooltipX,
y: tooltipY - 40,
lineX: x, // 传递SVG坐标系的X位置
content: `<div style="text-align: center; margin-bottom: 4px; font-weight: bold;">${tooltipDate}</div>${contentLines}`
});
}
}}
/>
);
});
})()}
{/* 绘制折线和折点 */}
{['订单创建', '订单完成', '退款'].map((type, typeIndex) => {
const colorMap = ['#1677FF', '#52C41A', '#FF4D4F'];
const color = colorMap[typeIndex];
const typeData = orderLineSeries.filter(item => item.type === type);
if (typeData.length === 0) return null;
// 为所有日期填充数据,缺失的日期用前一个有效数据填充
const filledData: { date: string; value: number; original: boolean }[] = [];
let lastValidValue = 0;
allDates.forEach((date) => {
const dataForDate = typeData.find(item => item.date === date);
if (dataForDate) {
// 有真实数据
lastValidValue = dataForDate.value;
filledData.push({
date,
value: dataForDate.value,
original: true
});
} else {
// 无数据,使用上一个有效值
filledData.push({
date,
value: lastValidValue,
original: false
});
}
});
// 生成平滑曲线路径 - 使用贝塞尔曲线
const pathData = (() => {
if (filledData.length === 0) return '';
const chartBottom = rangeType === 'year' ? 520 : 430;
const chartTop = 40;
const chartHeight = chartBottom - chartTop;
const points = filledData.map((item, index) => {
const x = 60 + index * xStep;
const y = chartBottom - (item.value / maxValue) * chartHeight;
return { x, y };
});
let path = `M ${points[0].x} ${points[0].y}`;
if (points.length === 1) {
return path;
}
// 使用二次贝塞尔曲线连接各点
for (let i = 1; i < points.length; i++) {
const prev = points[i - 1];
const curr = points[i];
// 计算控制点,创建平滑曲线
const cpx = (prev.x + curr.x) / 2;
const cpy = (prev.y + curr.y) / 2;
if (i === 1) {
// 第一段曲线
const cp1x = prev.x + (curr.x - prev.x) * 0.3;
const cp1y = prev.y;
path += ` C ${cp1x} ${cp1y}, ${cpx} ${cpy}, ${curr.x} ${curr.y}`;
} else {
// 后续曲线段
const next = points[i + 1];
if (next) {
const cp2x = curr.x - (next.x - prev.x) * 0.15;
const cp2y = curr.y;
path += ` S ${cp2x} ${cp2y}, ${curr.x} ${curr.y}`;
} else {
// 最后一个点
const cp2x = curr.x - (curr.x - prev.x) * 0.3;
const cp2y = curr.y;
path += ` S ${cp2x} ${cp2y}, ${curr.x} ${curr.y}`;
}
}
}
return path;
})();
return (
<g key={type}>
{/* 折线 - 平滑曲线,始终连续 */}
{filledData.filter(item => item.original).length > 0 && (
<path
d={pathData}
fill="none"
stroke={color}
strokeWidth="3"
strokeLinejoin="round"
strokeLinecap="round"
/>
)}
{/* 折点 - 只在有真实数据且值大于0的位置显示 */}
{typeData.map((item, index) => {
if (item.value <= 0) return null;
const dateIndex = allDates.indexOf(item.date);
const x = 60 + dateIndex * xStep;
const chartBottom = rangeType === 'year' ? 520 : 430;
const chartTop = 40;
const chartHeight = chartBottom - chartTop;
const y = chartBottom - (item.value / maxValue) * chartHeight;
return (
<circle
key={index}
cx={x}
cy={y}
r="6"
fill={color}
stroke="#fff"
strokeWidth="2"
style={{
filter: 'drop-shadow(0 2px 4px rgba(0,0,0,0.2))'
}}
/>
);
})}
</g>
);
})}
</>
);
})()}
{/* 垂直指示线 */}
{tooltipData && (
<line
x1={tooltipData.lineX}
y1="40"
x2={tooltipData.lineX}
y2={rangeType === 'year' ? 520 : 430}
stroke="#999"
strokeWidth="1"
strokeDasharray="5,5"
opacity="0.6"
/>
)}
</svg>
{/* 自定义Tooltip */}
{tooltipData && (
<div
style={{
position: 'absolute',
left: `${(tooltipData.x / (rangeType === 'year' ? 1200 : 1100)) * 100}%`,
top: `${(tooltipData.y / (rangeType === 'year' ? 600 : 500)) * 100}%`,
transform: 'translate(-50%, 0)',
backgroundColor: 'rgba(0, 0, 0, 0.8)',
color: '#fff',
padding: '8px 12px',
borderRadius: '4px',
fontSize: '12px',
whiteSpace: 'nowrap',
pointerEvents: 'none',
zIndex: 1000,
minWidth: '120px',
}}
dangerouslySetInnerHTML={{ __html: tooltipData.content }}
/>
)}
</div>
</Card>
</Col>
</Row>
{/* 订单状态分布 + 订单列表 */}
<Row gutter={[16, 16]}>
<Row gutter={[16, 16]} style={{ marginTop: 16 }}>
<Col xs={24} md={12}>
<Card title="订单状态分布" loading={pageLoading || aggLoading} style={{ height: '100%' }}>
<div style={{ marginBottom: 12 }}>
<Line {...orderLineConfig} />
</div>
<Card title="订单状态分布" loading={pageLoading} style={{ height: '100%' }}>
<Pie {...distributionConfig} />
</Card>
</Col>