/**
 * 等级编辑页面功能模块
 * 包含该页面的所有交互逻辑
 */

// 模拟不同商户的等级编辑数据
const merchantEditData = {
    '牛牛蔬菜店': [
        {
            level: 'LV1',
            name: '铜牌会员',
            growthStart: 0,
            growthEnd: 100,
            discountEnabled: true,
            discountRate: 5,
            pointsEnabled: false,
            birthdayCouponEnabled: false,
            birthdayPointsEnabled: false
        },
        {
            level: 'LV2',
            name: '银牌会员',
            growthStart: 101,
            growthEnd: 500,
            discountEnabled: true,
            discountRate: 10,
            pointsEnabled: true,
            birthdayCouponEnabled: true,
            birthdayPointsEnabled: true
        },
        {
            level: 'LV3',
            name: '金牌会员',
            growthStart: 501,
            growthEnd: 1200,
            discountEnabled: true,
            discountRate: 15,
            pointsEnabled: true,
            birthdayCouponEnabled: true,
            birthdayPointsEnabled: true
        },
        {
            level: 'LV4',
            name: '钻石会员',
            growthStart: 1201,
            growthEnd: 9999,
            discountEnabled: true,
            discountRate: 20,
            pointsEnabled: true,
            birthdayCouponEnabled: true,
            birthdayPointsEnabled: true
        }
    ],
    '羊羊水果店': [
        {
            level: 'LV1',
            name: '普通会员',
            growthStart: 0,
            growthEnd: 80,
            discountEnabled: true,
            discountRate: 2,
            pointsEnabled: false,
            birthdayCouponEnabled: false,
            birthdayPointsEnabled: false
        },
        {
            level: 'LV2',
            name: '优质会员',
            growthStart: 81,
            growthEnd: 400,
            discountEnabled: true,
            discountRate: 8,
            pointsEnabled: true,
            birthdayCouponEnabled: false,
            birthdayPointsEnabled: false
        },
        {
            level: 'LV3',
            name: '贵宾会员',
            growthStart: 401,
            growthEnd: 1000,
            discountEnabled: true,
            discountRate: 12,
            pointsEnabled: true,
            birthdayCouponEnabled: true,
            birthdayPointsEnabled: true
        }
    ]
};

// 页面初始化函数（必需）
function initLevelEdit() {
    console.log('等级编辑页面已初始化');
    
    // 从URL参数或全局变量获取商户名称
    const merchantName = getCurrentMerchantName();
    if (merchantName) {
        updateEditPageContent(merchantName);
    }
    
    // 初始化新增功能区域的交互事件
    initPointRatioSettings();
}

// 获取当前商户名称
function getCurrentMerchantName() {
    // 可以从tab标题中提取商户名称
    const activeTab = document.querySelector('.tab.active');
    if (activeTab) {
        const tabTitle = activeTab.textContent.trim();
        // 提取商户名称（去掉" - 等级编辑"后缀）
        const merchantName = tabTitle.replace(' - 等级编辑', '');
        // 如果标题中包含了商户名称，则返回商户名称
        if (merchantName !== tabTitle) {
            return merchantName;
        }
        // 否则尝试从关闭按钮的 × 前面获取标题文本
        const tabTextContent = activeTab.querySelector('.tab-text');
        if (tabTextContent) {
            return tabTextContent.textContent.replace(' - 等级编辑', '');
        }
    }
    return '时尚服装店'; // 默认值
}

// 更新页面内容
function updateEditPageContent(merchantName) {
    // 更新页面标题
    const merchantNameElement = document.getElementById('merchantName');
    if (merchantNameElement) {
        merchantNameElement.textContent = merchantName;
    }
    
    // 更新表格数据
    const editData = merchantEditData[merchantName];
    if (editData) {
        updateEditTable(editData);
    }
}

// 更新编辑表格数据
function updateEditTable(editData) {
    const tbody = document.getElementById('levelEditBody');
    if (!tbody) return;
    
    tbody.innerHTML = '';
    
    editData.forEach(level => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${level.level}</td>
            <td>
                <input type="text" value="${level.name}" class="form-input">
            </td>
            <td>
                <div class="range-input">
                    <input type="number" value="${level.growthStart}" class="form-input range-start"> -
                    <input type="number" value="${level.growthEnd}" class="form-input range-end">
                </div>
            </td>
            <td>
                <label class="switch">
                    <input type="checkbox" ${level.discountEnabled ? 'checked' : ''}>
                    <span class="slider"></span>
                </label>
            </td>
            <td>
                <input type="number" value="${level.discountRate}" class="form-input discount-input">
            </td>
            <td>
                <label class="switch">
                    <input type="checkbox" ${level.pointsEnabled ? 'checked' : ''}>
                    <span class="slider"></span>
                </label>
            </td>
            <td>
                <label class="switch">
                    <input type="checkbox" ${level.birthdayCouponEnabled ? 'checked' : ''}>
                    <span class="slider"></span>
                </label>
            </td>
            <td>
                <button class="btn btn-action" onclick="addCoupon('${level.level}')">添加优惠券</button>
            </td>
            <td>
                <label class="switch">
                    <input type="checkbox" ${level.birthdayPointsEnabled ? 'checked' : ''}>
                    <span class="slider"></span>
                </label>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// 添加优惠券功能
function addCoupon(level) {
    showCouponModal(level);
}

// 显示优惠券添加弹窗
async function showCouponModal(level) {
    try {
        
        // 加载HTML内容
        const response = await fetch('pages/coupon-modal.html');
        const modalHtml = await response.text();
        
        // 添加到页面
        document.body.insertAdjacentHTML('beforeend', modalHtml);
        
        // 存储当前等级信息
        window.currentCouponLevel = level;
        
    } catch (error) {
        console.error('加载优惠券弹窗失败:', error);
        alert('加载弹窗失败，请重试');
    }
}


// 关闭优惠券弹窗
function closeCouponModal() {
    const modal = document.getElementById('couponModal');
    if (modal) {
        modal.remove();
    }
}

// 确认添加优惠券
function confirmAddCoupon() {
    const couponName = document.getElementById('couponName').value;
    const threshold = document.getElementById('couponThreshold').value;
    const discount = document.getElementById('couponDiscount').value;
    const validity = document.getElementById('couponValidity').value;
    const level = window.currentCouponLevel;
    
    if (!couponName.trim()) {
        alert('请输入优惠券名称');
        return;
    }
    
    console.log('添加优惠券:', {
        level: level,
        name: couponName,
        threshold: threshold,
        discount: discount,
        validity: validity
    });
    
    alert(`已为${level}添加优惠券"${couponName}"`);
    closeCouponModal();
}

// 保存等级编辑
function saveLevelEdit() {
    // 收集表单数据
    const formData = collectFormData();
    console.log('保存的等级编辑数据:', formData);
    alert('等级编辑设置已保存！');
}

// 收集表单数据
function collectFormData() {
    const tbody = document.getElementById('levelEditBody');
    if (!tbody) return {};
    
    const rows = tbody.querySelectorAll('tr');
    const levelData = [];
    
    rows.forEach((row, index) => {
        const data = {
            level: row.cells[0].textContent,
            name: row.querySelector('input[type="text"]').value,
            growthStart: parseInt(row.querySelector('.range-start').value),
            growthEnd: parseInt(row.querySelector('.range-end').value),
            discountEnabled: row.querySelectorAll('input[type="checkbox"]')[0].checked,
            discountRate: parseInt(row.querySelector('.discount-input').value),
            pointsEnabled: row.querySelectorAll('input[type="checkbox"]')[1].checked,
            birthdayCouponEnabled: row.querySelectorAll('input[type="checkbox"]')[2].checked,
            birthdayPointsEnabled: row.querySelectorAll('input[type="checkbox"]')[3].checked
        };
        levelData.push(data);
    });
    
    // 收集积分有效期设置
    const validityDays = document.getElementById('validityDays')?.value || 365;
    
    // 收集积分兑换比例设置
    const spendAmount = document.getElementById('spendAmount')?.value || 1;
    const earnPoints = document.getElementById('earnPoints')?.value || 1;
    const deductPoints = document.getElementById('deductPoints')?.value || 100;
    const deductAmount = document.getElementById('deductAmount')?.value || 1;
    
    // 收集单笔订单最大积分使用限制
    const limitType = document.querySelector('input[name="limitType"]:checked')?.value || 'none';
    const limitPercentage = document.getElementById('limitPercentage')?.value || 50;
    const limitAmount = document.getElementById('limitAmount')?.value || 100;
    
    return {
        levels: levelData,
        pointValidity: {
            validityDays: parseInt(validityDays)
        },
        pointRatio: {
            spendAmount: parseFloat(spendAmount),
            earnPoints: parseInt(earnPoints),
            deductPoints: parseInt(deductPoints),
            deductAmount: parseFloat(deductAmount),
            limitType: limitType,
            limitPercentage: parseInt(limitPercentage),
            limitAmount: parseFloat(limitAmount)
        }
    };
}


// 初始化积分兑换比例设置的交互逻辑
function initPointRatioSettings() {
    const limitTypeRadios = document.querySelectorAll('input[name="limitType"]');
    const percentageContainer = document.querySelector('.percentage-container');
    const fixedContainer = document.querySelector('.fixed-container');
    
    if (limitTypeRadios.length === 0) return;
    
    // 积分使用限制类型变化事件
    limitTypeRadios.forEach(radio => {
        radio.addEventListener('change', function() {
            const value = this.value;
            
            // 隐藏所有容器
            if (percentageContainer) percentageContainer.style.display = 'none';
            if (fixedContainer) fixedContainer.style.display = 'none';
            
            // 显示对应的容器
            if (value === 'percentage' && percentageContainer) {
                percentageContainer.style.display = 'flex';
            } else if (value === 'fixed' && fixedContainer) {
                fixedContainer.style.display = 'flex';
            }
        });
    });
}

// 将需要在HTML中调用的函数暴露到全局作用域
window.addCoupon = addCoupon;
window.saveLevelEdit = saveLevelEdit;
window.closeCouponModal = closeCouponModal;
window.confirmAddCoupon = confirmAddCoupon;

// 页面清理函数（可选）
function cleanupLevelEdit() {
    // 清理事件监听器等
}