function handleSelectAll() {
    const checkboxes = document.querySelectorAll('input[name="device_ids"]');
    const selectAllButton = document.getElementById('selectAllBtn');
    const hasSelected = Array.from(checkboxes).some(checkbox => checkbox.checked);
    const newState = !hasSelected;
    
    checkboxes.forEach(checkbox => {
        checkbox.checked = newState;
    });

    selectAllButton.textContent = newState ? '清空' : '全选';
}

function handleInvertSelect() {
    const checkboxes = document.querySelectorAll('input[name="device_ids"]');
    checkboxes.forEach(checkbox => {
        checkbox.checked = !checkbox.checked;
    });
    updateSelectAllButtonText();
}

function updateSelectAllButtonText() {
    const checkboxes = document.querySelectorAll('input[name="device_ids"]');
    const selectAllButton = document.getElementById('selectAllBtn');
    const hasSelected = Array.from(checkboxes).some(checkbox => checkbox.checked);
    selectAllButton.textContent = hasSelected ? '清空' : '全选';
}

function changePerPage(value) {
    const currentUrl = new URL(window.location.href);
    currentUrl.searchParams.set('per_page', value);
    currentUrl.searchParams.set('page', '1');
    window.location.href = currentUrl.toString();
}

async function handleSync(type) {
    if (type === 'camera') {
        try {
            const response = await fetch('/get_captcha', {
                method: 'GET'
            });
            
            if (response.ok) {
                const blob = await response.blob();
                document.getElementById('captchaImage').src = URL.createObjectURL(blob);
                document.getElementById('captchaModal').style.display = 'block';
            } else {
                alert('获取验证码失败，请重试');
            }
        } catch (error) {
            console.error('获取验证码失败:', error);
            alert('获取验证码失败，请重试');
        }
    } else if (type === 'alarm') {
        // 显示确认模态框
        document.getElementById('alarmConfirmModal').style.display = 'block';
    }
}

// 添加关闭确认模态框的函数
function closeAlarmConfirmModal() {
    document.getElementById('alarmConfirmModal').style.display = 'none';
}

// 添加确认同步的函数
async function confirmAlarmSync() {
    try {
        // 关闭确认模态框
        closeAlarmConfirmModal();
        
        // 显示加载提示
        document.getElementById('resultMessage').textContent = '正在同步数据，请稍候...';
        document.getElementById('resultModal').style.display = 'block';

        const response = await fetch('/sync_offline_devices', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        });

        const data = await response.json();
        
        if (data.success) {
            document.getElementById('resultMessage').textContent = 
                `同步成功！已为 ${data.count} 个离线设备创建工单。`;
        } else {
            document.getElementById('resultMessage').textContent = '同步失败：' + data.message;
        }
        document.getElementById('resultModal').style.display = 'block';
    } catch (error) {
        console.error('同步失败:', error);
        document.getElementById('resultMessage').textContent = '同步失败，请重试';
        document.getElementById('resultModal').style.display = 'block';
    }
}

async function submitCaptcha() {
    const captcha = document.getElementById('captchaInput').value;
    if (!captcha) {
        alert('请输入验证码');
        return;
    }

    try {
        const response = await fetch('/sync_camera_step1', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ captcha: captcha })
        });
        
        const data = await response.json();
        
        if (data.success) {
            document.getElementById('captchaModal').style.display = 'none';
            // 更新模态框中的数量
            document.getElementById('updatedCount').textContent = data.updated_count || 0;
            document.getElementById('confirmModal').style.display = 'block';
        } else {
            if (data.message === 'INVALID_CAPTCHA') {
                alert('验证码错误，请重新输入');
                handleSync('camera');
            } else {
                alert('同步失败：' + data.message);
            }
        }
    } catch (error) {
        console.error('同步失败:', error);
        alert('同步失败，请重试');
    }
}

async function handleDispatch(isCamera = false) {
    try {
        // 不立即关闭确认模态框，而是先更新其内容
        const confirmModal = document.getElementById('confirmModal');
        const modalContent = confirmModal.querySelector('.modal-content');
        modalContent.innerHTML = `
            <h3>正在处理</h3>
            <p>正在为选中设备创建工单，请稍候...</p>
            <div class="loading-spinner"></div>
        `;

        let response;
        if (isCamera) {
            // 如果是摄像头同步，调用第二步接口
            response = await fetch('/sync_camera_step2', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
        } else {
            // 普通派单
            response = await fetch('/dispatch', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
        }

        const result = await response.json();
        
        // 处理完成后，平滑过渡到结果模态框
        document.getElementById('confirmModal').style.display = 'none';
        document.getElementById('resultMessage').textContent = `派单成功！已为 ${result.count} 个设备创建工单。`;
        document.getElementById('resultModal').style.display = 'block';
    } catch (error) {
        console.error('派单失败:', error);
        document.getElementById('resultMessage').textContent = '派单失败，请重试';
        document.getElementById('resultModal').style.display = 'block';
    }
}
 
function cancelDispatch() {
    document.getElementById('confirmModal').style.display = 'none';
    window.location.reload();
}

function closeCaptchaModal() {
    document.getElementById('captchaModal').style.display = 'none';
    document.getElementById('captchaInput').value = '';
}

// 备注编辑功能
function editRemark(deviceId, spanElement) {
    const inputElement = spanElement.nextElementSibling;
    spanElement.style.display = 'none';
    inputElement.style.display = 'inline-block';
    inputElement.focus();
}

async function saveRemark(deviceId, inputElement) {
    const newRemark = inputElement.value.trim();
    const spanElement = inputElement.previousElementSibling;
    
    try {
        const response = await fetch('/update_device_remark', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ 
                device_id: deviceId, 
                remark: newRemark 
            })
        });
        
        const data = await response.json();
        
        if (data.success) {
            spanElement.textContent = newRemark || '点击添加备注';
            spanElement.style.display = 'inline-block';
            inputElement.style.display = 'none';
        } else {
            alert('保存失败：' + data.message);
            inputElement.focus();
        }
    } catch (error) {
        console.error('保存备注失败:', error);
        alert('保存失败，请重试');
        inputElement.focus();
    }
}
document.addEventListener('DOMContentLoaded', function() {
    // 监听复选框的变化
    document.addEventListener('change', function(e) {
        if (e.target.matches('input[name="device_ids"]')) {
            updateSelectAllButtonText();
        }
    });

    // 添加表单提交前的检查
    document.getElementById('dispatchForm').addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const selectedDevices = Array.from(document.querySelectorAll('input[name="device_ids"]:checked'))
            .map(checkbox => checkbox.value);
            
        if (selectedDevices.length === 0) {
            alert('请至少选择一个设备');
            return;
        }

        try {
            const response = await fetch('/check_existing_orders', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ device_ids: selectedDevices })
            });
            
            const data = await response.json();
            
            if (data.existing_devices.length > 0) {
                alert(`以下设备已有在途工单，请勿重复派单：\n${data.existing_devices.join('\n')}`);
                return;
            }
            
            this.submit();
            
        } catch (error) {
            console.error('检查失败:', error);
            alert('检查在途工单失败，请重试');
        }
    });
});