// 加载企业/用户/场站列表（checkbox 列表）
async function loadEntities(page = 1, search = '') {
    const splitType = document.getElementById('split-type').value;
    const container = document.getElementById('entity-list');
    
    if (!splitType) {
        container.innerHTML = '<div class="empty">请先选择拆分方式</div>';
        return;
    }

    // 显示/隐藏合并特来电选项（仅按企业拆分时显示）
    const mergeTelecomSection = document.getElementById('telecom-vehicle-section');
    const mergeTelecomCheckbox = document.getElementById('merge-telecom');
    if (mergeTelecomSection && mergeTelecomCheckbox) {
        if (splitType === 'company_id') {
            mergeTelecomCheckbox.parentElement.style.display = 'block';
        } else {
            mergeTelecomCheckbox.parentElement.style.display = 'none';
            mergeTelecomCheckbox.checked = false;
            toggleTelecomVehicleNo();
        }
    }

    // 保存当前状态
    currentEntityType = splitType === 'company_id' ? 'company' : 
                       splitType === 'user_id' ? 'user' : 
                       splitType === 'station_id' ? 'station' : '';
    entityPage = page;
    currentSearch = search;

    container.innerHTML = '<div class="loading">加载中...</div>';

    try {
        const response = await fetch(`/api/entities?type=${currentEntityType}&page=${page}&page_size=${entityPageSize}&search=${encodeURIComponent(search)}`);
        const result = await response.json();
        
        if (result.success) {
            const entities = result.data;
            const total = result.total || 0;
            const totalPages = Math.ceil(total / entityPageSize);
            
            if (entities.length === 0) {
                container.innerHTML = '<div class="empty">无数据</div>';
            } else {
                const selected = [];
                const unselected = [];
                entities.forEach(e => {
                    let value = '';
                    let name = '';
                    let typeLabel = '';
                    
                    if (splitType === 'company_id') {
                        value = e.company_id;
                        name = e.company_name;
                    } else if (splitType === 'user_id') {
                        value = e.user_id;
                        name = e.user_name;
                        typeLabel = e.order_type === 3 ? '(企业用户)' : '(普通用户)';
                        if (e.phone) {
                            name = `${e.user_name} (${e.phone})`;
                        }
                    } else if (splitType === 'station_id') {
                        value = e.station_id;
                        name = e.station_name;
                    }
                    
                    const item = { value, name, typeLabel };
                    if (selectedEntityIds.has(String(value))) {
                        selected.push(item);
                    } else {
                        unselected.push(item);
                    }
                });
                
                const sortedEntities = [...selected, ...unselected];
                
                container.innerHTML = sortedEntities.map(e => {
                    const isChecked = selectedEntityIds.has(String(e.value)) ? 'checked' : '';
                    const isSelectedTop = selectedEntityIds.has(String(e.value));
                    return `
                        <div class="checkbox-item ${isChecked} ${isSelectedTop ? 'entity-selected-top' : ''}" onclick="toggleEntityCheckbox(this, '${e.value}')">
                            <input type="checkbox" value="${e.value}" ${isChecked} onclick="event.stopPropagation()">
                            <span>${e.name} ${e.typeLabel}</span>
                        </div>
                    `;
                }).join('');
            }
            
            // 更新分页UI
            updateEntityPagination(totalPages, total);
            updateSelectedCount();
        }
    } catch (error) {
        console.error('加载列表失败:', error);
        container.innerHTML = '<div class="empty">加载失败</div>';
    }
}

// 切换实体 checkbox
function toggleEntityCheckbox(item, value) {
    const checkbox = item.querySelector('input[type="checkbox"]');
    checkbox.checked = !checkbox.checked;
    
    if (checkbox.checked) {
        item.classList.add('checked');
        item.classList.add('entity-selected-top');
        selectedEntityIds.add(String(value));
    } else {
        item.classList.remove('checked');
        item.classList.remove('entity-selected-top');
        selectedEntityIds.delete(String(value));
    }
    
    updateSelectedCount();
}

// 重新排序列表（已选的在前面）
function reorderEntityList() {
    const container = document.getElementById('entity-list');
    const items = Array.from(container.querySelectorAll('.checkbox-item'));
    if (items.length === 0) return;
    
    const selected = [];
    const unselected = [];
    
    items.forEach(item => {
        const checkbox = item.querySelector('input[type="checkbox"]');
        if (checkbox.checked) {
            selected.push(item);
            item.classList.add('entity-selected-top');
        } else {
            unselected.push(item);
            item.classList.remove('entity-selected-top');
        }
    });
    
    // 用文档片段移动，避免 innerHTML 清空导致状态丢失
    const fragment = document.createDocumentFragment();
    [...selected, ...unselected].forEach(item => {
        fragment.appendChild(item);
    });
    container.appendChild(fragment);
}

// 更新已选数量显示
function updateSelectedCount() {
    const countSpan = document.getElementById('selected-count');
    if (countSpan) {
        countSpan.textContent = `已选：${selectedEntityIds.size} 个`;
    }
}

// 全选/取消全选实体
function toggleSelectAllEntities() {
    const container = document.getElementById('entity-list');
    const checkboxes = container.querySelectorAll('input[type="checkbox"]');
    const allChecked = Array.from(checkboxes).every(cb => cb.checked);
    
    checkboxes.forEach(cb => {
        cb.checked = !allChecked;
        const item = cb.closest('.checkbox-item');
        if (cb.checked) {
            item.classList.add('checked');
            selectedEntityIds.add(cb.value);
        } else {
            item.classList.remove('checked');
            selectedEntityIds.delete(cb.value);
        }
    });
    
    updateSelectedCount();
    reorderEntityList();
}

// 更新实体分页UI
function updateEntityPagination(totalPages, total) {
    const paginationDiv = document.getElementById('entity-pagination');
    if (!paginationDiv) return;
    
    if (totalPages <= 1) {
        paginationDiv.innerHTML = `<small style="color: var(--muted-foreground);">共 ${total} 条</small>`;
        return;
    }
    
    let html = `<small style="color: var(--muted-foreground);">共 ${total} 条</small>`;
    html += `<button type="button" class="btn btn-sm" onclick="loadEntities(${entityPage - 1}, currentSearch)" ${entityPage <= 1 ? 'disabled' : ''}>上一页</button>`;
    html += `<span>${entityPage}/${totalPages}</span>`;
    html += `<button type="button" class="btn btn-sm" onclick="loadEntities(${entityPage + 1}, currentSearch)" ${entityPage >= totalPages ? 'disabled' : ''}>下一页</button>`;
    
    paginationDiv.innerHTML = html;
}

// 搜索实体
function searchEntities() {
    const search = document.getElementById('entity-search').value.trim();
    loadEntities(1, search);
}

// 回车搜索
document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.getElementById('entity-search');
    if (searchInput) {
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                searchEntities();
            }
        });
    }
});

// 拆分方式变化时重新加载实体列表
function onSplitTypeChange() {
    selectedEntityIds.clear();
    loadEntities(1, '');
}

// 处理搜索框回车事件
function handleSearchEnter(event) {
    if (event.key === 'Enter') {
        const search = document.getElementById('entity-search').value;
        loadEntities(1, search);
    }
}
