"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.userGrowth}% {analyticsData.userGrowthText} > )}
{isLoading ? ( "載入中..." ) : ( <> +{analyticsData.todayActiveGrowth}% 較昨日 > )}
{isLoading ? ( "載入中..." ) : ( <> +{analyticsData.ratingGrowth} 較上週 > )}
{isLoading ? ( "載入中..." ) : ( <> +{analyticsData.newThisWeek} 本週新增 > )}
用戶活躍度與CPU使用率關聯分析
系統負載建議
{analyticsData.systemLoadAdvice || '正在分析系統負載狀態...'}
今日各時段用戶活躍度分析
{app.category}
滿意度
平均評分
{analyticsData.totalRatings > 0 && ({analyticsData.totalRatings} 個評分
)}本週回饋
平均用戶數
最高用戶數
平均CPU使用率
最高CPU使用率