/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
For commercial licensing, please contact support@quantumnous.com
*/
import { RefreshCw as ActionRefreshCw } from '@/components/common/icons/ActionIcons';
import React, { useState, useEffect, useCallback } from 'react';
import {
Card,
Row,
Col,
Empty,
Spin,
Tag,
Table,
Progress,
Button,
DatePicker,
Space,
} from '@/components/ui';
import {
Activity,
Clock,
Server,
Zap,
AlertTriangle,
CheckCircle,
XCircle,
ChevronDown,
ChevronUp,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { API, showError } from '../../helpers';
const GroupMonitorAdmin = () => {
const { t, i18n } = useTranslation();
const [groups, setGroups] = useState([]);
const [overview, setOverview] = useState(null);
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [expandedGroups, setExpandedGroups] = useState({});
const [historyData, setHistoryData] = useState({});
const [historyLoading, setHistoryLoading] = useState({});
const [dateRange, setDateRange] = useState({});
// 获取分组监控数据
const fetchGroupData = useCallback(
async (showRefreshIndicator = false) => {
if (showRefreshIndicator) {
setRefreshing(true);
} else {
setLoading(true);
}
try {
const [groupsRes, overviewRes] = await Promise.all([
API.get('/api/monitor/groups/admin'),
API.get('/api/monitor/groups/overview'),
]);
if (groupsRes.data.success) {
setGroups(groupsRes.data.data || []);
} else {
showError(groupsRes.data.message || t('获取分组数据失败'));
}
if (overviewRes.data.success) {
setOverview(overviewRes.data.data);
}
} catch (error) {
showError(error.message || t('网络请求失败'));
} finally {
setLoading(false);
setRefreshing(false);
}
},
[t],
);
// 获取历史趋势数据
const fetchHistoryData = useCallback(
async (groupName, startTime, endTime) => {
setHistoryLoading((prev) => ({ ...prev, [groupName]: true }));
try {
let url = `/api/monitor/groups/${encodeURIComponent(groupName)}/history`;
if (startTime && endTime) {
url += `?start_time=${Math.floor(startTime.getTime() / 1000)}&end_time=${Math.floor(endTime.getTime() / 1000)}`;
} else {
url += '?period=24h';
}
const res = await API.get(url);
if (res.data.success) {
setHistoryData((prev) => ({ ...prev, [groupName]: res.data.data }));
}
} catch (error) {
console.error('获取历史数据失败:', error);
} finally {
setHistoryLoading((prev) => ({ ...prev, [groupName]: false }));
}
},
[],
);
useEffect(() => {
fetchGroupData();
// 每30秒刷新一次数据
const interval = setInterval(() => {
fetchGroupData(true);
}, 30000);
return () => clearInterval(interval);
}, [fetchGroupData]);
// 切换分组展开状态
const toggleGroupExpand = (groupName) => {
setExpandedGroups((prev) => {
const newState = { ...prev, [groupName]: !prev[groupName] };
if (newState[groupName] && !historyData[groupName]) {
fetchHistoryData(groupName);
}
return newState;
});
};
// 处理日期范围变更
const handleDateRangeChange = (groupName, dates) => {
setDateRange((prev) => ({ ...prev, [groupName]: dates }));
if (dates && dates.length === 2) {
fetchHistoryData(groupName, dates[0], dates[1]);
}
};
// 格式化时间戳
const formatTime = (timestamp) => {
if (!timestamp) return '-';
const date = new Date(timestamp * 1000);
return date.toLocaleString(i18n.language, {
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
});
};
// 格式化相对时间
const formatRelativeTime = (timestamp) => {
if (!timestamp) return '-';
const now = Date.now() / 1000;
const diff = now - timestamp;
if (diff < 60) return t('刚刚');
if (diff < 3600) return t('{{n}} 分钟前', { n: Math.floor(diff / 60) });
if (diff < 86400) return t('{{n}} 小时前', { n: Math.floor(diff / 3600) });
return t('{{n}} 天前', { n: Math.floor(diff / 86400) });
};
// 获取健康度颜色
const getHealthColor = (score) => {
if (score >= 90) return 'var(--ui-color-success)';
if (score >= 70) return 'var(--ui-color-warning)';
return 'var(--ui-color-danger)';
};
// 获取状态配置
const getStatusConfig = (status) => {
switch (status) {
case 'healthy':
return {
color: 'green',
icon: ,
text: t('健康'),
};
case 'warning':
return {
color: 'orange',
icon: ,
text: t('警告'),
};
case 'critical':
return {
color: 'red',
icon: ,
text: t('严重'),
};
default:
return { color: 'grey', icon: null, text: t('未知') };
}
};
// 获取渠道状态配置
const getChannelStatusConfig = (status) => {
switch (status) {
case 1:
return { color: 'green', text: t('启用') };
case 2:
return { color: 'grey', text: t('手动禁用') };
case 3:
return { color: 'orange', text: t('自动禁用') };
default:
return { color: 'grey', text: t('未知') };
}
};
// 渲染趋势图
const renderTrendChart = (dataPoints, height = 80) => {
if (!dataPoints || dataPoints.length === 0) return null;
const uptimeData = dataPoints.map((p) => p.uptime_percent);
const max = Math.max(...uptimeData, 100);
const min = Math.min(...uptimeData, 0);
const range = max - min || 1;
const points = uptimeData
.map((value, index) => {
const x = (index / (uptimeData.length - 1)) * 100;
const y = 100 - ((value - min) / range) * 100;
return `${x},${y}`;
})
.join(' ');
const avgUptime = uptimeData.reduce((a, b) => a + b, 0) / uptimeData.length;
const lineColor = getHealthColor(avgUptime);
return (
);
};
// 渠道列定义
const channelColumns = [
{
title: t('渠道名称'),
dataIndex: 'name',
key: 'name',
render: (text, record) => (
{text}
{record.priority > 0 && (
P{record.priority}
)}
),
},
{
title: t('状态'),
dataIndex: 'status',
key: 'status',
width: 100,
render: (status) => {
const config = getChannelStatusConfig(status);
return {config.text};
},
},
{
title: t('响应时间'),
dataIndex: 'response_time',
key: 'response_time',
width: 120,
render: (time) => {
if (!time) return '-';
let color = 'green';
if (time > 3000) color = 'red';
else if (time > 1000) color = 'orange';
return (
{time}ms
);
},
},
{
title: t('最后测试'),
dataIndex: 'test_time',
key: 'test_time',
width: 120,
render: (time) => (
{formatRelativeTime(time)}
),
},
{
title: t('支持模型'),
dataIndex: 'models',
key: 'models',
render: (models) => (
{models?.slice(0, 3).map((m, i) => (
{m}
))}
{models?.length > 3 && (
+{models.length - 3}
)}
),
},
];
// 模型统计列定义
const modelColumns = [
{
title: t('模型'),
dataIndex: 'model',
key: 'model',
render: (text) => {text},
},
{
title: t('可用率'),
dataIndex: 'uptime_percent',
key: 'uptime_percent',
render: (value) => (
),
},
{
title: t('可用/总数'),
key: 'count',
render: (_, record) => `${record.available_count}/${record.total_count}`,
},
{
title: t('平均响应'),
dataIndex: 'avg_response_time',
key: 'avg_response_time',
render: (value) => (value > 0 ? `${value}ms` : '-'),
},
];
if (loading) {
return (
);
}
return (
{/* 概览卡片 */}
{overview && (
{overview.total_groups}
{t('分组总数')}
{overview.healthy_groups}
{t('健康分组')}
{overview.warning_groups}
{t('警告分组')}
{overview.average_uptime.toFixed(1)}%
{t('平均可用率')}
)}
{/* 刷新按钮 */}
}
onClick={() => fetchGroupData(true)}
loading={refreshing}
>
{t('刷新')}
{groups.length === 0 ? (
) : (
{groups.map((group) => {
const isExpanded = expandedGroups[group.name];
const statusConfig = getStatusConfig(group.status);
const groupHistory = historyData[group.name];
const isHistoryLoading = historyLoading[group.name];
return (
{/* 分组头部 */}
toggleGroupExpand(group.name)}
>
{/* 健康度环形图 */}
{Math.round(group.health_score)}
{group.name}
{statusConfig.icon}
{statusConfig.text}
{t('最后测试')}:{' '}
{formatRelativeTime(group.last_test_time)}
{group.available_count}/{group.total_channels}{' '}
{t('可用')}
{group.auto_disabled_count > 0 && (
{group.auto_disabled_count} {t('自动禁用')}
)}
{/* 快速统计 */}
{group.uptime_percent.toFixed(1)}%
{t('可用率')}
{group.avg_response_time || '-'}
ms
{t('平均响应')}
{group.models?.length || 0}
{t('模型数')}
{isExpanded ? (
) : (
)}
{/* 展开详情 */}
{isExpanded && (
{/* 详细统计 */}
{group.uptime_percent.toFixed(1)}%
{t('可用率')}
{group.available_count}
{t('可用渠道')}
{group.disabled_count}
{t('禁用渠道')}
{group.auto_disabled_count}
{t('自动禁用')}
{group.avg_response_time || '-'}ms
{t('平均响应')}
{group.max_response_time || '-'}ms
{t('最慢响应')}
{group.min_response_time || '-'}ms
{t('最快响应')}
{group.models?.length || 0}
{t('支持模型')}
{/* 时间选择器 */}
{t('趋势时间范围')}:
handleDateRangeChange(group.name, dates)
}
placeholder={[t('开始时间'), t('结束时间')]}
/>
{/* 趋势图 */}
{isHistoryLoading ? (
) : (
groupHistory?.data_points && (
{t('可用率趋势')}
{formatTime(groupHistory.start_time)} -{' '}
{formatTime(groupHistory.end_time)}
{renderTrendChart(groupHistory.data_points, 100)}
)
)}
{/* 模型统计 */}
{/* 渠道列表 */}
)}
);
})}
)}
);
};
export default GroupMonitorAdmin;