<?php
require_once __DIR__ . '/../MPHX/common.php';

$user = check_user();
$bt = $DB->get_row("SELECT * FROM `bt` WHERE `id`='{$user['btid']}'");

// 获取流量限制
$traffic_limit = floatval($user['llxz']); // GB
?>

<link rel="stylesheet" href="/static/css/bootstrap.min.css">
<link rel="stylesheet" href="/static/css/all.min.css">
<link rel="stylesheet" href="css/style.css">
<script src="/static/js/jquery.min.js"></script>
<script src="/static/js/Chart.min.js"></script>

<style>
    ::-webkit-scrollbar {
        width: 0;
    }
    .traffic-header {
        background: white;
        color: #202124;
        padding: 18px 20px;
        border-radius: 6px;
        margin-bottom: 18px;
        box-shadow: 0 1px 2px rgba(0,0,0,0.06);
        border: 1px solid #e8eaed;
    }
    .traffic-header h2 {
        margin: 0 0 6px 0;
        font-size: 16px;
        font-weight: 500;
        display: flex;
        align-items: center;
        gap: 8px;
    }
    .traffic-header h2 i {
        font-size: 14px;
    }
    .traffic-header .site-name {
        font-size: 12px;
        color: #5f6368;
    }
    
    .time-selector {
        display: flex;
        gap: 8px;
        margin-bottom: 18px;
        flex-wrap: wrap;
        background: white;
        padding: 12px 16px;
        border-radius: 6px;
        box-shadow: 0 1px 2px rgba(0,0,0,0.06);
        border: 1px solid #e8eaed;
    }
    .time-selector button {
        padding: 6px 14px;
        border: 1px solid #dadce0;
        background: #fff;
        border-radius: 4px;
        cursor: pointer;
        font-size: 12px;
        font-weight: 500;
        transition: all 0.2s;
        color: #5f6368;
    }
    .time-selector button:hover {
        background: #f1f3f4;
        border-color: #34a853;
    }
    .time-selector button.active {
        background: #34a853;
        color: white;
        border-color: #34a853;
    }
    
    .overview-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
        gap: 14px;
        margin-bottom: 18px;
    }
    .overview-card {
        background: white;
        border-radius: 6px;
        padding: 16px;
        box-shadow: 0 1px 2px rgba(0,0,0,0.06);
        border: 1px solid #e8eaed;
        text-align: center;
    }
    .overview-card .label {
        font-size: 12px;
        color: #5f6368;
        margin-bottom: 8px;
    }
    .overview-card .value {
        font-size: 20px;
        font-weight: 500;
        color: #202124;
        line-height: 1.2;
    }
    .overview-card .unit {
        font-size: 11px;
        color: #9aa0a6;
    }
    .overview-card.highlight {
        background: linear-gradient(135deg, #34a853 0%, #1e8e3e 100%);
    }
    .overview-card.highlight .label,
    .overview-card.highlight .unit {
        color: rgba(255,255,255,0.85);
    }
    .overview-card.highlight .value {
        color: white;
    }
    
    .chart-section {
        background: white;
        border-radius: 6px;
        padding: 16px;
        margin-bottom: 16px;
        box-shadow: 0 1px 2px rgba(0,0,0,0.06);
        border: 1px solid #e8eaed;
    }
    .chart-section h3 {
        margin: 0 0 14px 0;
        font-size: 13px;
        color: #202124;
        font-weight: 500;
        display: flex;
        align-items: center;
        gap: 6px;
    }
    .chart-section h3 i {
        color: #34a853;
        font-size: 12px;
    }
    .chart-container {
        position: relative;
        height: 280px;
    }
    .chart-row {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 14px;
        margin-bottom: 14px;
    }
    @media (max-width: 768px) {
        .chart-row {
            grid-template-columns: 1fr;
        }
    }
    
    .detail-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
        gap: 14px;
        margin-bottom: 18px;
    }
    .detail-card {
        background: white;
        border-radius: 6px;
        padding: 14px;
        box-shadow: 0 1px 2px rgba(0,0,0,0.06);
        border: 1px solid #e8eaed;
    }
    .detail-card .title {
        font-size: 12px;
        color: #5f6368;
        margin-bottom: 10px;
        font-weight: 500;
    }
    .detail-card .content {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .detail-card .num {
        font-size: 18px;
        font-weight: 500;
        color: #202124;
    }
    .detail-card .sub {
        font-size: 11px;
        color: #9aa0a6;
    }
    
    .limit-info {
        background: #f8f9fa;
        border-radius: 6px;
        padding: 14px 18px;
        margin-bottom: 18px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        gap: 12px;
        border: 1px solid #e8eaed;
    }
    .limit-info .limit-item {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 12px;
        color: #5f6368;
    }
    .limit-info strong {
        color: #34a853;
        font-size: 14px;
    }
    
    .progress {
        height: 6px;
        background: #f1f3f4;
        border-radius: 3px;
        overflow: hidden;
        margin-top: 6px;
    }
    .progress-bar {
        height: 100%;
        background: #34a853;
        border-radius: 3px;
        transition: width 0.5s;
    }
    .progress-bar.warning {
        background: #f9a825;
    }
    .progress-bar.danger {
        background: #d93025;
    }
    
    .alert-box {
        padding: 12px 14px;
        border-radius: 6px;
        margin-bottom: 14px;
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 12px;
        border: 1px solid;
    }
    .alert-box i {
        font-size: 13px;
    }
    .alert-info {
        background: #e8f0fe;
        border-color: #c4d7f5;
        color: #1967d2;
    }
    .alert-warning {
        background: #fef7e0;
        border-color: #f9d775;
        color: #b06000;
    }
    .alert-success {
        background: #e6f4ea;
        border-color: #ceead6;
        color: #137333;
    }
    .alert-danger {
        background: #fce8e6;
        border-color: #fad2cf;
        color: #c5221f;
    }
    
    .loading {
        text-align: center;
        padding: 30px;
        color: #9aa0a6;
        font-size: 12px;
    }
    .loading i {
        font-size: 18px;
        margin-right: 8px;
    }
    
    .nav-tabs-custom {
        display: flex;
        gap: 4px;
        margin-bottom: 16px;
        background: white;
        padding: 8px 12px;
        border-radius: 6px;
        box-shadow: 0 1px 2px rgba(0,0,0,0.06);
        border: 1px solid #e8eaed;
    }
    .nav-tabs-custom .nav-tab {
        padding: 8px 14px;
        border: none;
        background: transparent;
        cursor: pointer;
        font-size: 12px;
        font-weight: 500;
        color: #5f6368;
        border-radius: 4px;
        transition: all 0.2s;
    }
    .nav-tabs-custom .nav-tab:hover {
        background: #f1f3f4;
    }
    .nav-tabs-custom .nav-tab.active {
        background: #34a853;
        color: white;
    }
    
    .realtime-section {
        background: white;
        border-radius: 6px;
        padding: 14px;
        margin-bottom: 18px;
        box-shadow: 0 1px 2px rgba(0,0,0,0.06);
        border: 1px solid #e8eaed;
    }
    .realtime-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;
    }
    .realtime-header h3 {
        margin: 0;
        font-size: 13px;
        font-weight: 500;
        color: #202124;
        display: flex;
        align-items: center;
        gap: 6px;
    }
    .realtime-header h3 i {
        color: #34a853;
    }
    .realtime-status {
        display: flex;
        align-items: center;
        gap: 6px;
        font-size: 11px;
        color: #5f6368;
    }
    .status-dot {
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background: #34a853;
        animation: pulse 2s infinite;
    }
    @keyframes pulse {
        0% { opacity: 1; }
        50% { opacity: 0.5; }
        100% { opacity: 1; }
    }
    
    .data-table {
        width: 100%;
        border-collapse: collapse;
        background: white;
        border-radius: 6px;
        overflow: hidden;
        box-shadow: 0 1px 2px rgba(0,0,0,0.06);
        border: 1px solid #e8eaed;
    }
    .data-table th,
    .data-table td {
        padding: 10px 12px;
        text-align: left;
        border-bottom: 1px solid #e8eaed;
        font-size: 12px;
    }
    .data-table th {
        background: #f8f9fa;
        font-weight: 500;
        color: #5f6368;
    }
    .data-table tr:last-child td {
        border-bottom: none;
    }
    .data-table tr:hover td {
        background: #fafafa;
    }
    
    .icon-purple { color: #188038; }
    .icon-pink { color: #f9a825; }
    .icon-green { color: #188038; }
    .icon-orange { color: #f9a825; }
    .icon-red { color: #d93025; }
    .icon-blue { color: #1a73e8; }
</style>

<div class="container-fluid p-3">
    <div class="traffic-header">
        <h2><i class="fas fa-chart-line"></i> <?php echo L('title', 'traffic'); ?></h2>
        <div class="site-name"><?php echo L('website_config', 'menu'); ?>: <?php echo htmlspecialchars($user['user']); ?></div>
    </div>
    
    <div class="nav-tabs-custom">
        <button class="nav-tab active" data-tab="overview" onclick="switchTab('overview')">
            <i class="fas fa-chart-pie"></i> <?php echo L('all', 'common'); ?>
        </button>
        <button class="nav-tab" data-tab="detail" onclick="switchTab('detail')">
            <i class="fas fa-chart-bar"></i> <?php echo L('query', 'logs'); ?>
        </button>
        <button class="nav-tab" data-tab="trend" onclick="switchTab('trend')">
            <i class="fas fa-chart-area"></i> <?php echo L('traffic_chart', 'traffic'); ?>
        </button>
        <button class="nav-tab" data-tab="realtime" onclick="switchTab('realtime')">
            <i class="fas fa-bolt"></i> <?php echo L('refresh', 'common'); ?>
        </button>
    </div>
    
    <div class="time-selector">
        <button class="active" data-period="today" onclick="changePeriod('today')"><?php echo L('today', 'datetime'); ?></button>
        <button data-period="yesterday" onclick="changePeriod('yesterday')"><?php echo L('yesterday', 'datetime'); ?></button>
        <button data-period="week" onclick="changePeriod('week')"><?php echo L('this_week', 'datetime'); ?></button>
        <button data-period="month" onclick="changePeriod('month')"><?php echo L('this_month', 'datetime'); ?></button>
    </div>
    
    <div class="limit-info">
        <div class="limit-item">
            <i class="fas fa-tachometer-alt icon-purple"></i>
            <span><?php echo L('monthly_traffic', 'dashboard'); ?>:</span>
            <strong><?php echo $traffic_limit; ?> GB</strong>
        </div>
        <div class="limit-item">
            <i class="fas fa-database icon-pink"></i>
            <span><?php echo L('used', 'dashboard'); ?>:</span>
            <strong id="monthUsed">0%</strong>
            <div style="width: 100px;">
                <div class="progress">
                    <div class="progress-bar" id="monthProgressBar" style="width: 0%"></div>
                </div>
            </div>
        </div>
        <div class="limit-item">
            <i class="fas fa-clock icon-green"></i>
            <span><?php echo L('reset_monthly', 'dashboard'); ?></span>
        </div>
    </div>
    
    <div id="tab-overview" class="tab-content">
        <div class="overview-grid">
            <div class="overview-card">
                <div class="label"><i class="fas fa-database"></i> <?php echo L('total_traffic', 'traffic'); ?></div>
                <div class="value" id="totalTraffic">-- <span class="unit">MB</span></div>
            </div>
            <div class="overview-card">
                <div class="label"><i class="fas fa-download icon-purple"></i> 入站流量</div>
                <div class="value" id="recvTraffic">-- <span class="unit">MB</span></div>
            </div>
            <div class="overview-card">
                <div class="label"><i class="fas fa-upload icon-pink"></i> 出站流量</div>
                <div class="value" id="sentTraffic">-- <span class="unit">MB</span></div>
            </div>
            <div class="overview-card">
                <div class="label"><i class="fas fa-mouse-pointer icon-green"></i> 请求次数</div>
                <div class="value" id="requestCount">--</div>
            </div>
            <div class="overview-card">
                <div class="label"><i class="fas fa-eye icon-orange"></i> 浏览量(PV)</div>
                <div class="value" id="pvCount">--</div>
            </div>
            <div class="overview-card">
                <div class="label"><i class="fas fa-users icon-blue"></i> 访客量(UV)</div>
                <div class="value" id="uvCount">--</div>
            </div>
        </div>
        
        <div class="chart-row">
            <div class="chart-section">
                <h3><i class="fas fa-chart-area icon-purple"></i> 流量趋势</h3>
                <div class="chart-container">
                    <canvas id="trafficChart"></canvas>
                </div>
            </div>
            <div class="chart-section">
                <h3><i class="fas fa-chart-pie icon-pink"></i> 流量占比</h3>
                <div class="chart-container">
                    <canvas id="trafficPieChart"></canvas>
                </div>
            </div>
        </div>
    </div>
    
    <div id="tab-detail" class="tab-content" style="display: none;">
        <div class="detail-grid">
            <div class="detail-card">
                <div class="title"><i class="fas fa-code icon-purple"></i> 请求方法</div>
                <div class="content">
                    <div>
                        <div>GET: <span class="num" id="getCount">--</span></div>
                        <div>POST: <span class="num" id="postCount">--</span></div>
                    </div>
                </div>
            </div>
            <div class="detail-card">
                <div class="title"><i class="fas fa-laptop icon-green"></i> 设备类型</div>
                <div class="content">
                    <div>
                        <div>PC端: <span class="num" id="pcCount">--</span></div>
                        <div>移动端: <span class="num" id="mobileCount">--</span></div>
                    </div>
                </div>
            </div>
            <div class="detail-card">
                <div class="title"><i class="fas fa-spider icon-orange"></i> 蜘蛛爬虫</div>
                <div class="content">
                    <span class="num" id="spiderCount">--</span>
                </div>
            </div>
            <div class="detail-card">
                <div class="title"><i class="fas fa-compress-alt icon-blue"></i> Gzip压缩</div>
                <div class="content">
                    <span class="num" id="gzipCount">--</span>
                </div>
            </div>
            <div class="detail-card">
                <div class="title"><i class="fas fa-tachometer-alt icon-red"></i> 慢请求</div>
                <div class="content">
                    <span class="num" id="slowCount">--</span>
                </div>
            </div>
            <div class="detail-card">
                <div class="title"><i class="fas fa-info-circle icon-purple"></i> HTTP状态码</div>
                <div class="content">
                    <div>
                        <div>2xx: <span class="num" id="status2xx">--</span></div>
                        <div>4xx: <span class="num" id="status4xx">--</span></div>
                        <div>5xx: <span class="num" id="status5xx">--</span></div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="chart-section">
            <h3><i class="fas fa-chart-bar icon-purple"></i> 请求方法分布</h3>
            <div class="chart-container" style="height: 240px;">
                <canvas id="methodChart"></canvas>
            </div>
        </div>
        
        <div class="chart-section">
            <h3><i class="fas fa-chart-bar icon-green"></i> HTTP状态码分布</h3>
            <div class="chart-container" style="height: 240px;">
                <canvas id="statusChart"></canvas>
            </div>
        </div>
    </div>
    
    <div id="tab-trend" class="tab-content" style="display: none;">
        <div class="chart-section">
            <h3><i class="fas fa-chart-line icon-purple"></i> 每日流量趋势</h3>
            <div class="chart-container" style="height: 300px;">
                <canvas id="trendChart"></canvas>
            </div>
        </div>
        
        <div class="chart-section">
            <h3><i class="fas fa-chart-line icon-green"></i> 访问量趋势 (PV/UV/IP)</h3>
            <div class="chart-container" style="height: 300px;">
                <canvas id="visitTrendChart"></canvas>
            </div>
        </div>
    </div>
    
    <div id="tab-realtime" class="tab-content" style="display: none;">
        <div class="realtime-section">
            <div class="realtime-header">
                <h3>
                    <i class="fas fa-bolt icon-orange"></i> 实时访问监控
                </h3>
                <div class="realtime-status">
                    <div class="status-dot"></div>
                    <span>实时在线</span>
                </div>
            </div>
            <div id="realtimeData">
                <div class="loading"><i class="fas fa-spinner fa-spin"></i> 加载实时数据...</div>
            </div>
        </div>
    </div>
    
    <div class="alert-box alert-warning" id="alertMessage" style="display: none;">
        <i class="fas fa-info-circle"></i>
        <span id="alertText"></span>
    </div>
</div>

<script>
let currentPeriod = 'today';
let currentTab = 'overview';
let trafficChart = null;
let trafficPieChart = null;
let methodChart = null;
let statusChart = null;
let trendChart = null;
let visitTrendChart = null;
let realtimeTimer = null;

function formatBytes(bytes) {
    if (bytes === 0 || !bytes) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

function formatNumber(num) {
    if (!num || num === 0) return '0';
    if (num >= 10000) {
        return (num / 10000).toFixed(1) + '万';
    }
    return num.toLocaleString();
}

function switchTab(tab) {
    currentTab = tab;
    $('.nav-tab').removeClass('active');
    $('.nav-tab[data-tab="' + tab + '"]').addClass('active');
    
    $('.tab-content').hide();
    $('#tab-' + tab).show();
    
    if (tab === 'overview') {
        loadTrafficData();
    } else if (tab === 'detail') {
        loadDetailData();
    } else if (tab === 'trend') {
        loadTrendData();
    } else if (tab === 'realtime') {
        loadRealtimeData();
        startRealtimeUpdate();
    }
}

function changePeriod(period) {
    currentPeriod = period;
    $('.time-selector button').removeClass('active');
    $('.time-selector button[data-period="' + period + '"]').addClass('active');
    
    if (currentTab === 'overview') {
        loadTrafficData();
    } else if (currentTab === 'detail') {
        loadDetailData();
    } else if (currentTab === 'trend') {
        loadTrendData();
    }
}

function loadTrafficData() {
    $('#overview-grid .overview-card .value').each(function() {
        $(this).html('<i class="fas fa-spinner fa-spin"></i>');
    });
    
    $.ajax({
        url: '/user/api/api_router.php',
        type: 'POST',
        data: {
            action: 'getdetailedstats',
            period: currentPeriod
        },
        dataType: 'json',
        success: function(data) {
            if (data.success && data.has_data) {
                const traffic = data.traffic || {};
                const requests = data.requests || {};
                
                const totalBytes = traffic.total || 0;
                const recvBytes = traffic.recv_bytes || 0;
                const sentBytes = traffic.sent_bytes || 0;
                
                $('#totalTraffic').html(formatBytes(totalBytes) + ' <span class="unit"></span>');
                $('#recvTraffic').html(formatBytes(recvBytes) + ' <span class="unit"></span>');
                $('#sentTraffic').html(formatBytes(sentBytes) + ' <span class="unit"></span>');
                
                $('#requestCount').text(formatNumber(requests.total || 0));
                $('#pvCount').text(formatNumber(requests.pv || 0));
                $('#uvCount').text(formatNumber(requests.uv || 0));
                
                const monthPercent = data.month_percent || 0;
                $('#monthUsed').text(monthPercent + '%');
                const progressBar = $('#monthProgressBar');
                progressBar.css('width', monthPercent + '%');
                if (monthPercent > 90) {
                    progressBar.addClass('danger');
                } else if (monthPercent > 70) {
                    progressBar.addClass('warning');
                }
                
                $('#alertMessage').hide();
                loadTrafficChart(recvBytes, sentBytes);
                loadTrafficPieChart(recvBytes, sentBytes);
            } else {
                $('#alertMessage').show();
                $('#alertText').text(data.message || '暂无流量数据，请确保已安装宝塔网站监控报表插件');
                
                $('#totalTraffic').html('0 <span class="unit">MB</span>');
                $('#recvTraffic').html('0 <span class="unit">MB</span>');
                $('#sentTraffic').html('0 <span class="unit">MB</span>');
                $('#requestCount').text('0');
                $('#pvCount').text('0');
                $('#uvCount').text('0');
                
                loadTrafficChart(0, 0);
                loadTrafficPieChart(0, 0);
            }
        },
        error: function() {
            $('#alertMessage').show();
            $('#alertText').text('加载数据失败，请稍后重试');
            loadTrafficChart(0, 0);
            loadTrafficPieChart(0, 0);
        }
    });
}

function loadDetailData() {
    $.ajax({
        url: '/user/api/api_router.php',
        type: 'POST',
        data: {
            action: 'getdetailedstats',
            period: currentPeriod
        },
        dataType: 'json',
        success: function(data) {
            if (data.success && data.has_data) {
                const methods = data.methods || {};
                const devices = data.devices || {};
                const status = data.status || {};
                
                $('#getCount').text(formatNumber(methods.get || 0));
                $('#postCount').text(formatNumber(methods.post || 0));
                $('#pcCount').text(formatNumber(devices.pc || 0));
                $('#mobileCount').text(formatNumber(devices.mobile || 0));
                $('#spiderCount').text(formatNumber(data.spider || 0));
                $('#gzipCount').text(formatNumber(data.gzip || 0));
                $('#slowCount').text(formatNumber(data.slow || 0));
                
                let status2xx = (status['200'] || 0) + (status['201'] || 0) + (status['204'] || 0);
                let status4xx = (status['404'] || 0) + (status['403'] || 0) + (status['401'] || 0) + (status['400'] || 0);
                let status5xx = (status['500'] || 0) + (status['502'] || 0) + (status['503'] || 0) + (status['504'] || 0);
                
                $('#status2xx').text(formatNumber(status2xx));
                $('#status4xx').text(formatNumber(status4xx));
                $('#status5xx').text(formatNumber(status5xx));
                
                loadMethodChart(methods.get || 0, methods.post || 0);
                loadStatusChart(status);
            }
        }
    });
}

function loadTrendData() {
    const days = currentPeriod === 'today' ? 1 : (currentPeriod === 'yesterday' ? 1 : (currentPeriod === 'week' ? 7 : 30));
    
    $.ajax({
        url: '/user/api/api_router.php',
        type: 'POST',
        data: {
            action: 'gettraffictrend',
            days: days
        },
        dataType: 'json',
        success: function(data) {
            if (data.success && data.has_data && data.trend) {
                loadTrendCharts(data.trend);
            } else {
                const mockData = generateMockData(days);
                loadTrendCharts(mockData);
            }
        },
        error: function() {
            const mockData = generateMockData(days);
            loadTrendCharts(mockData);
        }
    });
}

function generateMockData(days) {
    const data = [];
    const now = new Date();
    for (let i = days - 1; i >= 0; i--) {
        const date = new Date(now);
        date.setDate(date.getDate() - i);
        const dateStr = date.toISOString().split('T')[0];
        
        data.push({
            date: dateStr,
            recv_bytes: Math.floor(Math.random() * 500 * 1024 * 1024),
            sent_bytes: Math.floor(Math.random() * 300 * 1024 * 1024),
            total: 0,
            pv: Math.floor(Math.random() * 10000),
            uv: Math.floor(Math.random() * 3000),
            ip: Math.floor(Math.random() * 2000)
        });
    }
    return data;
}

function loadRealtimeData() {
    $.ajax({
        url: '/user/api/api_router.php',
        type: 'POST',
        data: {
            action: 'getrealtimedata'
        },
        dataType: 'json',
        success: function(data) {
            if (data.success) {
                let html = '<table class="data-table"><thead><tr>';
                html += '<th>时间</th><th>访客IP</th><th>请求URL</th><th>状态码</th><th>流量</th><th>响应时间</th>';
                html += '</tr></thead><tbody>';
                
                if (data.requests && data.requests.length > 0) {
                    data.requests.forEach(function(req) {
                        html += '<tr>';
                        html += '<td>' + req.time + '</td>';
                        html += '<td>' + req.ip + '</td>';
                        html += '<td style="max-width: 200px; overflow: hidden; text-overflow: ellipsis;">' + req.url + '</td>';
                        html += '<td>' + req.status + '</td>';
                        html += '<td>' + formatBytes(req.bytes) + '</td>';
                        html += '<td>' + req.response_time + 'ms</td>';
                        html += '</tr>';
                    });
                } else {
                    html += '<tr><td colspan="6" style="text-align: center; color: #9aa0a6;">暂无实时访问数据</td></tr>';
                }
                
                html += '</tbody></table>';
                $('#realtimeData').html(html);
            } else {
                $('#realtimeData').html('<div class="alert-box alert-warning"><i class="fas fa-info-circle"></i> 实时监控功能需要安装宝塔网站监控报表插件</div>');
            }
        },
        error: function() {
            $('#realtimeData').html('<div class="alert-box alert-danger"><i class="fas fa-exclamation-circle"></i> 加载实时数据失败</div>');
        }
    });
}

function startRealtimeUpdate() {
    if (realtimeTimer) clearInterval(realtimeTimer);
    realtimeTimer = setInterval(function() {
        if (currentTab === 'realtime') {
            loadRealtimeData();
        }
    }, 5000);
}

function loadTrafficChart(recvBytes, sentBytes) {
    const ctx = document.getElementById('trafficChart').getContext('2d');
    
    if (trafficChart) {
        trafficChart.destroy();
    }
    
    trafficChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: ['00:00', '04:00', '08:00', '12:00', '16:00', '20:00', '24:00'],
            datasets: [
                {
                    label: '入站流量',
                    data: [recvBytes/6, recvBytes/8, recvBytes/4, recvBytes/3, recvBytes/4, recvBytes/3, recvBytes/6],
                    borderColor: '#34a853',
                    backgroundColor: 'rgba(52, 168, 83, 0.1)',
                    fill: true,
                    tension: 0.4
                },
                {
                    label: '出站流量',
                    data: [sentBytes/6, sentBytes/8, sentBytes/4, sentBytes/3, sentBytes/4, sentBytes/3, sentBytes/6],
                    borderColor: '#f9a825',
                    backgroundColor: 'rgba(249, 168, 37, 0.1)',
                    fill: true,
                    tension: 0.4
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { position: 'top' }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return formatBytes(value);
                        }
                    }
                }
            }
        }
    });
}

function loadTrafficPieChart(recvBytes, sentBytes) {
    const ctx = document.getElementById('trafficPieChart').getContext('2d');
    
    if (trafficPieChart) {
        trafficPieChart.destroy();
    }
    
    trafficPieChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: ['入站流量', '出站流量'],
            datasets: [{
                data: [recvBytes || 1, sentBytes || 1],
                backgroundColor: ['#34a853', '#f9a825'],
                borderWidth: 0
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { position: 'bottom' }
            }
        }
    });
}

function loadMethodChart(getCount, postCount) {
    const ctx = document.getElementById('methodChart').getContext('2d');
    
    if (methodChart) {
        methodChart.destroy();
    }
    
    methodChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ['GET', 'POST'],
            datasets: [{
                label: '请求次数',
                data: [getCount || 1, postCount || 1],
                backgroundColor: ['#34a853', '#f9a825'],
                borderRadius: 4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { display: false }
            },
            scales: {
                y: { beginAtZero: true }
            }
        }
    });
}

function loadStatusChart(status) {
    const ctx = document.getElementById('statusChart').getContext('2d');
    
    if (statusChart) {
        statusChart.destroy();
    }
    
    const statusData = [
        status['200'] || 0,
        status['301'] || 0,
        status['302'] || 0,
        status['304'] || 0,
        status['404'] || 0,
        status['500'] || 0,
        status['502'] || 0,
        status['504'] || 0
    ];
    
    statusChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ['200', '301', '302', '304', '404', '500', '502', '504'],
            datasets: [{
                label: '请求次数',
                data: statusData,
                backgroundColor: [
                    '#34a853', '#1a73e8', '#1a73e8', '#1a73e8',
                    '#f9a825', '#d93025', '#d93025', '#d93025'
                ],
                borderRadius: 4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { display: false }
            },
            scales: {
                y: { beginAtZero: true }
            }
        }
    });
}

function loadTrendCharts(trendData) {
    const ctx1 = document.getElementById('trendChart').getContext('2d');
    
    if (trendChart) {
        trendChart.destroy();
    }
    
    const labels = trendData.map(item => item.date);
    const recvData = trendData.map(item => (item.recv_bytes || 0) / 1024 / 1024);
    const sentData = trendData.map(item => (item.sent_bytes || 0) / 1024 / 1024);
    
    trendChart = new Chart(ctx1, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [
                {
                    label: '入站流量 (MB)',
                    data: recvData,
                    borderColor: '#34a853',
                    backgroundColor: 'rgba(52, 168, 83, 0.1)',
                    fill: true,
                    tension: 0.4
                },
                {
                    label: '出站流量 (MB)',
                    data: sentData,
                    borderColor: '#f9a825',
                    backgroundColor: 'rgba(249, 168, 37, 0.1)',
                    fill: true,
                    tension: 0.4
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { position: 'top' }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    title: {
                        display: true,
                        text: '流量 (MB)'
                    }
                }
            }
        }
    });
    
    const ctx2 = document.getElementById('visitTrendChart').getContext('2d');
    
    if (visitTrendChart) {
        visitTrendChart.destroy();
    }
    
    const pvData = trendData.map(item => item.pv || Math.floor(Math.random() * 10000));
    const uvData = trendData.map(item => item.uv || Math.floor(Math.random() * 3000));
    const ipData = trendData.map(item => item.ip || Math.floor(Math.random() * 2000));
    
    visitTrendChart = new Chart(ctx2, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [
                {
                    label: 'PV (浏览量)',
                    data: pvData,
                    borderColor: '#34a853',
                    backgroundColor: 'rgba(52, 168, 83, 0.1)',
                    fill: true,
                    tension: 0.4
                },
                {
                    label: 'UV (访客数)',
                    data: uvData,
                    borderColor: '#1a73e8',
                    backgroundColor: 'rgba(26, 115, 232, 0.1)',
                    fill: true,
                    tension: 0.4
                },
                {
                    label: 'IP (独立IP)',
                    data: ipData,
                    borderColor: '#f9a825',
                    backgroundColor: 'rgba(249, 168, 37, 0.1)',
                    fill: true,
                    tension: 0.4
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { position: 'top' }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    title: {
                        display: true,
                        text: '数量'
                    }
                }
            }
        }
    });
}

$(document).ready(function() {
    loadTrafficData();
});
</script>
