"use client" import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card" import { Badge } from "@/components/ui/badge" import { Button } from "@/components/ui/button" import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell, Line, ComposedChart, } from "recharts" import { Users, Eye, Star, TrendingUp, Clock, Activity, Calendar, AlertTriangle, Loader2 } from "lucide-react" import { useState, useEffect } from "react" export function AnalyticsDashboard() { const [showHistoryModal, setShowHistoryModal] = useState(false) const [selectedDateRange, setSelectedDateRange] = useState("近7天") const [isLoading, setIsLoading] = useState(true) const [analyticsData, setAnalyticsData] = useState({ totalUsers: 0, todayActiveUsers: 0, todayActiveGrowth: 0, avgRating: 0, ratingGrowth: 0, totalApps: 0, newThisWeek: 0, userGrowth: 0, userGrowthText: "較上月", dailyUsageData: [], categoryData: [], topApps: [], hourlyData: [], satisfactionRate: 0, weeklyFeedback: 0, userAvgRating: 0, totalRatings: 0, systemLoadStatus: "normal", systemLoadAdvice: "", maxCpuPeak: 0, maxDailyUsers: 0, avgDailyUsers: 0, totalWeeklySessions: 0, hourlyAnalysis: "", hourlyAdvice: "" }) // 載入分析數據 const loadAnalyticsData = async () => { try { setIsLoading(true) const response = await fetch('/api/admin/analytics') const data = await response.json() if (data.success) { setAnalyticsData(data.data) } else { console.error('載入分析數據失敗:', data.error) } } catch (error) { console.error('載入分析數據錯誤:', error) } finally { setIsLoading(false) } } // 初始載入數據 useEffect(() => { loadAnalyticsData() }, []) // 使用API提供的24小時使用數據 const hourlyData = analyticsData.hourlyData || [] // 獲取顏色基於使用強度 const getBarColor = (intensity: string) => { switch (intensity) { case "peak": return "#ef4444" // 紅色 - 高峰期 case "high": return "#3b82f6" // 藍色 - 高使用期 case "normal": return "#6b7280" // 灰藍色 - 正常期 case "low": return "#9ca3af" // 灰色 - 低峰期 default: return "#6b7280" } } // 近7天使用趨勢數據(動態日期) const getRecentDates = () => { const dates = [] const today = new Date() for (let i = 6; i >= 0; i--) { const date = new Date(today) date.setDate(today.getDate() - i) dates.push({ date: `${date.getMonth() + 1}/${date.getDate()}`, fullDate: date.toLocaleDateString("zh-TW"), dayName: ["日", "一", "二", "三", "四", "五", "六"][date.getDay()], }) } return dates } const recentDates = getRecentDates() const dailyUsageData = [ { ...recentDates[0], users: 245, sessions: 189, cpuPeak: 65, avgCpu: 45, memoryPeak: 58, requests: 1240 }, { ...recentDates[1], users: 267, sessions: 203, cpuPeak: 68, avgCpu: 48, memoryPeak: 62, requests: 1356 }, { ...recentDates[2], users: 289, sessions: 221, cpuPeak: 72, avgCpu: 52, memoryPeak: 65, requests: 1478 }, { ...recentDates[3], users: 312, sessions: 245, cpuPeak: 75, avgCpu: 55, memoryPeak: 68, requests: 1589 }, { ...recentDates[4], users: 298, sessions: 234, cpuPeak: 73, avgCpu: 53, memoryPeak: 66, requests: 1523 }, { ...recentDates[5], users: 334, sessions: 267, cpuPeak: 78, avgCpu: 58, memoryPeak: 71, requests: 1678 }, { ...recentDates[6], users: 356, sessions: 289, cpuPeak: 82, avgCpu: 62, memoryPeak: 75, requests: 1789 }, ] const categoryData = [ { name: "AI工具", value: 35, color: "#3b82f6", users: 3083, apps: 45 }, { name: "數據分析", value: 25, color: "#ef4444", users: 1565, apps: 32 }, { name: "自動化", value: 20, color: "#10b981", users: 856, apps: 25 }, { name: "機器學習", value: 15, color: "#f59e0b", users: 743, apps: 19 }, { name: "其他", value: 5, color: "#8b5cf6", users: 234, apps: 6 }, ] const topApps = [ { name: "智能客服助手", views: 1234, rating: 4.8, category: "AI工具" }, { name: "數據視覺化平台", views: 987, rating: 4.6, category: "數據分析" }, { name: "自動化工作流", views: 856, rating: 4.7, category: "自動化" }, { name: "預測分析系統", views: 743, rating: 4.5, category: "機器學習" }, { name: "文本分析工具", views: 692, rating: 4.4, category: "AI工具" }, ] // 獲取歷史數據 - 使用真實數據 const getHistoricalData = (range: string) => { // 所有時間範圍都使用真實的 dailyUsageData // 因為我們已經在API中獲取了近7天的真實數據 return analyticsData.dailyUsageData || [] } // 獲取歷史統計數據 - 使用真實數據 const getHistoricalStats = (range: string) => { const data = getHistoricalData(range) if (!data || data.length === 0) { return { avgUsers: 0, maxUsers: 0, avgCpu: 0, maxCpu: 0, } } const users = data.map((d) => d.users || 0) const cpus = data.map((d) => d.cpuPeak || 0) return { avgUsers: Math.round(users.reduce((a, b) => a + b, 0) / users.length), maxUsers: Math.max(...users), avgCpu: Math.round(cpus.reduce((a, b) => a + b, 0) / cpus.length), maxCpu: Math.max(...cpus), } } return (

數據分析

{/* 關鍵指標卡片 */}
總用戶數
{isLoading ? ( ) : ( analyticsData.totalUsers.toLocaleString() )}

{isLoading ? ( "載入中..." ) : ( <> +{analyticsData.userGrowth}% {analyticsData.userGrowthText} )}

今日活躍用戶
{isLoading ? ( ) : ( analyticsData.todayActiveUsers )}

{isLoading ? ( "載入中..." ) : ( <> +{analyticsData.todayActiveGrowth}% 較昨日 )}

平均評分
{isLoading ? ( ) : ( analyticsData.avgRating )}

{isLoading ? ( "載入中..." ) : ( <> +{analyticsData.ratingGrowth} 較上週 )}

應用總數
{isLoading ? ( ) : ( analyticsData.totalApps )}

{isLoading ? ( "載入中..." ) : ( <> +{analyticsData.newThisWeek} 本週新增 )}

{/* 圖表區域 */}
{/* 近7天使用趨勢與系統負載 */}
近7天使用趨勢與系統負載

用戶活躍度與CPU使用率關聯分析

{ if (name === "users") { return [`${value} 人`, "活躍用戶"] } if (name === "cpuPeak") { return [`${value}%`, "CPU峰值"] } return [value, name] }} labelFormatter={(label, payload) => { if (payload && payload.length > 0) { const data = payload[0].payload return `${data.fullDate} (週${data.dayName})` } return label }} contentStyle={{ backgroundColor: "white", border: "1px solid #e5e7eb", borderRadius: "8px", boxShadow: "0 4px 6px -1px rgba(0, 0, 0, 0.1)", fontSize: "14px", }} /> {/* 系統建議 - 動態狀態 */}
{analyticsData.systemLoadStatus === 'critical' ? ( ) : analyticsData.systemLoadStatus === 'warning' ? ( ) : analyticsData.systemLoadStatus === 'monitor' ? ( ) : analyticsData.systemLoadStatus === 'low' ? ( ) : ( )}

系統負載建議

{analyticsData.systemLoadAdvice || '正在分析系統負載狀態...'}

{/* 應用類別分布 */} 應用類別分布 `${name} ${(percent * 100).toFixed(0)}%`} labelLine={false} > {analyticsData.categoryData.map((entry, index) => ( ))} { const data = props.payload return [ [`${value}%`, "占比"], [`${data.users?.toLocaleString()} 人`, "用戶數"], [`${data.apps} 個`, "應用數量"], ] }} labelFormatter={(label) => label} contentStyle={{ backgroundColor: "white", border: "1px solid #e5e7eb", borderRadius: "8px", boxShadow: "0 4px 6px -1px rgba(0, 0, 0, 0.1)", fontSize: "14px", }} /> {/* 添加圖例說明 */}
{analyticsData.categoryData.map((category, index) => (
{category.name} {category.value}%
))}
{/* 24小時使用模式 - 優化版 */} 24小時使用模式

今日各時段用戶活躍度分析

高峰期 (80%+)
高使用期
正常期
低峰期
`${value}:00`} /> { const data = props.payload const getIntensityText = (intensity: string) => { switch (intensity) { case "peak": return "高峰期" case "high": return "高使用期" case "normal": return "正常期" case "low": return "低峰期" default: return "未知" } } return [ [`${value} 人`, "同時在線用戶"], [`${getIntensityText(data.intensity)}`, "時段分類"], [`${data.cpuUsage}%`, "CPU使用率"], [`${data.memoryUsage}%`, "記憶體使用率"], [`${data.period}`, "時段特性"], ] }} labelFormatter={(label) => `${label}:00 時段`} contentStyle={{ backgroundColor: "white", border: "1px solid #e5e7eb", borderRadius: "8px", boxShadow: "0 4px 6px -1px rgba(0, 0, 0, 0.1)", fontSize: "14px", minWidth: "220px", }} /> getBarColor(entry.intensity)}> {hourlyData.map((entry, index) => ( ))}

尖峰時段分析: {analyticsData.hourlyAnalysis || '正在分析24小時使用模式...'} {analyticsData.hourlyAdvice && ( {analyticsData.hourlyAdvice} )}

{/* 熱門應用排行 */} 熱門應用排行
{analyticsData.topApps.map((app, index) => (
{index + 1}

{app.name}

{app.category}

{app.views}
{app.rating}
))}
{/* 用戶回饋摘要 */} 用戶回饋摘要
{isLoading ? ( ) : ( `${analyticsData.satisfactionRate}%` )}

滿意度

{isLoading ? ( ) : ( analyticsData.userAvgRating || analyticsData.avgRating )}

平均評分

{analyticsData.totalRatings > 0 && (

{analyticsData.totalRatings} 個評分

)}
{isLoading ? ( ) : ( analyticsData.weeklyFeedback )}

本週回饋

{/* 歷史數據查看模態框 */} {showHistoryModal && (

歷史數據查看

{/* 日期範圍選擇 */}
{["近7天", "近30天", "近3個月", "近6個月"].map((range) => ( ))}
{/* 歷史數據圖表 */}
歷史使用趨勢 - {selectedDateRange} { if (name === "users") { return [`${value} 人`, "活躍用戶"] } if (name === "cpuPeak") { return [`${value}%`, "CPU峰值"] } return [value, name] }} labelFormatter={(label, payload) => { if (payload && payload.length > 0) { const data = payload[0].payload return data.fullDate || label } return label }} contentStyle={{ backgroundColor: "white", border: "1px solid #e5e7eb", borderRadius: "8px", boxShadow: "0 4px 6px -1px rgba(0, 0, 0, 0.1)", fontSize: "14px", }} /> {/* 歷史數據統計摘要 */}
{getHistoricalStats(selectedDateRange).avgUsers}

平均用戶數

{getHistoricalStats(selectedDateRange).maxUsers}

最高用戶數

{getHistoricalStats(selectedDateRange).avgCpu}%

平均CPU使用率

{getHistoricalStats(selectedDateRange).maxCpu}%

最高CPU使用率

)}
) }