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(); const [includeChildren, setIncludeChildren] = useState(true); const [rangeType, setRangeType] = useState('date'); const [range, setRange] = useState<[Moment, Moment]>(makeDefaultToday()); // 加载与数据 const [loading, setLoading] = useState(false); const [pageLoading, setPageLoading] = useState(true); const [ordersLoading, setOrdersLoading] = useState(false); const firstLoadRef = useRef(true); const [stat, setStat] = useState({ orderStats: {}, chartStats: {} }); const [orders, setOrders] = useState([]); const [ordersTotal, setOrdersTotal] = useState(0); const [page, setPage] = useState(1); const [pageSize, setPageSize] = useState(10); // 折线(订单创建/完成/退款) const [aggLoading, setAggLoading] = useState(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> = { '订单创建': {}, '完成': {}, '退款': {} }; // 将后端数据填充到映射表 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 = { '订单创建': '#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 (
{/* 顶部工具栏 */} 首页统计 { setTenantId(tid); setIncludeChildren(!!inc); }} /> 统计时间 {/* 概览卡片:左侧订单数统计 + 右侧金额统计 */} 总订单概览 总订单数 退款订单数 净订单数 金额统计 订单总金额(元) 退款总金额(元) 净收入(元) {/* 订单状态分布 + 订单列表 */}
{ load({ page: cp, pageSize: ps }); }, }} renderItem={(item: any) => ( 订单号:{item?.orderNo} {typeof item?.orderStatus !== 'undefined' ? (() => { const s = STATUS_OPTIONS.find(o => o.value === item.orderStatus); return {s?.label || '未知'}; })() : null} } description={ 金额:¥{Number((((item?.orderAmount ?? item?.amount) || 0) as number) / 100).toFixed(2)} 景区:{item?.tourismName || '-'} 时间:{item?.createTime || '-'} } /> )} />
); }; export default Welcome;