{% extends "base.html" %}

{% block title %}频道配置 - 智队中枢{% endblock %}

{% block content %}
<div class="space-y-6">
    {# 页面标题 #}
    <div class="flex items-center justify-between">
        <h1 class="text-2xl font-bold dark:text-white">频道配置</h1>
        <button onclick="showModal('add-modal')" class="btn btn-primary flex items-center gap-2">
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
            </svg>
            新增配置
        </button>
    </div>
    
    {# 频道列表 #}
    <div class="card">
        <div class="card-body">
            <table class="table">
                <thead>
                    <tr>
                        <th>名称</th>
                        <th>Gateway URL</th>
                        <th>状态</th>
                        <th>最后连接</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {% for config in configs %}
                    <tr>
                        <td class="font-medium">{{ config.name }}</td>
                        <td class="font-mono text-sm">{{ config.gateway_url }}</td>
                        <td>
                            {% if config.status == 'online' %}
                            <span class="badge badge-success">在线</span>
                            {% else %}
                            <span class="badge badge-danger">离线</span>
                            {% endif %}
                        </td>
                        <td class="text-gray-500 dark:text-gray-400 text-sm">
                            {{ config.last_connected.strftime('%Y-%m-%d %H:%M') if config.last_connected else '从未连接' }}
                        </td>
                        <td>
                            <div class="flex items-center gap-2">
                                <button onclick="testChannel('{{ config.id }}')" 
                                        class="p-2 text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900/30 rounded-lg transition-colors"
                                        title="测试连接">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path>
                                    </svg>
                                </button>
                                <button onclick="editChannel('{{ config.id }}')" 
                                        class="p-2 text-gray-600 hover:bg-gray-100 dark:text-gray-400 dark:hover:bg-gray-700 rounded-lg transition-colors"
                                        title="编辑">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                                    </svg>
                                </button>
                                <button onclick="deleteChannel('{{ config.id }}')" 
                                        class="p-2 text-red-600 hover:bg-red-50 dark:hover:bg-red-900/30 rounded-lg transition-colors"
                                        title="删除">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                                    </svg>
                                </button>
                            </div>
                        </td>
                    </tr>
                    {% else %}
                    <tr>
                        <td colspan="5" class="text-center py-8 text-gray-500 dark:text-gray-400">
                            暂无配置，点击下方按钮新增
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>

{# 新增/编辑配置模态框 #}
<div id="channel-modal" class="fixed inset-0 bg-black/50 hidden items-center justify-center z-50">
    <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-lg mx-4">
        <div class="card-header flex items-center justify-between">
            <h3 class="text-lg font-semibold dark:text-white" id="modal-title">新增配置</h3>
            <button onclick="hideModal('channel-modal')" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                </svg>
            </button>
        </div>
        <form id="channel-form" class="card-body space-y-4">
            <input type="hidden" id="channel-id" name="id">
            <div>
                <label class="block text-sm font-medium mb-1 dark:text-gray-300">名称</label>
                <input type="text" id="channel-name" name="name" class="input" required placeholder="如：默认频道">
            </div>
            <div>
                <label class="block text-sm font-medium mb-1 dark:text-gray-300">Gateway URL</label>
                <input type="url" id="channel-url" name="gateway_url" class="input" required placeholder="ws://localhost:18888/ws">
            </div>
            <div>
                <label class="block text-sm font-medium mb-1 dark:text-gray-300">认证 Token</label>
                <input type="password" id="channel-token" name="auth_token" class="input" placeholder="可选，用于认证">
            </div>
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium mb-1 dark:text-gray-300">重连间隔 (ms)</label>
                    <input type="number" id="channel-reconnect" name="reconnect_interval" class="input" value="5000" min="1000" step="1000">
                </div>
                <div>
                    <label class="block text-sm font-medium mb-1 dark:text-gray-300">心跳间隔 (ms)</label>
                    <input type="number" id="channel-heartbeat" name="heartbeat_interval" class="input" value="30000" min="1000" step="1000">
                </div>
            </div>
            <div class="flex items-center gap-2">
                <input type="checkbox" id="channel-enabled" name="enabled" class="w-4 h-4 text-primary-600 rounded" checked>
                <label for="channel-enabled" class="dark:text-gray-300">启用此频道</label>
            </div>
            <div class="flex justify-end gap-3 pt-4 border-t border-gray-200 dark:border-gray-700">
                <button type="button" onclick="hideModal('channel-modal')" class="btn btn-secondary">取消</button>
                <button type="submit" class="btn btn-primary">保存</button>
            </div>
        </form>
    </div>
</div>

<script>
    // 测试频道连接
    function testChannel(id) {
        showToast('正在测试连接...', 'info');
        
        fetch(`/api/web/channels/${id}/test`, { method: 'POST' })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    showToast('连接测试通过！', 'success');
                } else {
                    showToast(`连接失败: ${data.error}`, 'error');
                }
            })
            .catch(err => {
                showToast(`测试出错: ${err.message}`, 'error');
            });
    }
    
    // 编辑频道 - 跳转到独立编辑页面
    function editChannel(id) {
        window.location.href = `/web/config/channels/${id}/edit`;
    }
    
    // 删除频道
    function deleteChannel(id) {
        if (!confirm('确定要删除此配置吗？')) return;
        
        fetch(`/api/web/channels/${id}`, { method: 'DELETE' })
            .then(res => {
                if (res.ok) {
                    showToast('删除成功', 'success');
                    location.reload();
                } else {
                    showToast('删除失败', 'error');
                }
            });
    }
    
    // 表单提交
    document.getElementById('channel-form').addEventListener('submit', function(e) {
        e.preventDefault();
        const id = document.getElementById('channel-id').value;
        const method = id ? 'PUT' : 'POST';
        const url = id ? `/api/web/channels/${id}` : '/api/web/channels';
        
        const formData = new FormData(this);
        const data = Object.fromEntries(formData);
        data.enabled = !!data.enabled;
        data.reconnect_interval = parseInt(data.reconnect_interval);
        data.heartbeat_interval = parseInt(data.heartbeat_interval);
        
        fetch(url, {
            method: method,
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data)
        })
        .then(res => {
            if (res.ok) {
                showToast(id ? '更新成功' : '创建成功', 'success');
                hideModal('channel-modal');
                location.reload();
            } else {
                showToast('保存失败', 'error');
            }
        });
    });
    
    // 显示/隐藏模态框
    function showModal(id) {
        document.getElementById(id).classList.remove('hidden');
        document.getElementById(id).classList.add('flex');
    }
    
    function hideModal(id) {
        document.getElementById(id).classList.add('hidden');
        document.getElementById(id).classList.remove('flex');
    }
</script>
{% endblock %}
