import React, { useEffect, useRef, useState } from 'react'; 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, Bar } 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: 'Indigo' }, { value: 9, label: '拒绝退款', color: 'red' }, { value: 10,label: '部分退款', color: 'plum' }, ]; const Welcome: React.FC = () => { // 租户与时间 const [tenantId, setTenantId] = useState(); const [includeChildren, setIncludeChildren] = useState(true); // 默认统计时间:年 const [rangeType, setRangeType] = useState('year'); const [range, setRange] = useState<[Moment, Moment]>(computeRangeByType('year', moment())); // 加载与数据 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 [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 }) => { 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 {} // 直接使用已有的统计数据中的tourismOrderCount const tourismOrderData = res?.data?.chartStats?.tourismOrderCount || []; const formattedScenicData = Array.isArray(tourismOrderData) ? tourismOrderData.map((item: any, index: number) => ({ tourismId: item.tourismId || item.id || '', // 使用tourismId作为唯一标识,确保相同名称的景区也能分别显示 tourismName: `${item.tourismName || '未知景区'}_${item.tourismId || index}`, tourismNameDisplay: item.tourismName || '未知景区', // 保存原始名称用于显示 orderCount: Number(item.orderCount || 0) })) // 接口返回的数据是从多到少,反转后让订单多的显示在最下面 : []; setScenicOrderData(formattedScenicData); } 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(); // 根据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 = 'date'; } 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); } } const seriesRes: any = await ordersApi.getOrderSeries({ tenantId, includeChildren, startTime, endTime, statType: apiStatType, includeTestQrcodes: false }); const seriesData: any[] = seriesRes?.data || []; const typeAlias: Record = { '订单创建': '订单创建', '订单完成': '订单完成', '完成': '订单完成', '退款': '退款', '退款完成': '退款', }; const targetTypes = ['订单创建', '订单完成', '退款']; // 构建数据映射 const dataMap: Record> = {}; targetTypes.forEach((key) => { dataMap[key] = {}; }); // 将后端数据填充到映射 seriesData.forEach((item: any) => { const date = item.date || ''; const rawType = item.type || ''; const type = typeAlias[rawType] || rawType || '订单创建'; const value = Number(item.value || 0); if (!dataMap[type]) dataMap[type] = {}; dataMap[type][date] = value; }); // 获取接口返回的实际数据范围 const actualDates = [...new Set(seriesData.map((item: any) => item.date))].sort(); // 如果没有数据,使用生成的labels;否则使用实际数据范围 const effectiveLabels = actualDates.length > 0 ? actualDates : labels; // 填充所有时间点,缺失的补 0 const lineSeries: { date: string; value: number; type: string }[] = []; effectiveLabels.forEach((label) => { targetTypes.forEach((type) => { lineSeries.push({ date: label, type, value: dataMap[type]?.[label] || 0, }); }); }); setOrderLineSeries(lineSeries); } catch { setOrderLineSeries([]); } finally { setAggLoading(false); } }; const screens = Grid.useBreakpoint(); const isMobile = !screens.md; // 小于 md 视为移动端 // 折线图配置 - 最基础的配置确保颜色正确 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 totalScenicOrders = scenicOrderData.reduce((sum, item) => sum + item.orderCount, 0); // 最多同时可见 5 条,通过容器滚动查看全部 const MAX_SCENIC_BARS = 6; const ROW_HEIGHT = 35; const chartFullHeight = Math.max(((Array.isArray(scenicOrderData) ? scenicOrderData.length : 0) * ROW_HEIGHT), MAX_SCENIC_BARS * ROW_HEIGHT); // 景区订单数量横向条形图配置 - 景区名称在Y轴(左侧),订单数量横向展示 const scenicOrderConfig: any = { data: scenicOrderData, xField: 'tourismName', // 这里反直觉:xField是分类(显示为Y轴) yField: 'orderCount', // yField是数值(显示为横向长度) autoFit: true, height: chartFullHeight, // 关键:转置坐标系,使横向条形图 coordinate: { transpose: true, }, // 使用绿色渐变,根据数值大小 color: ({ orderCount }: any) => { const maxCount = Math.max(...scenicOrderData.map(d => d.orderCount), 1); const ratio = orderCount / maxCount; // 从浅绿到深绿的渐变 if (ratio > 0.7) return '#52C41A'; // 深绿 if (ratio > 0.4) return '#73D13D'; // 中绿 if (ratio > 0.2) return '#95DE64'; // 浅绿 return '#B7EB8F'; // 很浅绿 }, label: { position: 'right', // 标签显示在条形右侧外部 offset: 8, content: (item: any) => { // 订单数为0时不显示标签,避免与景区名称重叠 if (item.orderCount === 0) return ''; return `${item.orderCount}单`; }, style: { fill: '#666', fontSize: 12, fontWeight: 500, textAlign: 'left', }, }, xAxis: { title: { text: '订单数量', style: { fontSize: 14, fontWeight: 500, }, }, grid: { line: { style: { stroke: '#E8E8E8', lineWidth: 1, lineDash: [3, 3], }, }, }, label: { formatter: (val: string) => `${Number(val)}单`, style: { fontSize: 12, }, }, }, yAxis: { label: { style: { fontSize: isMobile ? 11 : 13, fill: '#262626', }, autoEllipsis: true, autoRotate: false, }, }, barStyle: { radius: [0, 4, 4, 0], // 右侧圆角 }, animation: { appear: { animation: 'scale-in-x', duration: 800, }, }, }; // 饼图配置 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: (isMobile ? 'bottom' : 'right') as 'top' | 'right' | 'bottom' | 'left' }, label: false, animation: false, }; // 平台分账比例(默认 90%),用于分账计算展示框 const [platformSharePercent, setPlatformSharePercent] = useState(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)); const axisLeft = 40; const axisTop = 40; const axisBottom = 370; const axisRight = 1850; // 首次加载/筛选变化 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); }} /> 统计时间 document.body} popupStyle={{ zIndex: 9999 }} placement={isMobile ? 'bottomLeft' : 'bottomRight'} style={{ width: isMobile ? '100%' : undefined, minWidth: isMobile ? 220 : undefined }} /> {/* 概览卡片:总订单 / 金额 / 分账 */} 总订单概览 支付总订单数 退款订单数 支付净订单数 金额统计 订单总金额(元) 退款总金额(元) 净收入(元) 分账计算 平台分账比例
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}%` }} /> setPlatformSharePercent(Number(v || 0))} formatter={(v) => `${v}%`} parser={(v: any) => Number(String(v || '').replace('%', ''))} />
平台分账金额(元) 景区分账金额(元) 基于净收入计算(净收入 = 订单总金额 - 退款总金额)
{/* 订单趋势 - 单独一列 */}
setTooltipData(null)} > {/* 绘制坐标轴 */} {/* 图例 */} 订单创建 订单完成 退款 {/* 获取所有日期和最大值 */} {(() => { const allDates = [...new Set(orderLineSeries.map(item => item.date))].sort(); const maxValue = Math.max(...orderLineSeries.map(item => item.value), 1); const chartRight = axisRight; const xStep = (chartRight - axisLeft) / 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 = axisBottom; const chartTop = axisTop; const chartHeight = chartBottom - chartTop; const y = chartBottom - (value / maxValue) * chartHeight; return ( {value} ); })} {/* X轴标签 - 智能处理重叠问题 */} {(() => { // 根据日期数量和时间范围计算显示策略 let maxLabels = 12; if (rangeType === 'year') { maxLabels = 24; // 年视图显示月份标记,每月1-2个标签 } else if (rangeType === 'month') { maxLabels = Math.min(allDates.length, 31); } else if (rangeType === 'week') { maxLabels = 10; } const labelInterval = Math.ceil(allDates.length / maxLabels); return allDates.map((date, index) => { // 判断是否显示此标签 let shouldShow = index === 0 || index === allDates.length - 1; // 年视图特殊处理:优先显示每月1日或15日 if (rangeType === 'year') { if (date.includes('-')) { const parts = date.split('-'); if (parts.length >= 3) { const day = parseInt(parts[2]); // 显示每月1日,或者每月中间的某个日期 shouldShow = shouldShow || day === 1 || day === 15; } } } else { // 其他视图按间隔显示 shouldShow = shouldShow || index % labelInterval === 0; } if (!shouldShow) return null; const x = axisLeft + 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') { const day = parseInt(parts[2]); // 年视图:每月1日显示"月月",其他日期显示"月-日" if (day === 1) { displayText = `${parseInt(parts[1])}月`; } else { displayText = `${parts[1]}-${parts[2]}`; } } else if (rangeType === 'month') { displayText = `${parts[1]}-${parts[2]}`; // 月-日 } else { displayText = `${parts[1]}-${parts[2]}`; // 月-日 } } } const chartBottom = axisBottom; return ( {displayText} ); }); })()} {/* 垂直交互区域 - 只为有数据的日期创建 */} {(() => { // 获取有数据的日期集合 const datesWithData = [...new Set(orderLineSeries.map(item => item.date))]; return datesWithData.map((date, dateIndex) => { const actualDateIndex = allDates.indexOf(date); const x = axisLeft + actualDateIndex * xStep; const chartBottom = axisBottom; const chartTop = axisTop; const chartHeight = chartBottom - chartTop; return ( { const svgRect = e.currentTarget.closest('svg').getBoundingClientRect(); const svgWidth = 1900; const svgHeight = 450; 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: Record = { '订单创建': '#1677FF', '订单完成': '#52C41A', '退款': '#FF4D4F' }; const color = colorMap[item.type] || '#666'; return `● ${item.type}: ${item.value}`; }).join('
'); // 格式化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: `
${tooltipDate}
${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 = axisBottom; const chartTop = axisTop; const chartHeight = chartBottom - chartTop; const points = filledData.map((item, index) => { const x = axisLeft + 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 ( {/* 折线 - 平滑曲线,始终连续 */} {filledData.filter(item => item.original).length > 0 && ( )} {/* 折点 - 只在有真实数据且值大于0的位置显示 */} {typeData.map((item, index) => { if (item.value <= 0) return null; const dateIndex = allDates.indexOf(item.date); const x = axisLeft + dateIndex * xStep; const chartBottom = axisBottom; const chartTop = axisTop; const chartHeight = chartBottom - chartTop; const y = chartBottom - (item.value / maxValue) * chartHeight; return ( ); })} ); })} ); })()} {/* 垂直指示线 */} {tooltipData && ( )} {/* 自定义Tooltip */} {tooltipData && (
)}
{/* 景区订单数量统计:单行展示 */}
{/* 订单状态分布 + 订单列表 */} { 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 ? (moment(item.createTime).isValid() ? moment(item.createTime).utcOffset(8).format('YYYY-MM-DD HH:mm:ss') : String(item.createTime)) : '-'} } /> )} />
); }; export default Welcome;