/**
 * 会员查看页面功能
 * 会员列表的查看、筛选和分页功能
 */

// 页面初始化函数（必需）
function initMemberView() {
    console.log('会员查看页面已初始化');
    initMemberTable();
    bindMemberEvents();
}

// 初始化会员表格
function initMemberTable() {
    const selectAllCheckbox = document.getElementById('selectAll');
    if (selectAllCheckbox) {
        selectAllCheckbox.addEventListener('change', toggleSelectAll);
    }
}

// 绑定事件
function bindMemberEvents() {
    // 筛选查询按钮事件已在HTML中绑定onclick
    
    // 分页大小改变事件
    const pageSizeSelect = document.getElementById('pageSize');
    if (pageSizeSelect) {
        pageSizeSelect.addEventListener('change', handlePageSizeChange);
    }
}

// 全选切换
function toggleSelectAll() {
    const selectAllCheckbox = document.getElementById('selectAll');
    const memberCheckboxes = document.querySelectorAll('#memberTableBody input[type="checkbox"]');
    
    memberCheckboxes.forEach(checkbox => {
        checkbox.checked = selectAllCheckbox.checked;
    });
}

// 筛选查询功能
function searchMembers() {
    const storeFilter = document.getElementById('storeFilter').value;
    const nicknameFilter = document.getElementById('nicknameFilter').value;
    const phoneFilter = document.getElementById('phoneFilter').value;
    const levelFilter = document.getElementById('levelFilter').value;
    const registrationDate = document.getElementById('registrationDate').value;
    
    console.log('筛选条件:', {
        store: storeFilter,
        nickname: nicknameFilter,
        phone: phoneFilter,
        level: levelFilter,
        date: registrationDate
    });
    
    // 这里实现筛选逻辑
    filterMemberTable(storeFilter, nicknameFilter, phoneFilter, levelFilter, registrationDate);
}

// 筛选表格数据
function filterMemberTable(store, nickname, level, date) {
    const tableBody = document.getElementById('memberTableBody');
    const rows = tableBody.querySelectorAll('tr');
    
    rows.forEach(row => {
        let showRow = true;
        
        // 店铺筛选
        if (store && row.cells[1].textContent !== store) {
            showRow = false;
        }
        
        // 昵称筛选
        if (nickname && !row.cells[4].textContent.toLowerCase().includes(nickname.toLowerCase())) {
            showRow = false;
        }
        
        // 等级筛选
        if (level && !row.cells[6].textContent.includes(level)) {
            showRow = false;
        }
        
        // 日期筛选（简单日期匹配）
        if (date && !row.cells[8].textContent.includes(date)) {
            showRow = false;
        }
        
        row.style.display = showRow ? '' : 'none';
    });
}

// 查看会员详情
function viewMemberDetail(memberId) {
    console.log('查看会员详情:', memberId);
    
    // 先加载会员详情模块
    loadMemberDetailModule().then(() => {
        // 调用会员详情模块的函数
        if (window.viewMemberDetail_Detail) {
            window.viewMemberDetail_Detail(memberId);
        } else {
            console.error('会员详情模块未正确加载');
            alert('页面加载失败，请重试');
        }
    }).catch(error => {
        console.error('加载会员详情模块失败:', error);
        alert('页面加载失败，请重试');
    });
}

// 动态加载会员详情模块
async function loadMemberDetailModule() {
    // 检查是否已经加载
    if (window.memberDetailModuleLoaded) {
        return Promise.resolve();
    }
    
    return new Promise((resolve, reject) => {
        const script = document.createElement('script');
        script.src = 'js/member-detail.js';
        script.onload = () => {
            window.memberDetailModuleLoaded = true;
            resolve();
        };
        script.onerror = () => {
            reject(new Error('Failed to load member-detail.js'));
        };
        document.head.appendChild(script);
    });
}

// 处理分页大小改变
function handlePageSizeChange() {
    const pageSize = document.getElementById('pageSize').value;
    console.log('分页大小改为:', pageSize);
    
    // 这里实现分页逻辑
    // 实际项目中会重新请求数据或重新分页显示
}

// 排序功能
function sortTable(columnIndex, sortType = 'asc') {
    const table = document.querySelector('.member-table');
    const tbody = table.querySelector('tbody');
    const rows = Array.from(tbody.querySelectorAll('tr'));
    
    rows.sort((a, b) => {
        const aValue = a.cells[columnIndex].textContent.trim();
        const bValue = b.cells[columnIndex].textContent.trim();
        
        if (sortType === 'asc') {
            return aValue.localeCompare(bValue, 'zh-CN');
        } else {
            return bValue.localeCompare(aValue, 'zh-CN');
        }
    });
    
    // 重新插入排序后的行
    rows.forEach(row => tbody.appendChild(row));
}

// 重置筛选条件
function resetFilters() {
    document.getElementById('storeFilter').value = '';
    document.getElementById('nicknameFilter').value = '';
    document.getElementById('levelFilter').value = '';
    document.getElementById('registrationDate').value = '';
    
    // 显示所有行
    const tableBody = document.getElementById('memberTableBody');
    const rows = tableBody.querySelectorAll('tr');
    rows.forEach(row => {
        row.style.display = '';
    });
}

// 暴露到全局作用域供HTML调用
window.searchMembers = searchMembers;
window.viewMemberDetail = viewMemberDetail;
window.resetFilters = resetFilters;
window.sortTable = sortTable;

// 页面清理函数（可选）
function cleanupMemberView() {
    // 清理事件监听器等
    const selectAllCheckbox = document.getElementById('selectAll');
    if (selectAllCheckbox) {
        selectAllCheckbox.removeEventListener('change', toggleSelectAll);
    }
    
    const pageSizeSelect = document.getElementById('pageSize');
    if (pageSizeSelect) {
        pageSizeSelect.removeEventListener('change', handlePageSizeChange);
    }
}