// 会员查看页面 - H5版本

let memberData = [];
let filteredData = [];
let sortOrder = {};
let selectedMembers = new Set();

// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
    loadMemberData();
});

// 加载会员数据
function loadMemberData() {
    // 使用模拟数据
    memberData = [
        { id: 1, name: '张三', phone: '138****1234', level: 'LV2', points: 1250, joinDate: '2024-01-15' },
        { id: 2, name: '李四', phone: '139****5678', level: 'LV3', points: 2800, joinDate: '2024-02-20' },
        { id: 3, name: '王五', phone: '137****9012', level: 'LV1', points: 580, joinDate: '2024-03-10' },
        { id: 4, name: '赵六', phone: '136****3456', level: 'LV4', points: 5200, joinDate: '2024-01-08' },
        { id: 5, name: '钱七', phone: '135****7890', level: 'LV2', points: 1580, joinDate: '2024-02-15' },
        { id: 6, name: '孙八', phone: '134****2345', level: 'LV1', points: 420, joinDate: '2024-03-20' },
        { id: 7, name: '周九', phone: '133****6789', level: 'LV3', points: 3200, joinDate: '2024-01-25' },
        { id: 8, name: '吴十', phone: '132****0123', level: 'LV4', points: 4800, joinDate: '2024-02-10' }
    ];

    filteredData = [...memberData];
    renderTable();
}

// 渲染表格
function renderTable() {
    const tableBody = document.getElementById('member-table-body');
    tableBody.innerHTML = filteredData.map(member => `
        <tr>
            <td>
                <input type="checkbox" class="member-checkbox" value="${member.id}" 
                       onchange="toggleMemberSelection(${member.id})"
                       ${selectedMembers.has(member.id) ? 'checked' : ''}>
            </td>
            <td>${member.name}</td>
            <td>${member.phone}</td>
            <td>${member.level}</td>
            <td>${member.points}</td>
            <td>${member.joinDate}</td>
            <td>
                <button class="btn btn-small btn-primary" onclick="viewMemberDetail(${member.id})">
                    查看详情
                </button>
            </td>
        </tr>
    `).join('');
    updateSelectedCount();
}

// 筛选会员
function filterMembers() {
    const levelFilter = document.getElementById('level-filter').value;
    const searchText = document.getElementById('member-search').value.toLowerCase();

    filteredData = memberData.filter(member => {
        const matchLevel = !levelFilter || member.level === levelFilter;
        const matchSearch = !searchText || 
            member.name.toLowerCase().includes(searchText) ||
            member.phone.includes(searchText);
        
        return matchLevel && matchSearch;
    });

    renderTable();
    updateSelectAllState();
    showNotification(`筛选结果：${filteredData.length} 名会员`, 'info');
}

// 表格排序
function sortTable(column) {
    const isAscending = sortOrder[column] !== 'asc';
    sortOrder = {}; // 重置其他列的排序状态
    sortOrder[column] = isAscending ? 'asc' : 'desc';

    filteredData.sort((a, b) => {
        let valueA = a[column];
        let valueB = b[column];

        // 处理数字类型
        if (column === 'points') {
            valueA = parseInt(valueA);
            valueB = parseInt(valueB);
        }
        
        // 处理日期类型
        if (column === 'joinDate') {
            valueA = new Date(valueA);
            valueB = new Date(valueB);
        }

        if (valueA < valueB) {
            return isAscending ? -1 : 1;
        }
        if (valueA > valueB) {
            return isAscending ? 1 : -1;
        }
        return 0;
    });

    renderTable();
    updateSelectAllState();
    showNotification(`按${getColumnName(column)}${isAscending ? '升序' : '降序'}排列`, 'info');
}

// 获取列名中文
function getColumnName(column) {
    const names = {
        'name': '姓名',
        'phone': '手机号',
        'level': '等级',
        'points': '积分',
        'joinDate': '加入时间'
    };
    return names[column] || column;
}

// 查看会员详情
function viewMemberDetail(memberId) {
    const member = memberData.find(m => m.id === memberId);
    if (member) {
        // 这里可以跳转到会员详情页面，或者显示弹窗
        showNotification(`查看会员：${member.name} 的详情`, 'info');
        console.log('会员详情:', member);
    }
}

// 批量选择相关功能
function toggleSelectAll() {
    const selectAllCheckbox = document.getElementById('select-all');
    const memberCheckboxes = document.querySelectorAll('.member-checkbox');
    
    if (selectAllCheckbox.checked) {
        // 全选当前页面显示的会员
        filteredData.forEach(member => {
            selectedMembers.add(member.id);
        });
        memberCheckboxes.forEach(checkbox => {
            checkbox.checked = true;
        });
    } else {
        // 取消全选
        selectedMembers.clear();
        memberCheckboxes.forEach(checkbox => {
            checkbox.checked = false;
        });
    }
    
    updateSelectedCount();
}

// 切换单个会员选择状态
function toggleMemberSelection(memberId) {
    console.log('toggleMemberSelection called, memberId:', memberId);
    
    if (selectedMembers.has(memberId)) {
        selectedMembers.delete(memberId);
        console.log('Member removed from selection');
    } else {
        selectedMembers.add(memberId);
        console.log('Member added to selection');
    }
    
    console.log('Selected members:', Array.from(selectedMembers));
    
    updateSelectedCount();
    updateSelectAllState();
}

// 更新选中数量显示
function updateSelectedCount() {
    const selectedCount = selectedMembers.size;
    const countElement = document.getElementById('selected-count');
    const batchEditBtn = document.getElementById('batch-edit-btn');
    
    countElement.textContent = `已选择 ${selectedCount} 位会员`;
    batchEditBtn.disabled = selectedCount === 0;
}

// 更新全选checkbox状态
function updateSelectAllState() {
    const selectAllCheckbox = document.getElementById('select-all');
    const currentPageMemberIds = filteredData.map(member => member.id);
    const selectedCurrentPageCount = currentPageMemberIds.filter(id => selectedMembers.has(id)).length;
    
    if (selectedCurrentPageCount === 0) {
        selectAllCheckbox.checked = false;
        selectAllCheckbox.indeterminate = false;
    } else if (selectedCurrentPageCount === currentPageMemberIds.length) {
        selectAllCheckbox.checked = true;
        selectAllCheckbox.indeterminate = false;
    } else {
        selectAllCheckbox.checked = false;
        selectAllCheckbox.indeterminate = true;
    }
}

// 打开批量编辑弹窗
function openBatchEditModal() {
    console.log('openBatchEditModal called, selectedMembers size:', selectedMembers.size);
    
    if (selectedMembers.size === 0) {
        showNotification('请先选择要编辑的会员', 'warning');
        return;
    }
    
    // 显示选中的会员列表
    const selectedMembersList = document.getElementById('selected-members-list');
    const selectedMembersData = memberData.filter(member => selectedMembers.has(member.id));
    
    console.log('selectedMembersData:', selectedMembersData);
    
    selectedMembersList.innerHTML = selectedMembersData.map(member => 
        `<div style="margin-bottom: 5px;">${member.name} (${member.phone}) - 当前等级: ${member.level}</div>`
    ).join('');
    
    // 重置表单
    document.getElementById('new-level').value = '';
    document.getElementById('batch-edit-remark').value = '';
    
    // 显示弹窗
    const modal = document.getElementById('batch-edit-modal');
    console.log('Modal element:', modal);
    if (modal) {
        modal.style.display = 'flex';
        console.log('Modal display set to flex');
    } else {
        console.error('Modal element not found!');
    }
}

// 关闭批量编辑弹窗
function closeBatchEditModal() {
    document.getElementById('batch-edit-modal').style.display = 'none';
}

// 确认批量编辑
function confirmBatchEdit() {
    const newLevel = document.getElementById('new-level').value;
    const remark = document.getElementById('batch-edit-remark').value;
    
    if (!newLevel) {
        showNotification('请选择新的会员等级', 'warning');
        return;
    }
    
    // 执行批量编辑
    const selectedMembersData = memberData.filter(member => selectedMembers.has(member.id));
    let updatedCount = 0;
    
    selectedMembersData.forEach(member => {
        if (member.level !== newLevel) {
            member.level = newLevel;
            updatedCount++;
        }
    });
    
    // 重新渲染表格
    renderTable();
    
    // 关闭弹窗
    closeBatchEditModal();
    
    // 清除选择
    selectedMembers.clear();
    document.getElementById('select-all').checked = false;
    updateSelectedCount();
    
    // 显示成功消息
    const message = remark ? 
        `批量编辑完成：${updatedCount}位会员等级已更新为${newLevel}。备注：${remark}` :
        `批量编辑完成：${updatedCount}位会员等级已更新为${newLevel}`;
    
    showNotification(message, 'success');
    
    console.log('批量编辑完成:', {
        updatedCount,
        newLevel,
        remark,
        selectedMembers: selectedMembersData.map(m => ({ id: m.id, name: m.name }))
    });
}

// 导出函数到全局
window.filterMembers = filterMembers;
window.sortTable = sortTable;
window.viewMemberDetail = viewMemberDetail;
window.toggleSelectAll = toggleSelectAll;
window.toggleMemberSelection = toggleMemberSelection;
window.openBatchEditModal = openBatchEditModal;
window.closeBatchEditModal = closeBatchEditModal;
window.confirmBatchEdit = confirmBatchEdit;