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

369 lines
15 KiB
TypeScript

import React, { useEffect, useRef, useState } from 'react';
import { Card, Space, Typography, Row, Col, Button, message, DatePicker, Segmented, List, Tag, Statistic } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import { Line, Pie } from '@ant-design/plots';
import TenantScopeFilter from '@/components/TenantScopeFilter';
import { dashboardApi } from '@/services/dashboard';
import { ordersApi } from '@/services/orders';
import moment, { Moment } from 'moment';
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 = () => {
// 租户与时间
const [tenantId, setTenantId] = useState<string>();
const [includeChildren, setIncludeChildren] = useState<boolean>(true);
const [rangeType, setRangeType] = useState<RangeType>('date');
const [range, setRange] = useState<[Moment, Moment]>(makeDefaultToday());
// 加载与数据
const [loading, setLoading] = useState<boolean>(false);
const [pageLoading, setPageLoading] = useState<boolean>(true);
const [ordersLoading, setOrdersLoading] = useState<boolean>(false);
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 }[]>([]);
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';
setRangeType(t);
const anchor = range?.[0] || moment();
setRange(computeRangeByType(t, anchor));
};
const handleRangeChange = (vals: any) => {
if (!Array.isArray(vals) || vals.length !== 2 || !vals[0] || !vals[1]) {
setRange(makeDefaultToday());
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 }) => {
if (firstLoadRef.current) setPageLoading(true);
setLoading(true);
try {
const { startTime, endTime } = getTimeParams();
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 });
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 {}
} catch (e) {
message.error('加载统计失败');
} finally {
setLoading(false);
if (firstLoadRef.current) {
firstLoadRef.current = false;
setPageLoading(false);
}
}
};
const loadAggregations = async () => {
if (!tenantId) return;
setAggLoading(true);
try {
const { startTime, endTime } = getTimeParams();
const unit: 'hour' | 'day' | 'month' = (rangeType === 'date') ? 'hour' : (rangeType === 'year' ? 'month' : '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)) {
labels.push(fmtLabel(cursor));
cursor.add(1, unit as any);
}
}
const seriesRes: any = await ordersApi.getOrderSeries({ tenantId, includeChildren, startTime, endTime, statType: rangeType, includeTestQrcodes: false });
const seriesData: any[] = seriesRes?.data || [];
// 构建数据映射表
const dataMap: Record<string, Record<string, number>> = {
'订单创建': {},
'完成': {},
'退款': {}
};
// 将后端数据填充到映射表
seriesData.forEach((item: any) => {
const date = item.date || '';
const type = item.type || '';
const value = Number(item.value || 0);
if (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 });
});
setOrderLineSeries(lineSeries);
} catch {
setOrderLineSeries([]);
} finally {
setAggLoading(false);
}
};
// 折线图配置(按 type 分组,不同颜色显示)
const getColorByType = (type: string) => {
const colorMapping: Record<string, string> = {
'订单创建': '#1890ff',
'完成': '#52c41a',
'退款': '#ff4d4f'
};
return colorMapping[type] || '#1890ff';
};
const orderLineConfig: any = {
data: orderLineSeries,
xField: 'date',
yField: 'value',
seriesField: 'type',
smooth: true,
height: 220,
legend: { position: 'top' as const },
color: (datum: any) => {
return getColorByType(datum.type);
},
};
// 饼图配置
const chartStats = stat?.chartStats || {};
const orderStats = stat?.orderStats || {};
const distributionData = chartStats?.orderDistribution || [];
const distributionPalette = ['#1668DC', '#5AD8A6', '#F6BD16', '#E8684A', '#6DC8EC', '#9270CA', '#FF9D4D', '#269A99', '#FF99C3', '#1D9ED1'];
const distributionConfig: any = {
data: distributionData,
angleField: 'value',
colorField: 'type',
radius: 0.9,
color: distributionPalette,
legend: { position: 'right' },
label: false,
animation: false,
};
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));
// 首次加载/筛选变化
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 }}>
{/* 顶部工具栏 */}
<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>
<Col flex="auto">
<Space style={{ width: '100%', justifyContent: 'flex-end', flexWrap: 'wrap' }} size={12}>
<TenantScopeFilter autoApply onChanged={(tid, inc) => { setTenantId(tid); setIncludeChildren(!!inc); }} />
<Space>
<span>统计时间</span>
<Segmented
options={[{ label: '日', value: 'date' }, { label: '周', value: 'week' }, { label: '月', value: 'month' }, { label: '年', value: 'year' }]}
value={rangeType}
onChange={handleRangeTypeChange}
/>
<RangePicker
showTime={rangeType === 'date'}
allowClear={false}
value={range as any}
picker={rangeType as any}
onChange={handleRangeChange}
/>
<Button type="primary" icon={<ReloadOutlined />} loading={loading && !pageLoading} onClick={() => { load(); }}>刷新</Button>
</Space>
</Space>
</Col>
</Row>
</Card>
{/* 概览卡片:左侧订单数统计 + 右侧金额统计 */}
<Row gutter={[16, 16]}>
<Col xs={24} md={12}>
<Card loading={pageLoading} style={{ height: '100%' }}>
<Space direction="vertical" style={{ width: '100%' }} size={12}>
<Text strong>总订单概览</Text>
<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?.totalOrders || 0} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} />
</Col>
</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' }} />
</Col>
</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?.totalOrders || 0) - (orderStats?.refundedOrders || 0)} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} />
</Col>
</Row>
</Space>
</Card>
</Col>
<Col xs={24} md={12}>
<Card loading={pageLoading} style={{ height: '100%' }}>
<Space direction="vertical" style={{ width: '100%' }} size={12}>
<Text strong>金额统计</Text>
<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={totalAmountYuan} precision={2} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} />
</Col>
</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={refundAmountYuan} precision={2} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} />
</Col>
</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={netIncomeYuan} precision={2} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} />
</Col>
</Row>
</Space>
</Card>
</Col>
</Row>
{/* 订单状态分布 + 订单列表 */}
<Row gutter={[16, 16]}>
<Col xs={24} md={12}>
<Card title="订单状态分布" loading={pageLoading || aggLoading} style={{ height: '100%' }}>
<div style={{ marginBottom: 12 }}>
<Line {...orderLineConfig} />
</div>
<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>
</Row>
</div>
);
};
export default Welcome;