<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('服务监控')" />
    <script th:src="@{/js/echarts.min.js}"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
        }
        
        .header {
            text-align: center;
            color: white;
            margin-bottom: 30px;
        }
        
        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }
        
        .header p {
            opacity: 0.9;
            font-size: 1.1em;
        }
        
        .chart-card {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            backdrop-filter: blur(10px);
        }
        
        .chart-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
            gap: 15px;
        }
        
        .chart-title {
            font-size: 1.5em;
            color: #333;
            font-weight: 600;
        }
        
        .controls {
            display: flex;
            gap: 10px;
            align-items: center;
        }
        
        .btn {
            padding: 8px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s ease;
            font-weight: 500;
        }
        
        .btn-primary {
            background: #2a5298;
            color: white;
        }
        
        .btn-primary:hover {
            background: #1e3c72;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(42, 82, 152, 0.4);
        }
        
        .btn-secondary {
            background: #f0f0f0;
            color: #333;
        }
        
        .btn-secondary:hover {
            background: #e0e0e0;
        }
        
        .status {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 6px 16px;
            border-radius: 20px;
            font-size: 13px;
            font-weight: 500;
        }
        
        .status.online {
            background: #d4edda;
            color: #155724;
        }
        
        .status.offline {
            background: #f8d7da;
            color: #721c24;
        }
        
        .status-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            animation: pulse 2s infinite;
        }
        
        .status.online .status-dot {
            background: #28a745;
        }
        
        .status.offline .status-dot {
            background: #dc3545;
            animation: none;
        }
        
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }
        
        #chart {
            width: 100%;
            height: 500px;
            border-radius: 12px;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-top: 25px;
        }
        
        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 15px;
            text-align: center;
            transition: transform 0.3s ease;
        }
        
        .stat-card:hover {
            transform: translateY(-5px);
        }
        
        .stat-label {
            font-size: 0.9em;
            opacity: 0.9;
            margin-bottom: 8px;
            text-transform: uppercase;
            letter-spacing: 1px;
        }
        
        .stat-value {
            font-size: 2em;
            font-weight: bold;
            font-family: 'Courier New', monospace;
        }
        
        .stat-unit {
            font-size: 0.8em;
            opacity: 0.8;
        }
        
        .time-range {
            color: #666;
            font-size: 0.9em;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="chart-card">
            <div class="chart-header">
                <div>
                    <div class="chart-title">
                        <select id="chartSelect" onchange="changeChart(this.value)" style="
                                font-size: small;
                                font-weight: 600;
                                color: #333;
                                border: 2px solid #e0e0e0;
                                border-radius: 8px;
                                padding: 8px 15px;
                                background: white;
                                cursor: pointer;
                                outline: none;
                                min-width: 250px;
                                font-family: inherit;
                            ">
                            <option value="system.cpu">系统整体 CPU</option>
                            <option value="system.ram">系统整体内存</option>
                            <option value="system.io">系统磁盘 I/O</option>
                            <option value="net.enp4s0">网卡流量</option>
                            <option value="app.easycallcenter365_cpu_utilization">easycallcenter365 CPU</option>
                            <option value="app.easycallcenter365_mem_usage">easycallcenter365 内存</option>
                            <option value="app.easycallcenter365-gui_cpu_utilization">easycallcenter365-gui CPU</option>
                            <option value="app.easycallcenter365-gui_mem_usage">easycallcenter365-gui 内存</option>
                            <option value="app.freeswitch_cpu_utilization">FreeSWITCH CPU</option>
                            <option value="app.freeswitch_mem_usage">FreeSWITCH 内存</option>
                            <option value="app.mysql_cpu_utilization">MySQL CPU</option>
                            <option value="app.mysql_mem_usage">MySQL 内存</option>
                        </select>
                    </div>
                    <div class="time-range" id="timeRange">加载中...</div>
                </div>
                <div class="controls">
        <span class="status offline" id="status">
            <span class="status-dot"></span>
            <span id="statusText">离线</span>
        </span>
                    <button class="btn btn-secondary" onclick="changeTimeRange(300)">5分钟</button>
                    <button class="btn btn-secondary" onclick="changeTimeRange(900)">15分钟</button>
                    <button class="btn btn-secondary" onclick="changeTimeRange(3600)">1小时</button>
                    <button class="btn btn-secondary" onclick="changeTimeRange(86400)">24小时</button>
                    <button class="btn btn-secondary" onclick="changeTimeRange(259200)">3天</button>
                    <button class="btn btn-primary" onclick="refreshData()">🔄 刷新</button>
                </div>
            </div>
            
            <div id="chart"></div>
            
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-label">当前值</div>
                    <div class="stat-value" id="currentValue">--</div>
                </div>
                <div class="stat-card">
                    <div class="stat-label">平均值</div>
                    <div class="stat-value" id="avgValue">--</div>
                </div>
                <div class="stat-card">
                    <div class="stat-label">最大值</div>
                    <div class="stat-value" id="maxValue">--</div>
                </div>
                <div class="stat-card">
                    <div class="stat-label">最小值</div>
                    <div class="stat-value" id="minValue">--</div>
                </div>
            </div>
        </div>
    </div>
    <th:block th:include="include :: footer" />

    <script th:inline="javascript">
        let myChart = null;
        let currentTimeRange = 600;
        let refreshInterval = null;
        const API_BASE = [[${netdataApiBase}]];
        let CHART_NAME = 'system.cpu'; // 默认值改为 system.cpu

        // 新增：切换图表函数
        function changeChart(chartName) {
            CHART_NAME = chartName;
            // 更新图表标题（可选，用于 yAxis name）
            updateChartTitle(chartName);
            // 重新获取数据并刷新
            updateChart();
        }

        // 新增：根据图表名称更新 Y 轴标题
        function updateChartTitle(chartName) {
            let title = '';
            if (chartName.includes('cpu')) {
                title = 'CPU 使用率 (%)';
            } else if (chartName.includes('ram') || chartName.includes('mem')) {
                title = '内存使用 (MiB)';
            } else if (chartName.includes('io')) {
                title = '磁盘 I/O (KiB/s)';
            } else if (chartName.startsWith('net.')) {
                title = '网络流量 (kilobits/s)';
            }

            if (myChart) {
                myChart.setOption({
                    yAxis: {
                        name: title
                    }
                });
            }
        }

        function initChart() {
            const chartDom = document.getElementById('chart');
            myChart = echarts.init(chartDom);

            // 初始化时设置默认选中的图表
            document.getElementById('chartSelect').value = CHART_NAME;

            const option = {
                backgroundColor: 'transparent',
                tooltip: {
                    trigger: 'axis',
                    backgroundColor: 'rgba(255, 255, 255, 0.95)',
                    borderColor: '#ddd',
                    borderWidth: 1,
                    textStyle: {
                        color: '#333'
                    },
                    formatter: function(params) {
                        const time = new Date(params[0].name * 1000);
                        const value = params[0].value;
                        return `
                        <div style="font-weight:600;margin-bottom:5px">${time.toLocaleString()}</div>
                        <div style="color:#2a5298;font-weight:600">
                            <span style="display:inline-block;width:10px;height:10px;background:#2a5298;border-radius:50%;margin-right:5px"></span>
                            ${value !== null && value !== undefined ? value.toFixed(2) : '--'}
                        </div>
                    `;
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '10%',
                    top: '15%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: [],
                    axisLine: {
                        lineStyle: {
                            color: '#999'
                        }
                    },
                    axisLabel: {
                        color: '#666',
                        formatter: function(value) {
                            const date = new Date(value * 1000);
                            return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
                        }
                    },
                    splitLine: {
                        show: true,
                        lineStyle: {
                            color: '#f0f0f0'
                        }
                    }
                },
                yAxis: {
                    type: 'value',
                    name: 'CPU 使用率 (%)',
                    nameTextStyle: {
                        color: '#666',
                        padding: [0, 0, 0, 50]
                    },
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        color: '#666',
                        formatter: '{value}'
                    },
                    splitLine: {
                        lineStyle: {
                            color: '#f0f0f0',
                            type: 'dashed'
                        }
                    }
                },
                series: [{
                    name: 'Value',
                    type: 'line',
                    smooth: false,
                    symbol: 'none',
                    itemStyle: {
                        color: '#2a5298'
                    },
                    lineStyle: {
                        width: 2
                    },
                    data: []
                }]
            };

            myChart.setOption(option);

            window.addEventListener('resize', function() {
                myChart.resize();
            });

            // 初始化时更新标题
            updateChartTitle(CHART_NAME);
        }

        async function fetchData() {
            const after = Math.floor(Date.now() / 1000) - currentTimeRange;
            const before = Math.floor(Date.now() / 1000);
            const points = Math.min(currentTimeRange, 600);
            var gtime = 60;
            if (currentTimeRange <= 3600) {
                gtime = 1;
            } else {
                gtime = 60;
            }

            const url = `${API_BASE}?chart=${CHART_NAME}&format=json&after=${after}&before=${before}&points=${points}&gtime=${gtime}`;

            try {
                const response = await fetch(url);
                if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);

                const data = await response.json();
                return data;
            } catch (error) {
                console.error('Fetch error:', error);
                throw error;
            }
        }

        async function updateChart() {
            const statusEl = document.getElementById('status');
            const statusText = document.getElementById('statusText');

            try {
                const data = await fetchData();

                if (!data.data || data.data.length === 0) {
                    throw new Error('无数据返回');
                }

                const times = data.data.map(item => item[0]).reverse();
                const values = data.data.map(item => item[1]).reverse();

                const current = values[values.length - 1];
                const avg = values.reduce((a, b) => a + b, 0) / values.length;
                const max = Math.max(...values);
                const min = Math.min(...values);

                const firstTime = new Date(times[0] * 1000);
                const lastTime = new Date(times[times.length - 1] * 1000);
                document.getElementById('timeRange').textContent =
                    `${firstTime.toLocaleString()} - ${lastTime.toLocaleString()}`;

                document.getElementById('currentValue').textContent = current !== null ? current.toFixed(2) : '--';
                document.getElementById('avgValue').textContent = avg !== null ? avg.toFixed(2) : '--';
                document.getElementById('maxValue').textContent = max !== null ? max.toFixed(2) : '--';
                document.getElementById('minValue').textContent = min !== null ? min.toFixed(2) : '--';

                myChart.setOption({
                    xAxis: {
                        data: times
                    },
                    series: [{
                        data: values
                    }]
                });

                statusEl.className = 'status online';
                statusText.textContent = '在线';

            } catch (error) {
                console.error('Update error:', error);
                statusEl.className = 'status offline';
                statusText.textContent = '连接失败';
                document.getElementById('timeRange').textContent = `错误: ${error.message}`;
            }
        }

        function refreshData() {
            const btn = document.querySelector('.btn-primary');
            btn.style.transform = 'rotate(360deg)';
            setTimeout(() => btn.style.transform = '', 500);
            updateChart();
        }

        function changeTimeRange(seconds) {
            currentTimeRange = seconds;
            document.querySelectorAll('.btn-secondary').forEach(btn => {
                btn.style.background = '#f0f0f0';
                btn.style.color = '#333';
            });
            event.target.style.background = '#2a5298';
            event.target.style.color = 'white';
            updateChart();
        }

        function startAutoRefresh() {
            refreshInterval = setInterval(updateChart, 5000);
        }

        function stopAutoRefresh() {
            if (refreshInterval) {
                clearInterval(refreshInterval);
            }
        }

        document.addEventListener('DOMContentLoaded', function() {
            initChart();
            updateChart();
            startAutoRefresh();
        });

        document.addEventListener('visibilitychange', function() {
            if (document.hidden) {
                stopAutoRefresh();
            } else {
                updateChart();
                startAutoRefresh();
            }
        });
    </script>
</body>
</html>