{% extends "base.html" %}

{% block content %}
<section class="platform-section">
    <h2>云平台连接设置</h2>
    <div class="platform-controls">
        <div class="platform-select">
            <label for="platform">云平台选择</label>
            <select id="platform">
                {% for key, platform in platform_c.items() %}
                <option value="{{ key }}" {% if current_platform == key %}selected{% endif %}>{{ platform.name }}</option>
                {% endfor %}
            </select>
        </div>

        <button id="connect-btn" class="disconnected">已断开</button>
    </div>

    <div class="platform-info" id="platform-info">
        <div>IP地址: <span id="platform-ip">加载中...</span></div>
        <div class="connection-status" id="connection-status"></div>
        <div>后台已运行: <span id="run-time">加载中...</span></div>
    </div>

    <div class="mqtt-publish">
        <h3>发布测试消息</h3>
        <div class="form-group">
            <label for="mqtt-message">消息内容</label>
            <input type="text" id="mqtt-message" placeholder="输入要发布的消息..." value='{"status": "online"}'>
        </div>
        <button id="publish-btn" class="publish-btn">发布消息</button>
    </div>
</section>

<section class="feature-nav">
    <div class="feature-card">
        <h3>固件包管理</h3>
        <p>固件管理：上传、下载、删除、编辑</p>
        <a href="{{ url_for('firmware') }}" class="feature-btn">进入</a>
    </div>

    <div class="feature-card">
        <h3>设备配置</h3>
        <p>管理设备，进行批量操作和参数配置</p>
        <a href="{{ url_for('devices') }}" class="feature-btn">进入</a>
    </div>

    <div class="feature-card">
        <h3>用户中心</h3>
        <p>查看用户信息，管理账户设置</p>
        <a href="{{ url_for('login') }}" class="feature-btn">进入</a>
    </div>
    <div class="feature-card">
        <h3>应用管理</h3>
        <p>重启应用，更新应用</p>
        <a href="{{ url_for('app_manage') }}" class="feature-btn">进入</a>
    </div>
</section>
{% endblock %}

{% block scripts %}
<script>
    
    // 初始化连接状态为已断开
    document.addEventListener('DOMContentLoaded', function() {
        // 更新状态显示
        const statusEl = document.getElementById('connection-status');
        statusEl.textContent = '状态: 已断开';
        statusEl.className = 'connection-status status-disconnected';

        // 更新按钮显示
        const connectBtn = document.getElementById('connect-btn');
        connectBtn.className = 'disconnected';
        connectBtn.textContent = '已断开';

        // 初始加载云平台状态
        loadPlatformStatus(currentPlatform);
    });

    // 更新运行时长
    function updateRunTime() {
        fetch("{{ url_for('get_run_time') }}")
            .then(response => response.json())
            .then(data => {
                document.getElementById('run-time').textContent = data.run_time;
            })
            .catch(error => console.error('获取运行时长失败:', error));
    }


    // 当前选中的云平台
    let currentPlatform = '{{ current_platform }}';
    // 云平台数据
    const platformData = {{ platform_c|tojson }};
    console.log('云平台数据:', platformData); // 调试信息
    // 确保platforms是对象且包含platform_c
    // const platformData = platform_c && platform_c.platform_c ? platform_c.platform_c : {};

    // 更新云平台信息显示
    function updatePlatformInfo(platformId) {
        const platform = platformData[platformId];
        if (!platform) return;
        console.log('云平台数据:', platform.name, platform.status); // 调试信息

        // 更新信息显示
        document.getElementById('platform-ip').textContent = platform.ip;
        // 删除了对platform-sub-topic的更新，因为该元素已不存在


        // 更新状态显示
        const statusEl = document.getElementById('connection-status');
        statusEl.textContent = `状态: ${platform.status === 'connected' ? '已连接' : '已断开'}`;
        statusEl.className = `connection-status ${platform.status === 'connected' ? 'status-connected' : 'status-disconnected'}`;

        // 更新按钮显示
        const connectBtn = document.getElementById('connect-btn');
        connectBtn.className = platform.status === 'connected' ? 'connected' : 'disconnected';
        connectBtn.textContent = platform.status === 'connected' ? '已连接' : '已断开';
    }

    // 加载云平台状态
    function loadPlatformStatus(platformId) {
        fetch(`{{ url_for('get_platform_status') }}?platform_id=${platformId}`)
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    platformData[platformId] = data.platform;
                    updatePlatformInfo(platformId);
                }
            })
            .catch(error => console.error('加载云平台状态失败:', error));
    }

    // 选择云平台
    document.getElementById('platform').addEventListener('change', function() {
        const selectedPlatform = this.value;
        currentPlatform = selectedPlatform;

        // 通知后端选择了新云平台
        fetch("{{ url_for('select_platform') }}", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ platform_id: selectedPlatform })
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                platformData[selectedPlatform] = data.platform;
                updatePlatformInfo(selectedPlatform);
            }
        });
    });

    // 连接/断开按钮
    document.getElementById('connect-btn').addEventListener('click', function() {
        const connectBtn = this;
        // 防止重复点击
        if (connectBtn.disabled) return;
        connectBtn.disabled = true;
        connectBtn.textContent = '处理中...';

        // 切换连接状态
        fetch("{{ url_for('toggle_connection') }}", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ platform_id: currentPlatform })
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                // 立即更新状态显示
                platformData[currentPlatform].status = data.new_status;
                updatePlatformInfo(currentPlatform);
            }
        })
        .catch(error => {
            console.error('切换连接状态失败:', error);
            // 恢复按钮状态
            loadPlatformStatus(currentPlatform);
        })
        .finally(() => {
            connectBtn.disabled = false;
        });
    });

    // 发布消息按钮
    document.getElementById('publish-btn').addEventListener('click', function() {
        const message = document.getElementById('mqtt-message').value;
        if (!message) {
            alert('请输入消息内容');
            return;
        }

        fetch("{{ url_for('publish_message') }}", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                platform_id: currentPlatform,
                message: message
            })
        })
        .then(response => response.json())
        .then(data => {
            alert(data.message);
        });
    });

    // 更新运行时长
    function updateRunTime() {
        fetch("{{ url_for('get_run_time') }}")
            .then(response => response.json())
            .then(data => {
                document.getElementById('run-time').textContent = data.run_time;
            })
            .catch(error => console.error('获取运行时长失败:', error));
    }

    // 统一更新函数
    function updateAll() {
        updateRunTime();
        loadPlatformStatus(currentPlatform);
    }

    // 初始加载
    document.addEventListener('DOMContentLoaded', function() {
        updatePlatformInfo(currentPlatform);
        updateRunTime(); // 初始化运行时长
        // 定期刷新所有数据
        setInterval(updateAll, 1000);
    });
</script>
{% endblock %}