/**
 * 会员详情页面功能
 * 包含会员信息展示、成长值明细、积分明细等功能
 */

// 当前会员数据
let currentMemberData = null;

/**
 * 初始化会员详情页面
 */
function initMemberDetail() {
    console.log('会员详情页面已初始化');
}


/**
 * 查看会员详情 - 从会员列表页面调用
 * @param {string} memberId - 会员ID  
 */
function viewMemberDetail_Detail(memberId) {
    console.log('打开会员详情页面:', memberId);
    
    // 获取会员数据
    const memberData = getMemberData(memberId);
    if (!memberData) {
        alert('会员信息不存在');
        return;
    }
    
    currentMemberData = memberData;
    
    // 使用系统的openTab功能打开新标签页
    const tabTitle = `会员详情-${memberData.nickname}`;
    
    // 检查是否已经打开了该会员的详情页
    const existingTab = Array.from(document.querySelectorAll('.tab')).find(tab => 
        tab.querySelector('span').textContent === tabTitle
    );
    
    if (existingTab) {
        // 如果已存在，直接激活该标签页
        window.switchTab(existingTab.id);
        return;
    }
    
    // 创建自定义的会员详情标签页
    createMemberDetailTab(tabTitle, memberData);
}

/**
 * 创建会员详情标签页
 * @param {string} tabTitle - 标签页标题
 * @param {Object} memberData - 会员数据
 */
async function createMemberDetailTab(tabTitle, memberData) {
    try {
        // 使用全局的tab计数器
        window.tabCounter++;
        const tabId = `tab-${window.tabCounter}`;
        const contentId = `content-${window.tabCounter}`;
        
        // 创建新的tab
        const tabBar = document.querySelector('.tab-bar');
        const newTab = document.createElement('div');
        newTab.className = 'tab';
        newTab.id = tabId;
        newTab.innerHTML = `
            <span>${tabTitle}</span>
            <button class="close-btn" onclick="closeTab('${tabId}')" aria-label="关闭">×</button>
        `;
        
        // 添加点击事件
        newTab.addEventListener('click', function(e) {
            if (!e.target.classList.contains('close-btn')) {
                window.switchTab(tabId);
            }
        });
        
        tabBar.appendChild(newTab);
        
        // 创建对应的内容区域
        const contentArea = document.querySelector('.content-area');
        const newContent = document.createElement('div');
        newContent.className = 'tab-content';
        newContent.id = contentId;
        
        
        // 加载HTML内容
        const response = await fetch('pages/member-detail.html');
        const htmlContent = await response.text();
        newContent.innerHTML = htmlContent;
        
        contentArea.appendChild(newContent);
        
        // 更新页面内容为具体会员数据
        updateMemberDetailContent(newContent, memberData);
        
        // 初始化标签页功能
        initDetailTabs(newContent);
        
        // 激活新创建的tab
        window.switchTab(tabId);
        
    } catch (error) {
        console.error('创建会员详情标签页失败:', error);
        alert('打开会员详情失败，请重试');
    }
}

/**
 * 更新会员详情页面内容
 * @param {HTMLElement} container - 页面容器
 * @param {Object} memberData - 会员数据
 */
function updateMemberDetailContent(container, memberData) {
    // 更新标题
    const title = container.querySelector('.detail-header h2');
    if (title) {
        title.textContent = `会员详情-${memberData.nickname}`;
    }
    
    // 更新头像
    const avatar = container.querySelector('.avatar');
    if (avatar) {
        avatar.textContent = memberData.nickname.charAt(0);
        avatar.className = `avatar large-avatar ${memberData.avatarClass}`;
    }
    
    // 更新基本信息
    const nameEl = container.querySelector('.member-name');
    if (nameEl) nameEl.textContent = memberData.nickname;
    
    const idEl = container.querySelector('.member-id');
    if (idEl) idEl.textContent = `会员系统编号：${memberData.systemId}`;
    
    const phoneEl = container.querySelector('.member-phone');
    if (phoneEl) phoneEl.textContent = `会员手机号：${memberData.phone}`;
    
    const birthEl = container.querySelector('.member-birth');
    if (birthEl) birthEl.textContent = `会员生日：${memberData.birthday}`;
    
    // 更新资产信息
    const growthValue = container.querySelector('.asset-item:nth-child(1) .asset-value');
    if (growthValue) growthValue.textContent = memberData.growthValue;
    
    const pointsValue = container.querySelector('.asset-item:nth-child(2) .asset-value');
    if (pointsValue) pointsValue.textContent = memberData.points;
    
    const couponsValue = container.querySelector('.asset-item:nth-child(3) .asset-value');
    if (couponsValue) couponsValue.textContent = memberData.coupons;
}

/**
 * 初始化详情标签页功能
 * @param {HTMLElement} container - 页面容器
 */
function initDetailTabs(container) {
    // 确保成长值明细标签页默认激活
    const growthTab = container.querySelector('#growthTab');
    const pointsTab = container.querySelector('#pointsTab');
    const growthHeader = container.querySelector('.tab-header:first-child');
    const pointsHeader = container.querySelector('.tab-header:last-child');
    
    if (growthTab && pointsTab && growthHeader && pointsHeader) {
        growthTab.classList.add('active');
        pointsTab.classList.remove('active');
        growthHeader.classList.add('active');
        pointsHeader.classList.remove('active');
    }
}

/**
 * 切换详情标签页
 * @param {Event} event - 点击事件
 * @param {string} tabName - 标签页名称
 */
function switchDetailTab(event, tabName) {
    const container = event.target.closest('.page-content');
    if (!container) return;
    
    // 移除所有激活状态
    const allHeaders = container.querySelectorAll('.tab-header');
    const allContents = container.querySelectorAll('.tab-content');
    
    allHeaders.forEach(header => header.classList.remove('active'));
    allContents.forEach(content => content.classList.remove('active'));
    
    // 激活当前标签页
    event.target.classList.add('active');
    
    const targetTab = container.querySelector(`#${tabName}Tab`);
    if (targetTab) {
        targetTab.classList.add('active');
    }
}

/**
 * 关闭会员详情标签页
 */
function closeMemberDetailTab() {
    // 获取当前活动的标签页
    const activeTab = document.querySelector('.tab-item.active');
    if (activeTab) {
        const tabId = activeTab.getAttribute('data-tab');
        closeTab(tabId);
    }
}

/**
 * 获取会员数据 - 模拟数据
 * @param {string} memberId - 会员ID
 * @returns {Object|null} 会员数据
 */
function getMemberData(memberId) {
    const mockMembers = {
        'M001': {
            id: 'M001',
            nickname: '张三',
            systemId: '二',
            phone: '138****1234',
            birthday: '1990-05-15',
            avatarClass: 'green-avatar',
            growthValue: 1250,
            points: 890,
            coupons: 5,
            level: 'LV2',
            store: '时尚服装店',
            registerTime: '2024-01-15 14:30:25'
        },
        'M002': {
            id: 'M002',
            nickname: '李四',
            systemId: '三',
            phone: '139****5678',
            birthday: '1985-08-20',
            avatarClass: 'orange-avatar',
            growthValue: 800,
            points: 650,
            coupons: 3,
            level: 'LV1',
            store: '数码电子城',
            registerTime: '2024-02-20 09:15:30'
        },
        'M003': {
            id: 'M003',
            nickname: '王五',
            systemId: '四',
            phone: '136****9012',
            birthday: '1992-12-08',
            avatarClass: 'red-avatar',
            growthValue: 1850,
            points: 1200,
            coupons: 8,
            level: 'LV3',
            store: '美食餐厅',
            registerTime: '2024-03-10 16:45:12'
        },
        'M004': {
            id: 'M004',
            nickname: '赵六',
            systemId: '五',
            phone: '137****3456',
            birthday: '1988-03-25',
            avatarClass: 'purple-avatar',
            growthValue: 600,
            points: 420,
            coupons: 2,
            level: 'LV1',
            store: '家居生活馆',
            registerTime: '2024-04-05 11:20:45'
        },
        'M005': {
            id: 'M005',
            nickname: '孙七',
            systemId: '六',
            phone: '135****7890',
            birthday: '1995-07-12',
            avatarClass: 'pink-avatar',
            growthValue: 2500,
            points: 1800,
            coupons: 12,
            level: 'LV4',
            store: '运动健身店',
            registerTime: '2024-05-22 13:55:18'
        },
        'M006': {
            id: 'M006',
            nickname: '周八',
            systemId: '七',
            phone: '134****2468',
            birthday: '1991-11-30',
            avatarClass: 'blue-avatar',
            growthValue: 1100,
            points: 750,
            coupons: 4,
            level: 'LV2',
            store: '时尚服装店',
            registerTime: '2024-06-18 08:35:22'
        }
    };
    
    return mockMembers[memberId] || null;
}

/**
 * 显示成长值详情弹窗
 * @param {string} changeTime - 变化时间
 * @param {string} changeValue - 变化值
 * @param {string} relatedOrder - 关联订单
 */
function showGrowthDetail(changeTime, changeValue, relatedOrder) {
    const modal = document.getElementById('growthDetailModal');
    const content = document.getElementById('growthDetailContent');
    
    if (!modal || !content) return;
    
    // 根据是否有关联订单生成不同的内容
    let detailContent = '';
    
    if (relatedOrder && relatedOrder !== '无') {
        // 有关联订单的情况
        detailContent = `
            <div class="detail-section">
                <div class="detail-label">变化原因:</div>
                <div class="detail-value">订单消费</div>
            </div>
            <div class="detail-section">
                <div class="detail-label">变化时间:</div>
                <div class="detail-value">${changeTime}</div>
            </div>
            <div class="detail-section">
                <div class="detail-label">成长值增加:</div>
                <div class="detail-value positive">${changeValue}</div>
            </div>
            <div class="detail-section">
                <div class="detail-label">订单编号:</div>
                <div class="detail-value">${relatedOrder}</div>
            </div>
            <div class="detail-section">
                <div class="detail-label">订单总金额:</div>
                <div class="detail-value">¥${generateOrderAmount()}</div>
            </div>
            <div class="detail-section">
                <div class="detail-label">订单时间:</div>
                <div class="detail-value">${changeTime}</div>
            </div>
            <div class="detail-section">
                <div class="detail-label">订单归属据点:</div>
                <div class="detail-value">${getRandomStore()}</div>
            </div>
            <div class="detail-section">
                <div class="detail-label">成长值变化:</div>
                <div class="detail-value positive">${changeValue}</div>
            </div>
        `;
    } else {
        // 无关联订单的情况（系统奖励）
        const reason = getSystemRewardReason();
        detailContent = `
            <div class="detail-section">
                <div class="detail-label">变化原因:</div>
                <div class="detail-value">${reason}</div>
            </div>
            <div class="detail-section">
                <div class="detail-label">变化时间:</div>
                <div class="detail-value">${changeTime}</div>
            </div>
            <div class="detail-section">
                <div class="detail-label">成长值增加:</div>
                <div class="detail-value positive">${changeValue}</div>
            </div>
            <div class="detail-section">
                <div class="detail-description">${getRewardDescription(reason)}</div>
            </div>
        `;
    }
    
    content.innerHTML = detailContent;
    modal.style.display = 'flex';
    
    // 添加点击背景关闭功能
    modal.onclick = function(e) {
        if (e.target === modal) {
            closeGrowthDetailModal();
        }
    };
}

/**
 * 关闭成长值详情弹窗
 */
function closeGrowthDetailModal() {
    const modal = document.getElementById('growthDetailModal');
    if (modal) {
        modal.style.display = 'none';
    }
}

/**
 * 生成随机订单金额
 * @returns {string} 订单金额
 */
function generateOrderAmount() {
    const amounts = ['270.54', '156.88', '89.99', '345.20', '128.50', '298.76', '199.99', '78.30'];
    return amounts[Math.floor(Math.random() * amounts.length)];
}

/**
 * 获取随机店铺
 * @returns {string} 店铺名称
 */
function getRandomStore() {
    const stores = ['美食餐厅', '时尚服装店', '数码电子城', '家居生活馆', '运动健身店'];
    return stores[Math.floor(Math.random() * stores.length)];
}

/**
 * 获取系统奖励原因
 * @returns {string} 奖励原因
 */
function getSystemRewardReason() {
    const reasons = ['生日奖励', '签到奖励', '活动奖励', '推荐奖励', '完善资料奖励'];
    return reasons[Math.floor(Math.random() * reasons.length)];
}

/**
 * 获取奖励描述
 * @param {string} reason - 奖励原因
 * @returns {string} 奖励描述
 */
function getRewardDescription(reason) {
    const descriptions = {
        '生日奖励': '会员生日当天系统自动发放的生日礼品成长值',
        '签到奖励': '会员连续签到获得的成长值奖励',
        '活动奖励': '参与平台活动获得的成长值奖励',
        '推荐奖励': '成功推荐新会员注册获得的成长值奖励',
        '完善资料奖励': '完善个人资料信息获得的成长值奖励'
    };
    return descriptions[reason] || '系统自动发放的成长值奖励';
}

/**
 * 显示积分详情弹窗
 * @param {string} changeTime - 变化时间
 * @param {string} changeValue - 变化值
 * @param {string} relatedOrder - 关联订单
 */
function showPointsDetail(changeTime, changeValue, relatedOrder) {
    const modal = document.getElementById('pointsDetailModal');
    const content = document.getElementById('pointsDetailContent');
    
    if (!modal || !content) return;
    
    // 根据变化值和关联订单生成不同的内容
    let detailContent = '';
    
    if (relatedOrder && relatedOrder !== '无' && !relatedOrder.includes('兑换')) {
        // 有关联订单的情况（订单获得积分）
        detailContent = `
            <div class="detail-section">
                <div class="detail-label">变化原因:</div>
                <div class="detail-value">订单消费</div>
            </div>
            <div class="detail-section">
                <div class="detail-label">变化时间:</div>
                <div class="detail-value">${changeTime}</div>
            </div>
            <div class="detail-section">
                <div class="detail-label">积分变动:</div>
                <div class="detail-value ${changeValue.startsWith('+') ? 'positive' : 'negative'}">${changeValue}</div>
            </div>
            <div class="detail-section">
                <div class="detail-label">订单编号:</div>
                <div class="detail-value">${relatedOrder}</div>
            </div>
            <div class="detail-section">
                <div class="detail-label">订单总金额:</div>
                <div class="detail-value">¥${generateOrderAmount()}</div>
            </div>
            <div class="detail-section">
                <div class="detail-label">订单时间:</div>
                <div class="detail-value">${changeTime}</div>
            </div>
            <div class="detail-section">
                <div class="detail-label">订单归属摊位:</div>
                <div class="detail-value">${getRandomStore()}</div>
            </div>
            <div class="detail-section">
                <div class="detail-label">积分变化:</div>
                <div class="detail-value ${changeValue.startsWith('+') ? 'positive' : 'negative'}">${changeValue}</div>
            </div>
        `;
    } else if (relatedOrder && (relatedOrder.includes('兑换'))) {
        // 积分消耗的情况（兑换商品/优惠券）
        const exchangeType = relatedOrder.includes('商品') ? '商品' : '优惠券';
        const exchangeItem = getRandomExchangeItem(exchangeType);
        detailContent = `
            <div class="detail-section">
                <div class="detail-label">变化原因:</div>
                <div class="detail-value">${relatedOrder}</div>
            </div>
            <div class="detail-section">
                <div class="detail-label">变化时间:</div>
                <div class="detail-value">${changeTime}</div>
            </div>
            <div class="detail-section">
                <div class="detail-label">积分变动:</div>
                <div class="detail-value ${changeValue.startsWith('+') ? 'positive' : 'negative'}">${changeValue}</div>
            </div>
            <div class="detail-section">
                <div class="detail-label">兑换${exchangeType}:</div>
                <div class="detail-value">${exchangeItem}</div>
            </div>
            <div class="detail-section">
                <div class="detail-label">兑换数量:</div>
                <div class="detail-value">1个</div>
            </div>
            <div class="detail-section">
                <div class="detail-description">使用${Math.abs(parseInt(changeValue))}积分兑换${exchangeType}，兑换成功后积分将被扣除且不可退还。</div>
            </div>
        `;
    } else {
        // 无关联订单的情况（系统奖励）
        const reason = getPointsRewardReason();
        detailContent = `
            <div class="detail-section">
                <div class="detail-label">变化原因:</div>
                <div class="detail-value">${reason}</div>
            </div>
            <div class="detail-section">
                <div class="detail-label">变化时间:</div>
                <div class="detail-value">${changeTime}</div>
            </div>
            <div class="detail-section">
                <div class="detail-label">积分变动:</div>
                <div class="detail-value ${changeValue.startsWith('+') ? 'positive' : 'negative'}">${changeValue}</div>
            </div>
            <div class="detail-section">
                <div class="detail-description">${getPointsRewardDescription(reason)}</div>
            </div>
        `;
    }
    
    content.innerHTML = detailContent;
    modal.style.display = 'flex';
    
    // 添加点击背景关闭功能
    modal.onclick = function(e) {
        if (e.target === modal) {
            closePointsDetailModal();
        }
    };
}

/**
 * 关闭积分详情弹窗
 */
function closePointsDetailModal() {
    const modal = document.getElementById('pointsDetailModal');
    if (modal) {
        modal.style.display = 'none';
    }
}

/**
 * 获取随机兑换商品
 * @param {string} type - 兑换类型（商品/优惠券）
 * @returns {string} 兑换物品名称
 */
function getRandomExchangeItem(type) {
    if (type === '商品') {
        const items = ['精美水杯', '品牌T恤', '蓝牙耳机', '保温饭盒', '无线充电器', '护肤礼盒'];
        return items[Math.floor(Math.random() * items.length)];
    } else {
        const coupons = ['满100减20优惠券', '8折通用优惠券', '满200减50优惠券', '新品9折优惠券', '免运费券'];
        return coupons[Math.floor(Math.random() * coupons.length)];
    }
}

/**
 * 获取积分奖励原因
 * @returns {string} 奖励原因
 */
function getPointsRewardReason() {
    const reasons = ['签到奖励', '完成任务', '评价奖励', '邀请好友', '活动奖励', '每日任务'];
    return reasons[Math.floor(Math.random() * reasons.length)];
}

/**
 * 获取积分奖励描述
 * @param {string} reason - 奖励原因
 * @returns {string} 奖励描述
 */
function getPointsRewardDescription(reason) {
    const descriptions = {
        '签到奖励': '连续签到获得的积分奖励，每日签到可获得不同数量的积分',
        '完成任务': '完成平台指定任务获得的积分奖励',
        '评价奖励': '对购买商品进行评价后获得的积分奖励',
        '邀请好友': '成功邀请好友注册并消费后获得的积分奖励',
        '活动奖励': '参与平台活动获得的积分奖励',
        '每日任务': '完成每日任务目标获得的积分奖励'
    };
    return descriptions[reason] || '系统自动发放的积分奖励';
}

// 暴露全局函数
window.viewMemberDetail_Detail = viewMemberDetail_Detail;
window.switchDetailTab = switchDetailTab;
window.closeMemberDetailTab = closeMemberDetailTab;
window.showGrowthDetail = showGrowthDetail;
window.closeGrowthDetailModal = closeGrowthDetailModal;
window.showPointsDetail = showPointsDetail;
window.closePointsDetailModal = closePointsDetailModal;