// 批量编辑第二步 - 等级设置页面

let selectedShops = [];
let levelData = [];

// 预设模板
const templates = {
    default: [
        { 
            level: 'LV1', 
            name: '铜牌会员', 
            growthMin: 0, 
            growthMax: 100, 
            memberDiscount: true, 
            discountRate: 5, 
            pointExchange: false, 
            birthdayCoupon: false, 
            birthdayDoublePoints: false 
        },
        { 
            level: 'LV2', 
            name: '银牌会员', 
            growthMin: 101, 
            growthMax: 500, 
            memberDiscount: true, 
            discountRate: 10, 
            pointExchange: true, 
            birthdayCoupon: true, 
            birthdayDoublePoints: true 
        },
        { 
            level: 'LV3', 
            name: '金牌会员', 
            growthMin: 501, 
            growthMax: 1200, 
            memberDiscount: true, 
            discountRate: 15, 
            pointExchange: true, 
            birthdayCoupon: true, 
            birthdayDoublePoints: true 
        }
    ],
    premium: [
        { 
            level: 'LV1', 
            name: '新手会员', 
            growthMin: 0, 
            growthMax: 200, 
            memberDiscount: true, 
            discountRate: 8, 
            pointExchange: true, 
            birthdayCoupon: true, 
            birthdayDoublePoints: false 
        },
        { 
            level: 'LV2', 
            name: '进阶会员', 
            growthMin: 201, 
            growthMax: 800, 
            memberDiscount: true, 
            discountRate: 15, 
            pointExchange: true, 
            birthdayCoupon: true, 
            birthdayDoublePoints: true 
        },
        { 
            level: 'LV3', 
            name: '高级会员', 
            growthMin: 801, 
            growthMax: 2000, 
            memberDiscount: true, 
            discountRate: 20, 
            pointExchange: true, 
            birthdayCoupon: true, 
            birthdayDoublePoints: true 
        },
        { 
            level: 'LV4', 
            name: 'VIP会员', 
            growthMin: 2001, 
            growthMax: 9999, 
            memberDiscount: true, 
            discountRate: 25, 
            pointExchange: true, 
            birthdayCoupon: true, 
            birthdayDoublePoints: true 
        }
    ]
};

// 获取URL参数
function getUrlParameter(name) {
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get(name) || '';
}

// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
    loadSelectedShops();
    loadTemplate('default'); // 默认加载基础模板
    displaySelectedShops();
});

// 加载选中的店铺数据
function loadSelectedShops() {
    const storedShops = sessionStorage.getItem('batchEditSelectedShops');
    if (storedShops) {
        selectedShops = JSON.parse(storedShops);
    } else {
        // 如果没有数据，返回上一步
        showNotification('未找到选中的店铺数据，请重新选择', 'error');
        setTimeout(() => {
            navigateTo('batch-edit-step1.html');
        }, 2000);
        return;
    }
}

// 显示选中的店铺
function displaySelectedShops() {
    const shopCount = document.getElementById('shop-count');
    const shopsList = document.getElementById('selected-shops-list');
    
    shopCount.textContent = selectedShops.length;
    
    const html = selectedShops.map(shop => `
        <span class="shop-tag">${shop.name}</span>
    `).join('');
    
    shopsList.innerHTML = html;
}

// 加载模板
function loadTemplate(templateName) {
    if (templates[templateName]) {
        levelData = JSON.parse(JSON.stringify(templates[templateName])); // 深拷贝
        renderTable();
        showNotification(`已加载${templateName === 'default' ? '默认' : '高级'}模板`, 'success');
    }
}

// 重置设置
function resetSettings() {
    confirmAction('确定要重置所有设置吗？', () => {
        levelData = [];
        renderTable();
        showNotification('已重置所有设置', 'info');
    });
}

// 渲染表格
function renderTable() {
    const tableBody = document.getElementById('level-edit-table');
    let html = '';
    
    levelData.forEach((level, index) => {
        // 主行
        html += `
        <tr>
            <td>${level.level}</td>
            <td>
                <input type="text" value="${level.name}" id="levelName_${index}" 
                       style="width: 100%; padding: 5px; border: 1px solid #ddd;"
                       onchange="updateLevelData(${index}, 'name', this.value)">
            </td>
            <td>
                <button class="expand-btn" onclick="toggleLevelDetail(${index})" id="expandBtn_${index}">
                    展开详情
                </button>
            </td>
        </tr>`;
        
        // 详情行（默认隐藏）
        html += `
        <tr id="detailRow_${index}" class="level-detail-row hidden">
            <td colspan="3">
                <div class="level-detail-content">
                    <div class="detail-form-group">
                        <div class="detail-label">成长值范围</div>
                        <div class="detail-input">
                            <input type="number" value="${level.growthMin}" id="growthMin_${index}" 
                                   style="width:60px;" onchange="updateLevelData(${index}, 'growthMin', this.value)"> 
                            - 
                            <input type="number" value="${level.growthMax}" id="growthMax_${index}" 
                                   style="width:60px;" onchange="updateLevelData(${index}, 'growthMax', this.value)">
                        </div>
                    </div>
                    
                    <div class="detail-form-group">
                        <div class="detail-label">开启会员折扣</div>
                        <div class="detail-input">
                            <label class="switch">
                                <input type="checkbox" ${level.memberDiscount ? 'checked' : ''} 
                                       id="memberDiscount_${index}" onchange="toggleDiscountRate(${index})">
                                <span class="slider"></span>
                            </label>
                        </div>
                    </div>
                    
                    <div class="detail-form-group">
                        <div class="detail-label">折扣率(%)</div>
                        <div class="detail-input">
                            <input type="number" value="${level.discountRate}" id="discountRate_${index}" 
                                   ${!level.memberDiscount ? 'disabled' : ''}
                                   onchange="updateLevelData(${index}, 'discountRate', this.value)">
                        </div>
                    </div>
                    
                    <div class="detail-form-group">
                        <div class="detail-label">开启积分兑换</div>
                        <div class="detail-input">
                            <label class="switch">
                                <input type="checkbox" ${level.pointExchange ? 'checked' : ''} 
                                       id="pointExchange_${index}" onchange="updateLevelData(${index}, 'pointExchange', this.checked)">
                                <span class="slider"></span>
                            </label>
                        </div>
                    </div>
                    
                    <div class="detail-form-group">
                        <div class="detail-label">开启生日优惠券</div>
                        <div class="detail-input">
                            <label class="switch">
                                <input type="checkbox" ${level.birthdayCoupon ? 'checked' : ''} 
                                       id="birthdayCoupon_${index}" onchange="toggleCouponButton(${index})">
                                <span class="slider"></span>
                            </label>
                        </div>
                    </div>
                    
                    <div class="detail-form-group">
                        <div class="detail-label">生日优惠券设置</div>
                        <div class="detail-input">
                            <button class="btn btn-small ${!level.birthdayCoupon ? 'hidden' : ''}" 
                                    id="addCouponBtn_${index}" onclick="addBirthdayCoupon(${index})">
                                添加优惠券
                            </button>
                        </div>
                    </div>
                    
                    <div class="detail-form-group">
                        <div class="detail-label">开启生日双倍积分</div>
                        <div class="detail-input">
                            <label class="switch">
                                <input type="checkbox" ${level.birthdayDoublePoints ? 'checked' : ''} 
                                       id="birthdayDoublePoints_${index}" onchange="updateLevelData(${index}, 'birthdayDoublePoints', this.checked)">
                                <span class="slider"></span>
                            </label>
                        </div>
                    </div>
                    
                    <div class="detail-actions">
                        ${index === levelData.length - 1 ? `
                            <button class="btn btn-primary" onclick="addNewLevel()" style="margin-right: 10px;">
                                添加新等级
                            </button>
                            <button class="btn" style="background: #f44336; color: white;" onclick="deleteLevel(${index})">
                                删除等级
                            </button>
                        ` : ''}
                    </div>
                </div>
            </td>
        </tr>`;
    });
    
    tableBody.innerHTML = html;
}

// 更新等级数据
function updateLevelData(index, field, value) {
    if (levelData[index]) {
        if (field === 'growthMin' || field === 'growthMax' || field === 'discountRate') {
            levelData[index][field] = parseInt(value) || 0;
        } else {
            levelData[index][field] = value;
        }
    }
}

// 切换等级详情展开/收缩
function toggleLevelDetail(index) {
    const detailRow = document.getElementById(`detailRow_${index}`);
    const expandBtn = document.getElementById(`expandBtn_${index}`);
    
    if (detailRow.classList.contains('hidden')) {
        // 展开
        detailRow.classList.remove('hidden');
        expandBtn.textContent = '收起详情';
        expandBtn.style.background = '#ff9800';
    } else {
        // 收起
        detailRow.classList.add('hidden');
        expandBtn.textContent = '展开详情';
        expandBtn.style.background = '#4CAF50';
    }
}

// 切换折扣率输入框状态
function toggleDiscountRate(index) {
    const checkbox = document.getElementById(`memberDiscount_${index}`);
    const discountInput = document.getElementById(`discountRate_${index}`);
    
    if (checkbox.checked) {
        discountInput.disabled = false;
        levelData[index].memberDiscount = true;
    } else {
        discountInput.disabled = true;
        levelData[index].memberDiscount = false;
    }
}

// 切换优惠券按钮显示
function toggleCouponButton(index) {
    const checkbox = document.getElementById(`birthdayCoupon_${index}`);
    const addButton = document.getElementById(`addCouponBtn_${index}`);
    
    if (checkbox.checked) {
        addButton.classList.remove('hidden');
        levelData[index].birthdayCoupon = true;
    } else {
        addButton.classList.add('hidden');
        levelData[index].birthdayCoupon = false;
    }
}

// 添加生日优惠券
function addBirthdayCoupon(index) {
    const modal = document.getElementById('coupon-modal');
    modal.classList.remove('hidden');
    resetCouponForm();
}

// 关闭优惠券弹窗
function closeCouponModal(event) {
    if (event && event.target !== event.currentTarget) {
        return;
    }
    
    const modal = document.getElementById('coupon-modal');
    if (modal) {
        modal.classList.add('hidden');
    }
}

// 重置优惠券表单
function resetCouponForm() {
    document.getElementById('coupon-name').value = '生日优惠券';
    document.getElementById('coupon-threshold').value = '10';
    document.getElementById('coupon-discount').value = '1';
    document.getElementById('coupon-validity').value = '1';
}

// 提交优惠券
function submitCoupon() {
    const couponData = {
        name: document.getElementById('coupon-name').value,
        threshold: document.getElementById('coupon-threshold').value,
        discount: document.getElementById('coupon-discount').value,
        validity: document.getElementById('coupon-validity').value
    };
    
    if (!couponData.name.trim()) {
        showNotification('请输入优惠券名称', 'error');
        return;
    }
    
    if (parseInt(couponData.discount) >= parseInt(couponData.threshold)) {
        showNotification('减免金额不能大于或等于门槛金额', 'error');
        return;
    }
    
    showNotification(`成功添加优惠券：${couponData.name}`, 'success');
    closeCouponModal();
}

// 删除等级
function deleteLevel(index) {
    if (levelData.length <= 1) {
        showNotification('至少需要保留一个等级', 'warning');
        return;
    }
    
    confirmAction('确定要删除这个等级吗？', () => {
        levelData.splice(index, 1);
        
        // 重新编号等级
        levelData.forEach((level, i) => {
            level.level = `LV${i + 1}`;
        });
        
        renderTable();
        showNotification(`删除等级成功`, 'success');
    });
}

// 添加新等级
function addNewLevel() {
    const newLevelNum = levelData.length + 1;
    const lastLevel = levelData[levelData.length - 1];
    
    const newLevel = {
        level: `LV${newLevelNum}`,
        name: `新等级${newLevelNum}`,
        growthMin: lastLevel.growthMax + 1,
        growthMax: lastLevel.growthMax + 1000,
        memberDiscount: true,
        discountRate: Math.min(lastLevel.discountRate + 5, 50),
        pointExchange: true,
        birthdayCoupon: true,
        birthdayDoublePoints: true
    };
    
    levelData.push(newLevel);
    renderTable();
    showNotification(`添加新等级 LV${newLevelNum}`, 'success');
}

// 上一步
function previousStep() {
    navigateTo('batch-edit-step1.html');
}

// 下一步
function nextStep() {
    if (levelData.length === 0) {
        showNotification('请至少设置一个等级', 'warning');
        return;
    }
    
    // 验证等级设置
    for (let i = 0; i < levelData.length; i++) {
        const level = levelData[i];
        if (!level.name.trim()) {
            showNotification(`请为 ${level.level} 设置等级名称`, 'error');
            return;
        }
        if (level.growthMin >= level.growthMax) {
            showNotification(`${level.level} 的成长值范围设置有误`, 'error');
            return;
        }
    }
    
    // 将等级设置数据存储到sessionStorage
    sessionStorage.setItem('batchEditLevelData', JSON.stringify(levelData));
    
    // 跳转到第三步
    navigateTo('batch-edit-step3.html');
}

// 导出函数到全局
window.loadTemplate = loadTemplate;
window.resetSettings = resetSettings;
window.toggleLevelDetail = toggleLevelDetail;
window.toggleDiscountRate = toggleDiscountRate;
window.toggleCouponButton = toggleCouponButton;
window.addBirthdayCoupon = addBirthdayCoupon;
window.closeCouponModal = closeCouponModal;
window.submitCoupon = submitCoupon;
window.deleteLevel = deleteLevel;
window.addNewLevel = addNewLevel;
window.updateLevelData = updateLevelData;
window.previousStep = previousStep;
window.nextStep = nextStep;