{% extends "base.html" %}

{% block title %}编辑频道 - 智队中枢{% endblock %}

{% block content %}
<div class="space-y-6">
    {# 页面头部 #}
    <div class="flex items-center justify-between">
        <div class="flex items-center gap-4">
            <a href="{{ url_for('web.channels') }}" class="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors">
                <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="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
                </svg>
            </a>
            <div>
                <h1 class="text-2xl font-bold dark:text-white">编辑频道配置</h1>
                <p class="text-sm text-gray-500 dark:text-gray-400">{{ config.name }}</p>
            </div>
        </div>
    </div>

    {# 表单 #}
    <form id="channel-form" class="space-y-6">
        <input type="hidden" id="channel-id" value="{{ config.id }}">
        
        {# 基本信息 #}
        <div class="card">
            <div class="card-header">
                <h2 class="text-lg font-semibold dark:text-white">基本信息</h2>
            </div>
            <div class="card-body space-y-4">
                <div>
                    <label class="block text-sm font-medium mb-1 dark:text-gray-300">
                        名称 <span class="text-red-500">*</span>
                    </label>
                    <input type="text" id="channel-name" name="name" class="input" required 
                           value="{{ config.name }}" placeholder="如：默认频道">
                    <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">频道配置的唯一名称</p>
                </div>
                
                <div>
                    <label class="block text-sm font-medium mb-1 dark:text-gray-300">
                        Gateway URL <span class="text-red-500">*</span>
                    </label>
                    <input type="url" id="channel-url" name="gateway_url" class="input" required
                           value="{{ config.gateway_url }}" placeholder="ws://localhost:18888/ws">
                    <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">WebSocket 连接地址</p>
                </div>
                
                <div>
                    <label class="block text-sm font-medium mb-1 dark:text-gray-300">认证 Token</label>
                    <div class="relative">
                        <input type="password" id="channel-token" name="auth_token" class="input pr-10"
                               value="{{ config.auth_token or '' }}" placeholder="可选，用于认证">
                        <button type="button" onclick="toggleTokenVisibility()" 
                                class="absolute right-2 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600">
                            <svg id="eye-icon" 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="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                            </svg>
                        </button>
                    </div>
                    <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">用于连接认证的 Token</p>
                </div>
            </div>
        </div>

        {# 连接配置 #}
        <div class="card">
            <div class="card-header">
                <h2 class="text-lg font-semibold dark:text-white">连接配置</h2>
            </div>
            <div class="card-body space-y-4">
                <div class="grid grid-cols-1 md: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="{{ config.reconnect_interval or 5000 }}" min="1000" step="1000">
                        <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">连接断开后的重连间隔</p>
                    </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="{{ config.heartbeat_interval or 30000 }}" min="1000" step="1000">
                        <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">心跳包发送间隔</p>
                    </div>
                </div>
                
                <div class="flex items-center gap-3 p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
                    <input type="checkbox" id="channel-enabled" name="enabled" 
                           class="w-5 h-5 text-primary-600 rounded focus:ring-primary-500"
                           {{ 'checked' if config.enabled else '' }}>
                    <div>
                        <label for="channel-enabled" class="font-medium dark:text-gray-200 cursor-pointer">启用此频道</label>
                        <p class="text-xs text-gray-500 dark:text-gray-400">启用后将自动连接到 Gateway</p>
                    </div>
                </div>
            </div>
        </div>

        {# 状态信息 #}
        <div class="card">
            <div class="card-header">
                <h2 class="text-lg font-semibold dark:text-white">状态信息</h2>
            </div>
            <div class="card-body">
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div class="p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
                        <div class="text-xs text-gray-500 dark:text-gray-400 mb-1">连接状态</div>
                        <div class="flex items-center gap-2">
                            {% if config.status == 'online' %}
                            <span class="w-2 h-2 bg-green-500 rounded-full animate-pulse"></span>
                            <span class="font-medium text-green-600 dark:text-green-400">在线</span>
                            {% else %}
                            <span class="w-2 h-2 bg-red-500 rounded-full"></span>
                            <span class="font-medium text-red-600 dark:text-red-400">离线</span>
                            {% endif %}
                        </div>
                    </div>
                    <div class="p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
                        <div class="text-xs text-gray-500 dark:text-gray-400 mb-1">最后连接</div>
                        <div class="font-medium dark:text-white">
                            {{ config.last_connected.strftime('%Y-%m-%d %H:%M') if config.last_connected else '从未连接' }}
                        </div>
                    </div>
                    <div class="p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
                        <div class="text-xs text-gray-500 dark:text-gray-400 mb-1">更新时间</div>
                        <div class="font-medium dark:text-white">
                            {{ config.updated_at.strftime('%Y-%m-%d %H:%M') if config.updated_at else '-' }}
                        </div>
                    </div>
                </div>
                
                {% if config.last_error %}
                <div class="mt-4 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
                    <div class="flex items-start gap-2">
                        <svg class="w-5 h-5 text-red-500 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                        </svg>
                        <div>
                            <div class="font-medium text-red-700 dark:text-red-400">最后错误</div>
                            <div class="text-sm text-red-600 dark:text-red-300 mt-1">{{ config.last_error }}</div>
                        </div>
                    </div>
                </div>
                {% endif %}
            </div>
        </div>

        {# 操作按钮 #}
        <div class="flex items-center justify-between">
            <button type="button" onclick="testConnection()" class="btn btn-secondary 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="M13 10V3L4 14h7v7l9-11h-7z"></path>
                </svg>
                测试连接
            </button>
            <div class="flex items-center gap-3">
                <a href="{{ url_for('web.channels') }}" class="btn btn-secondary">取消</a>
                <button type="submit" 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="M5 13l4 4L19 7"></path>
                    </svg>
                    保存更改
                </button>
            </div>
        </div>
    </form>
</div>

<script>
    function toggleTokenVisibility() {
        const input = document.getElementById('channel-token');
        const icon = document.getElementById('eye-icon');
        
        if (input.type === 'password') {
            input.type = 'text';
            icon.innerHTML = '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"></path>';
        } else {
            input.type = 'password';
            icon.innerHTML = '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>';
        }
    }
    
    function testConnection() {
        showToast('正在测试连接...', 'info');
        
        fetch(`/api/web/channels/{{ config.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');
            });
    }
    
    document.getElementById('channel-form').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const data = {
            name: document.getElementById('channel-name').value,
            gateway_url: document.getElementById('channel-url').value,
            auth_token: document.getElementById('channel-token').value,
            reconnect_interval: parseInt(document.getElementById('channel-reconnect').value),
            heartbeat_interval: parseInt(document.getElementById('channel-heartbeat').value),
            enabled: document.getElementById('channel-enabled').checked
        };
        
        fetch(`/api/web/channels/{{ config.id }}`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data)
        })
        .then(res => {
            if (res.ok) {
                showToast('保存成功', 'success');
                setTimeout(() => location.href = '{{ url_for("web.channels") }}', 1000);
            } else {
                return res.json().then(d => { throw new Error(d.error || '保存失败'); });
            }
        })
        .catch(err => {
            showToast(err.message, 'error');
        });
    });
</script>
{% endblock %}
