Files
gofly-platform-services/zlt-web/react-web-next/src/pages/Welcome.tsx
T

942 lines
39 KiB
TypeScript
Raw Normal View History

2025-10-21 12:37:44 +08:00
import React, { useEffect, useRef, useState } from 'react';
2025-10-21 16:48:35 +08:00
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';
2025-10-21 16:48:35 +08:00
import { Line, Pie, Column } from '@ant-design/plots';
import TenantScopeFilter from '@/components/TenantScopeFilter';
2025-10-01 03:51:53 +08:00
import { dashboardApi } from '@/services/dashboard';
import { ordersApi } from '@/services/orders';
import moment, { Moment } from 'moment';
2025-10-01 03:51:53 +08:00
const { Title, Text } = Typography;
const { RangePicker } = DatePicker;
type RangeType = 'date' | 'week' | 'month' | 'year';
const makeDefaultToday = (): [Moment, Moment] => [moment().startOf('day'), moment().endOf('day')];
const computeRangeByType = (type: RangeType, anchor?: Moment): [Moment, Moment] => {
const base = (anchor ? anchor.clone() : moment());
const unit = type === 'date' ? 'day' : type;
return [base.clone().startOf(unit as any), base.clone().endOf(unit as any)];
};
const STATUS_OPTIONS: { value: number; label: string; color?: string }[] = [
{ value: 0, label: '待支付' },
{ value: 1, label: '排队中', color: 'gold' },
{ value: 2, label: '已取消', color: 'red' },
{ value: 3, label: '设备执行完成', color: 'green' },
{ value: 4, label: '正在服务', color: 'blue' },
{ value: 5, label: '素材上传', color: 'geekblue' },
{ value: 6, label: '任务完成', color: 'purple' },
{ value: 7, label: '退款中', color: 'orange' },
{ value: 8, label: '退款成功', color: 'lime' },
{ value: 9, label: '退款失败', color: 'red' },
];
const Welcome: React.FC = () => {
// 租户与时间
2025-10-01 03:51:53 +08:00
const [tenantId, setTenantId] = useState<string>();
const [includeChildren, setIncludeChildren] = useState<boolean>(true);
// 默认统计时间:年
const [rangeType, setRangeType] = useState<RangeType>('year');
const [range, setRange] = useState<[Moment, Moment]>(computeRangeByType('year', moment()));
// 加载与数据
2025-10-01 03:51:53 +08:00
const [loading, setLoading] = useState<boolean>(false);
const [pageLoading, setPageLoading] = useState<boolean>(true);
const [ordersLoading, setOrdersLoading] = useState<boolean>(false);
2025-10-01 03:51:53 +08:00
const firstLoadRef = useRef(true);
const [stat, setStat] = useState<any>({ orderStats: {}, chartStats: {} });
const [orders, setOrders] = useState<any[]>([]);
const [ordersTotal, setOrdersTotal] = useState<number>(0);
const [page, setPage] = useState<number>(1);
const [pageSize, setPageSize] = useState<number>(10);
// 折线(订单创建/完成/退款)
const [aggLoading, setAggLoading] = useState<boolean>(false);
const [orderLineSeries, setOrderLineSeries] = useState<{ date: string; value: number; type: string }[]>([]);
2025-10-21 16:48:35 +08:00
// 景区订单数量条形图数据
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') };
};
const handleRangeTypeChange = (val: any) => {
const t = (val as RangeType) || 'date';
// 只在类型真正变化时才处理
if (t !== rangeType) {
// 切换到不同类型时,重置为当前时间
const anchorNow = moment();
setRange(computeRangeByType(t, anchorNow));
setRangeType(t);
}
};
const handleRangeChange = (vals: any) => {
if (!Array.isArray(vals) || vals.length !== 2 || !vals[0] || !vals[1]) {
// 按当前类型回退默认范围
setRange(computeRangeByType(rangeType, moment()));
return;
}
let s = vals[0] as Moment;
let e = vals[1] as Moment;
if (rangeType !== 'date') {
s = s.clone().startOf('day');
e = e.clone().endOf('day');
}
setRange([s, e]);
};
const load = async (opts?: { page?: number; pageSize?: number }) => {
2025-10-01 03:51:53 +08:00
if (firstLoadRef.current) setPageLoading(true);
setLoading(true);
try {
const { startTime, endTime } = getTimeParams();
2025-10-14 16:27:25 +08:00
const statType = (rangeType === 'month' ? 'month' : (rangeType === 'year' ? 'year' : 'day')) as 'day' | 'month' | 'year';
const res: any = await dashboardApi.statistics({ tenantId, includeChildren, startTime, endTime, statType, includeTestQrcodes: false });
2025-10-01 03:51:53 +08:00
setStat(res?.data || res);
setOrdersLoading(true);
try {
const curPage = opts?.page ?? page;
const curSize = opts?.pageSize ?? pageSize;
const ordersRes: any = await ordersApi.getDashboardOrders({ tenantId, includeChildren, startTime, endTime, includeTestQrcodes: false, page: curPage, limit: curSize });
const data = ordersRes?.data?.data || ordersRes?.data || [];
const total = ordersRes?.data?.count ?? ordersRes?.count ?? (Array.isArray(data) ? data.length : 0);
setOrders(Array.isArray(data) ? data : []);
setOrdersTotal(Number(total) || 0);
setPage(curPage);
setPageSize(curSize);
} catch {
setOrders([]);
setOrdersTotal(0);
} finally {
setOrdersLoading(false);
}
try { await loadAggregations(); } catch {}
2025-10-21 16:48:35 +08:00
try { await loadScenicOrderData(); } catch {}
2025-10-01 03:51:53 +08:00
} catch (e) {
message.error('加载统计失败');
} finally {
setLoading(false);
if (firstLoadRef.current) {
firstLoadRef.current = false;
setPageLoading(false);
}
}
};
const loadAggregations = async () => {
2025-10-01 03:51:53 +08:00
if (!tenantId) return;
setAggLoading(true);
try {
const { startTime, endTime } = getTimeParams();
2025-10-21 16:48:35 +08:00
// 根据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 cursor = start.clone();
while (cursor.isSameOrBefore(end)) {
labels.push(fmtLabel(cursor));
cursor.add(1, unit as any);
}
}
2025-10-21 16:48:35 +08:00
const seriesRes: any = await ordersApi.getOrderSeries({ tenantId, includeChildren, startTime, endTime, statType: apiStatType, includeTestQrcodes: false });
const seriesData: any[] = seriesRes?.data || [];
2025-10-01 03:51:53 +08:00
2025-10-21 16:48:35 +08:00
const typeAlias: Record<string, string> = {
'订单创建': '订单创建',
'订单完成': '订单完成',
'完成': '订单完成',
'退款': '退款',
'退款完成': '退款',
};
2025-10-21 16:48:35 +08:00
const targetTypes = ['订单创建', '订单完成', '退款'];
// 构建数据映射
const dataMap: Record<string, Record<string, number>> = {};
targetTypes.forEach((key) => { dataMap[key] = {}; });
2025-10-14 16:27:25 +08:00
// 将后端数据填充到映射
seriesData.forEach((item: any) => {
const date = item.date || '';
2025-10-21 16:48:35 +08:00
const rawType = item.type || '';
const type = typeAlias[rawType] || rawType || '订单创建';
const value = Number(item.value || 0);
2025-10-21 16:48:35 +08:00
if (!dataMap[type]) dataMap[type] = {};
dataMap[type][date] = value;
});
2025-10-14 16:27:25 +08:00
// 填充所有时间点,缺失的补 0
const lineSeries: { date: string; value: number; type: string }[] = [];
labels.forEach((label) => {
2025-10-21 16:48:35 +08:00
targetTypes.forEach((type) => {
lineSeries.push({
date: label,
type,
value: dataMap[type]?.[label] || 0,
});
});
});
setOrderLineSeries(lineSeries);
} catch {
setOrderLineSeries([]);
} finally {
setAggLoading(false);
}
2025-10-09 14:33:15 +08:00
};
2025-10-21 16:48:35 +08:00
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([]);
}
};
2025-10-14 16:27:25 +08:00
const screens = Grid.useBreakpoint();
const isMobile = !screens.md; // 小于 md 视为移动端
2025-10-21 16:48:35 +08:00
// 折线图配置 - 最基础的配置确保颜色正确
const orderLineConfig = {
data: orderLineSeries,
2025-10-01 03:51:53 +08:00
xField: 'date',
yField: 'value',
seriesField: 'type',
smooth: true,
2025-10-21 16:48:35 +08:00
height: 350,
// 直接指定颜色映射
color: ({
'订单创建': '#1677FF',
'订单完成': '#52C41A',
'退款': '#FF4D4F'
}),
// 确保折点也使用对应颜色
point: {
size: 5,
},
lineStyle: {
lineWidth: 3,
},
legend: {
position: 'top',
},
};
// 景区订单数量条形图配置
const scenicOrderConfig: any = {
data: scenicOrderData,
xField: 'tourismName',
yField: 'orderCount',
2025-10-14 16:27:25 +08:00
autoFit: true,
2025-10-21 16:48:35 +08:00
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' }],
2025-10-01 03:51:53 +08:00
};
// 饼图配置
const chartStats = stat?.chartStats || {};
const orderStats = stat?.orderStats || {};
const distributionData = chartStats?.orderDistribution || [];
const distributionPalette = ['#1668DC', '#5AD8A6', '#F6BD16', '#E8684A', '#6DC8EC', '#9270CA', '#FF9D4D', '#269A99', '#FF99C3', '#1D9ED1'];
2025-10-01 03:51:53 +08:00
const distributionConfig: any = {
data: distributionData,
angleField: 'value',
colorField: 'type',
radius: 0.9,
2025-10-09 14:33:15 +08:00
color: distributionPalette,
2025-10-14 16:27:25 +08:00
legend: { position: (isMobile ? 'bottom' : 'right') as 'top' | 'right' | 'bottom' | 'left' },
label: false,
2025-10-01 03:51:53 +08:00
animation: false,
};
// 平台分账比例(默认 90%),用于分账计算展示框
const [platformSharePercent, setPlatformSharePercent] = useState<number>(90);
const totalAmountYuan = Number(((orderStats?.totalAmount ?? 0) as number) / 100);
const refundAmountYuan = Number(((orderStats?.refundAmount ?? 0) as number) / 100);
const netIncomeYuan = Number((totalAmountYuan - refundAmountYuan).toFixed(2));
// 分账金额(基于净收入)
const platformAmountYuan = Number(((netIncomeYuan * platformSharePercent) / 100).toFixed(2));
const scenicAmountYuan = Number((netIncomeYuan - platformAmountYuan).toFixed(2));
// 首次加载/筛选变化
useEffect(() => {
if (!tenantId) return;
setPage(1);
load({ page: 1, pageSize });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tenantId, includeChildren, rangeType, range]);
return (
<div className="page-enter" style={{ padding: 24 }}>
2025-10-14 16:27:25 +08:00
{/* 顶部工具区 */}
2025-10-01 03:51:53 +08:00
<Card className="modern-card" style={{ marginBottom: 16 }}>
<Row align="middle" justify="space-between" gutter={[12, 12]}>
<Col flex="none"><Title level={4} style={{ margin: 0 }}>首页统计</Title></Col>
2025-10-01 03:51:53 +08:00
<Col flex="auto">
2025-10-14 16:27:25 +08:00
<Space direction={isMobile ? 'vertical' : 'horizontal'} style={{ width: '100%', justifyContent: 'flex-end', flexWrap: 'wrap' }} size={12}>
2025-10-01 03:51:53 +08:00
<TenantScopeFilter autoApply onChanged={(tid, inc) => { setTenantId(tid); setIncludeChildren(!!inc); }} />
2025-10-14 16:27:25 +08:00
<Space direction={isMobile ? 'vertical' : 'horizontal'} wrap>
<span>统计时间</span>
2025-10-01 03:51:53 +08:00
<Segmented
2025-10-14 16:27:25 +08:00
block={isMobile}
size={isMobile ? 'small' : 'middle'}
// 统计维度顺序:年 月 周 日(覆盖上方默认)
options={[
{ label: '年', value: 'year' },
{ label: '月', value: 'month' },
{ label: '周', value: 'week' },
{ label: '日', value: 'date' },
]}
value={rangeType}
onChange={handleRangeTypeChange}
2025-10-01 03:51:53 +08:00
/>
<RangePicker
showTime={rangeType === 'date'}
allowClear={false}
value={range as any}
picker={rangeType as any}
onChange={handleRangeChange}
2025-10-14 16:27:25 +08:00
size={isMobile ? 'small' : 'middle'}
getPopupContainer={() => document.body}
popupStyle={{ zIndex: 9999 }}
2025-10-14 16:27:25 +08:00
placement={isMobile ? 'bottomLeft' : 'bottomRight'}
style={{ width: isMobile ? '100%' : undefined, minWidth: isMobile ? 220 : undefined }}
/>
2025-10-14 16:27:25 +08:00
<Button type="primary" icon={<ReloadOutlined />} loading={loading && !pageLoading} size={isMobile ? 'small' : 'middle'} onClick={() => { load(); }}>刷新</Button>
2025-10-01 03:51:53 +08:00
</Space>
</Space>
</Col>
</Row>
</Card>
{/* 概览卡片:左侧订单数统计 + 右侧金额统计 */}
2025-10-01 03:51:53 +08:00
<Row gutter={[16, 16]}>
<Col xs={24} md={12}>
2025-10-09 14:33:15 +08:00
<Card loading={pageLoading} style={{ height: '100%' }}>
2025-10-01 03:51:53 +08:00
<Space direction="vertical" style={{ width: '100%' }} size={12}>
<Text strong>总订单概览</Text>
2025-10-01 03:51:53 +08:00
<Row gutter={8} align="middle" style={{ width: '100%' }}>
<Col xs={12} sm={10} md={10}><Text type="secondary">支付总订单数</Text></Col>
2025-10-01 03:51:53 +08:00
<Col xs={12} sm={14} md={14} style={{ textAlign: 'right' }}>
<Statistic value={orderStats?.totalOrders || 0} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} />
</Col>
2025-10-01 03:51:53 +08:00
</Row>
<Row gutter={8} align="middle" style={{ width: '100%' }}>
<Col xs={12} sm={10} md={10}><Text type="secondary">退款订单数</Text></Col>
<Col xs={12} sm={14} md={14} style={{ textAlign: 'right' }}>
<Statistic value={orderStats?.refundedOrders || 0} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} />
2025-10-01 03:51:53 +08:00
</Col>
</Row>
<Row gutter={8} align="middle" style={{ width: '100%' }}>
<Col xs={12} sm={10} md={10}><Text type="secondary">支付净订单数</Text></Col>
2025-10-01 03:51:53 +08:00
<Col xs={12} sm={14} md={14} style={{ textAlign: 'right' }}>
<Statistic value={(orderStats?.totalOrders || 0) - (orderStats?.refundedOrders || 0)} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} />
2025-10-01 03:51:53 +08:00
</Col>
</Row>
</Space>
</Card>
</Col>
<Col xs={24} md={12}>
2025-10-09 14:33:15 +08:00
<Card loading={pageLoading} style={{ height: '100%' }}>
2025-10-01 03:51:53 +08:00
<Space direction="vertical" style={{ width: '100%' }} size={12}>
<Text strong>金额统计</Text>
2025-10-01 03:51:53 +08:00
<Row gutter={8} align="middle" style={{ width: '100%' }}>
<Col xs={12} sm={10} md={10}><Text type="secondary">订单总金额(元)</Text></Col>
2025-10-01 03:51:53 +08:00
<Col xs={12} sm={14} md={14} style={{ textAlign: 'right' }}>
<Statistic value={totalAmountYuan} precision={2} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} />
2025-10-01 03:51:53 +08:00
</Col>
</Row>
<Row gutter={8} align="middle" style={{ width: '100%' }}>
<Col xs={12} sm={10} md={10}><Text type="secondary">退款总金额(元)</Text></Col>
2025-10-01 03:51:53 +08:00
<Col xs={12} sm={14} md={14} style={{ textAlign: 'right' }}>
<Statistic value={refundAmountYuan} precision={2} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} />
2025-10-01 03:51:53 +08:00
</Col>
</Row>
<Row gutter={8} align="middle" style={{ width: '100%' }}>
<Col xs={12} sm={10} md={10}><Text type="secondary">净收入(元)</Text></Col>
2025-10-01 03:51:53 +08:00
<Col xs={12} sm={14} md={14} style={{ textAlign: 'right' }}>
<Statistic value={netIncomeYuan} precision={2} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} />
2025-10-01 03:51:53 +08:00
</Col>
</Row>
2025-10-21 12:37:44 +08:00
</Space>
</Card>
</Col>
</Row>
2025-10-21 16:48:35 +08:00
{/* 分账计算 + 景区订单数量统计 */}
<Row gutter={[16, 16]} style={{ marginTop: 16 }}>
2025-10-21 16:48:35 +08:00
<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]}>
<Col flex="none"><Text strong>分账计算</Text></Col>
<Col flex="auto" style={{ textAlign: 'right' }}>
<Space>
<span>平台分账比例</span>
<div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, minWidth: 220 }}>
<Slider
style={{ width: 160 }}
min={0}
max={100}
step={1}
value={platformSharePercent}
onChange={(v: any) => setPlatformSharePercent(Number(v))}
marks={{
0: { style: { color: '#666' }, label: '0%' },
50: { style: { color: '#666' }, label: '50%' },
100: { style: { color: '#666' }, label: '100%' }
}}
tooltip={{ formatter: (value) => `${value}%` }}
/>
<InputNumber min={0} max={100} value={platformSharePercent} onChange={(v) => setPlatformSharePercent(Number(v || 0))} formatter={(v) => `${v}%`} parser={(v: any) => Number(String(v || '').replace('%', ''))} />
</div>
</Space>
</Col>
</Row>
<Row gutter={[8, 8]}>
<Col xs={24} sm={12}>
<Card>
<Space direction="vertical" style={{ width: '100%' }} size={8}>
<Text type="secondary">平台分账金额(元)</Text>
<Statistic value={platformAmountYuan} precision={2} valueStyle={{ fontWeight: 600 }} />
</Space>
</Card>
</Col>
<Col xs={24} sm={12}>
<Card>
<Space direction="vertical" style={{ width: '100%' }} size={8}>
<Text type="secondary">景区分账金额(元)</Text>
<Statistic value={scenicAmountYuan} precision={2} valueStyle={{ fontWeight: 600 }} />
</Space>
</Card>
</Col>
</Row>
<Text type="secondary">基于净收入计算(净收入 = 订单总金额 - 退款总金额)</Text>
2025-10-01 03:51:53 +08:00
</Space>
</Card>
</Col>
2025-10-21 16:48:35 +08:00
<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>
{/* 订单状态分布 + 订单列表 */}
2025-10-21 16:48:35 +08:00
<Row gutter={[16, 16]} style={{ marginTop: 16 }}>
2025-10-09 14:33:15 +08:00
<Col xs={24} md={12}>
2025-10-21 16:48:35 +08:00
<Card title="订单状态分布" loading={pageLoading} style={{ height: '100%' }}>
2025-10-01 03:51:53 +08:00
<Pie {...distributionConfig} />
</Card>
</Col>
<Col xs={24} md={12}>
<Card title={`订单列表(共 ${ordersTotal} 条)`} loading={pageLoading} style={{ height: '100%' }}>
<List
loading={ordersLoading}
dataSource={orders}
pagination={{
current: page,
pageSize,
total: ordersTotal,
showSizeChanger: true,
showQuickJumper: true,
onChange: (cp, ps) => { load({ page: cp, pageSize: ps }); },
}}
renderItem={(item: any) => (
<List.Item>
<List.Item.Meta
title={
<Space>
<span>订单号:{item?.orderNo}</span>
{typeof item?.orderStatus !== 'undefined' ? (() => {
const s = STATUS_OPTIONS.find(o => o.value === item.orderStatus);
return <Tag color={s?.color}>{s?.label || '未知'}</Tag>;
})() : null}
</Space>
}
description={
<Space size={16} wrap>
<span>金额:¥{Number((((item?.orderAmount ?? item?.amount) || 0) as number) / 100).toFixed(2)}</span>
<span>景区:{item?.tourismName || '-'}</span>
<span>时间:{item?.createTime || '-'}</span>
</Space>
}
/>
</List.Item>
)}
/>
</Card>
</Col>
2025-10-01 03:51:53 +08:00
</Row>
</div>
);
};
2025-09-29 19:29:41 +08:00
export default Welcome;