{% extends "base.html" %}

{% block content %}
<section class="device-management">
    <h2>解密机配置</h2>
    {% if true %}
        <script>
            console.log('{{ success }}');
            console.log('{{ message }}');
        </script>
    {% endif %}

    <div class="batch-actions">
        <button id="batch-restart" class="batch-btn">批量重启</button>
        <button id="batch-upgrade" class="batch-btn">批量升级</button>
        <button id="batch-config" class="batch-btn">批量配置</button>
    </div>

    <form id="device-form" method="POST">
        <table class="data-table">
            <thead>
                <tr>
                    <th><input type="checkbox" id="select-all"></th>
                    <th>设备类型</th>
                    <th>设备SN</th>
                    <th>固件版本</th>
                    <th>升级状态</th>
                    <th>平台</th>
                    <th>在线状态</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                {% for device in devices %}
                <tr>
                    <td><input type="checkbox" name="dev_sn" value="{{ device.dev_sn }}"></td>
                    <td>{{ device.dev_type }}</td>
                    <td>{{ device.dev_sn }}</td>
                    <td>{{ device.app_version }}</td>
                    <td>{{ device.upgrade_status if device.upgrade_status is defined else '未知' }}</td>
                    <td>{{ device.cloud_platform }}</td>
                    <td style="color: {% if device.online == '在线' %}green{% else %}red{% endif %};">{{ device.online }}</td>
                    <td>
                        <a href="{{ url_for('devices', dev_sn=device.dev_sn) }}" class="config-btn">配置</a>
                        <a href="{{ url_for('device_detail', dev_sn=device.dev_sn) }}" class="detail-btn">详情</a>
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </form>
</section>
{% endblock %}

{% block scripts %}
<script>
    // 全选功能
    const selectAll = document.getElementById('select-all');
    const checkboxes = document.querySelectorAll('input[name="dev_sn"]');

    selectAll.addEventListener('change', () => {
        checkboxes.forEach(checkbox => {
            checkbox.checked = selectAll.checked;
        });
    });

    // 批量重启
    document.getElementById('batch-restart').addEventListener('click', () => {
        const selectedCount = document.querySelectorAll('input[name="dev_sn"]:checked').length;
        if (selectedCount === 0) {
            alert('请至少选择一个设备');
            return;
        }
        if (confirm('确定要批量重启选中设备吗?')) {
            const form = document.getElementById('device-form');
            form.action = "{{ url_for('devices') }}";
            form.method = "POST";

            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'action';
            input.value = 'restart';
            form.appendChild(input);

            form.submit();
        }
    });

    // 批量升级
    document.getElementById('batch-upgrade').addEventListener('click', () => {
        const selectedCount = document.querySelectorAll('input[name="dev_sn"]:checked').length;
        if (selectedCount === 0) {
            alert('请至少选择一个设备');
            return;
        }

        // 创建固件选择弹窗
        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.innerHTML = `
            <div class="modal-content">
                <span class="close-btn">&times;</span>
                <h3>选择固件包</h3>
                <form id="firmware-select-form">
                    <input type="hidden" name="action" value="upgrade">
                    <div class="firmware-table-container">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>选择</th>
                                    <th>文件名</th>
                                    <th>上传时间</th>
                                    <th>备注</th>
                                </tr>
                            </thead>
                            <tbody id="firmware-list">
                                <!-- 固件数据将通过JS加载 -->
                            </tbody>
                        </table>
                    </div>
                    <button type="submit" class="confirm-btn">确认升级</button>
                </form>
            </div>
        `;
        document.body.appendChild(modal);
        modal.style.display = 'block';

        // 加载固件列表
        fetch('{{ url_for('get_firmwares') }}')
            .then(response => response.json())
            .then(firmwares => {
                const firmwareList = document.getElementById('firmware-list');
                firmwares.forEach(firmware => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td><input type="radio" name="firmware_id" value="${firmware.id}" required></td>
                        <td>${firmware.filename}</td>
                        <td>${firmware.upload_time}</td>
                        <td>${firmware.remark}</td>
                    `;
                    firmwareList.appendChild(row);
                });
            });

        // 关闭弹窗
        modal.querySelector('.close-btn').addEventListener('click', () => {
            modal.style.display = 'none';
            document.body.removeChild(modal);
        });

        // 提交表单
        document.getElementById('firmware-select-form').addEventListener('submit', (e) => {
            e.preventDefault();

            // 获取选中的固件ID
            const selectedFirmware = document.querySelector('input[name="firmware_id"]:checked');
            if (!selectedFirmware) {
                alert('请选择一个固件包');
                return;
            }
            const firmwareId = selectedFirmware.value;

            // 创建表单数据
            const formData = new FormData(document.getElementById('device-form'));
            formData.append('action', 'upgrade');
            formData.append('firmware_id', firmwareId);

            // 发送数据到后端
            fetch('{{ url_for('devices') }}', {
                method: 'POST',
                body: formData
            }).then(response => {
                if (response.ok) {
                    window.location.reload();
                }
            });
        });
    });

    // 批量配置
    document.getElementById('batch-config').addEventListener('click', () => {
        const selectedCount = document.querySelectorAll('input[name="dev_sn"]:checked').length;
        if (selectedCount === 0) {
            alert('请至少选择一个设备');
            return;
        }
        if (confirm('确定要批量配置选中设备吗?')) {
            const form = document.getElementById('device-form');
            form.action = "{{ url_for('devices') }}";
            form.method = "POST";

            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'action';
            input.value = 'config';
            form.appendChild(input);

            form.submit();
        }
    });
    // 每隔1秒钟更新device-form部分内容
    /*
    setInterval(function() {
        // 使用fetch异步获取表单内容
        fetch(window.location.href, {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.text())
        .then(html => {
            // 创建临时DOM元素来解析获取的HTML
            const tempDoc = document.createElement('div');
            tempDoc.innerHTML = html;
            // 获取新的表单内容
            const newFormContent = tempDoc.querySelector('#device-form').innerHTML;
            // 更新当前页面的表单内容
            document.querySelector('#device-form').innerHTML = newFormContent;
        })
        .catch(error => {
            console.error('更新表单内容失败:', error);
        });
    }, 1000);
    */
</script>
{% endblock %}