<?php
$title = '商品管理';
include __DIR__ . '/head.php';

// 获取接口分类
$classes_cloud = $DB->getAll("SELECT * FROM pre_login_class WHERE biz='cloud' ORDER BY id ASC");
$classes_dg = $DB->getAll("SELECT * FROM pre_login_class WHERE biz='dg' ORDER BY id ASC");
$version_name_cloud = $conf['version_name_cloud'] ?? '云端版';
$version_name_qzone = $conf['version_name_qzone'] ?? '秒赞版';
$version_name_all = $conf['version_name_all'] ?? '通用版';
$version_name_dg = $conf['version_name_dg'] ?? '代挂版';
$biz = isset($_GET['biz']) ? daddslashes($_GET['biz']) : 'all';
if(!in_array($biz, ['all','cloud','dg','qzone'], true)) $biz = 'all';
$version_name_cloud_short = preg_replace('/版$/u', '', $version_name_cloud);
$version_name_dg_short = preg_replace('/版$/u', '', $version_name_dg);
$version_name_qzone_short = preg_replace('/版$/u', '', $version_name_qzone);
$version_name_cloud_all = $conf['version_name_cloud_all'] ?? ($version_name_cloud_short . '·秒赞');
$version_name_dg_all = $conf['version_name_dg_all'] ?? ($version_name_dg_short . '·秒赞');
$version_name_tri_all = $conf['version_name_tri_all'] ?? '三版通用';
?>

<div class="p-4 md:p-6">
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div class="p-4 md:p-6 border-b border-gray-200">
            <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-3">
                <div>
                    <h2 class="text-base md:text-lg font-semibold text-gray-800">商品列表</h2>
                    <p class="text-xs md:text-sm text-gray-500 mt-1">管理<?php echo htmlspecialchars($version_name_cloud); ?> / <?php echo htmlspecialchars($version_name_dg); ?> / <?php echo htmlspecialchars($version_name_qzone); ?> / <?php echo htmlspecialchars($version_name_cloud_all); ?> / <?php echo htmlspecialchars($version_name_dg_all); ?> / <?php echo htmlspecialchars($version_name_tri_all); ?>商品和价格</p>
                </div>
                <div class="flex flex-wrap gap-2">
                    <select class="px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent" onchange="location.href='goods.php?biz='+this.value">
                        <option value="all" <?php echo $biz==='all'?'selected':''; ?>>全部</option>
                        <option value="cloud" <?php echo $biz==='cloud'?'selected':''; ?>><?php echo htmlspecialchars($version_name_cloud_short); ?></option>
                        <option value="dg" <?php echo $biz==='dg'?'selected':''; ?>><?php echo htmlspecialchars($version_name_dg_short); ?></option>
                        <option value="qzone" <?php echo $biz==='qzone'?'selected':''; ?>><?php echo htmlspecialchars($version_name_qzone_short); ?></option>
                    </select>
                    <button onclick="openAddModal()" class="px-4 py-2 bg-green-600 hover:bg-green-700 text-white font-medium rounded-lg transition text-sm">
                        <i class="fas fa-plus mr-2"></i>添加商品
                    </button>
                    <button onclick="openSyncModal()" class="px-4 py-2 bg-orange-600 hover:bg-orange-700 text-white font-medium rounded-lg transition text-sm">
                        <i class="fas fa-sync mr-2"></i>同步活动
                    </button>
                </div>
            </div>
        </div>
        
        <div class="overflow-x-auto">
            <table class="w-full min-w-[600px]">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">排序</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">商品名称</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">版本</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">基础价格</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">时长</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">接口分类</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">活动</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">折扣</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">状态</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">操作</th>
                    </tr>
                </thead>
                <tbody id="goods-list" class="divide-y divide-gray-200">
                </tbody>
            </table>
        </div>
        
        <!-- 分页 -->
        <div class="p-3 md:p-4 border-t border-gray-200 flex flex-col md:flex-row md:items-center md:justify-between gap-3">
            <span class="text-xs md:text-sm text-gray-600">共 <span id="total" class="font-semibold">0</span> 件商品</span>
            <div class="flex items-center gap-2">
                <button onclick="prevPage()" class="px-3 py-1.5 border border-gray-300 rounded-lg text-xs md:text-sm hover:bg-gray-50">上一页</button>
                <span class="text-xs md:text-sm text-gray-600">第 <span id="current-page">1</span> 页</span>
                <button onclick="nextPage()" class="px-3 py-1.5 border border-gray-300 rounded-lg text-xs md:text-sm hover:bg-gray-50">下一页</button>
            </div>
        </div>
        
        <!-- 价格与提成说明 -->
        <div class="p-4 md:p-6 bg-blue-50 border-t border-blue-100">
            <h4 class="text-sm font-semibold text-blue-800 mb-3">价格与提成逻辑说明</h4>
            
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <div>
                    <p class="text-xs font-medium text-blue-800 mb-2">1. 价格计算逻辑</p>
                    <ul class="text-xs text-blue-700 space-y-1">
                        <li>- 基础价格为商品原价。</li>
                        <li>- 支付价 = 基础价格 × 用户等级折扣 × 活动折扣(如有)。</li>
                        <li>- 例如：原价100元，VIP1(8折)用户在9折活动期间支付 100 × 0.8 × 0.9 = 72元。</li>
                    </ul>
                </div>
                
                <div>
                    <p class="text-xs font-medium text-blue-800 mb-2">2. 提成计算逻辑</p>
                    <ul class="text-xs text-blue-700 space-y-1">
                        <li>- 提成模式：差价提成。</li>
                        <li>- 提成金额 = 买家支付价 - 上级成本价。</li>
                        <li>- 上级成本价 = 基础价格 × 上级等级折扣 × 活动折扣(如有)。</li>
                        <li>- 这种模式确保了代理级别越高（折扣越大），下级消费时获得的利润越高。</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 添加/编辑模态框 -->
<div id="goods-modal" class="fixed inset-0 bg-black/50 hidden items-center justify-center z-50 p-4">
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-lg max-h-[90vh] overflow-y-auto">
        <div class="p-4 border-b border-gray-200 flex items-center justify-between sticky top-0 bg-white">
            <h3 id="modal-title" class="text-base md:text-lg font-semibold">添加商品</h3>
            <button onclick="closeModal()" class="text-gray-400 hover:text-gray-600">
                <i class="fas fa-times text-xl"></i>
            </button>
        </div>
        <form onsubmit="saveGoods(this);return false;" class="p-4 md:p-6 space-y-4">
            <input type="hidden" name="id" id="goods-id" value="0">
            <input type="hidden" name="act" id="goods-act" value="add">
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">商品名称</label>
                <input type="text" name="name" id="goods-name" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="如：月卡、季卡、年卡" required>
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">产品版本</label>
                <select name="version" id="goods-version" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500" onchange="toggleTypeByVersion()">
                    <option value="cloud"><?php echo htmlspecialchars($version_name_cloud); ?></option>
                    <option value="dg"><?php echo htmlspecialchars($version_name_dg); ?></option>
                    <option value="qzone"><?php echo htmlspecialchars($version_name_qzone); ?></option>
                    <option value="cloud_all"><?php echo htmlspecialchars($version_name_cloud_all); ?></option>
                    <option value="dg_all"><?php echo htmlspecialchars($version_name_dg_all); ?></option>
                    <option value="tri_all"><?php echo htmlspecialchars($version_name_tri_all); ?></option>
                </select>
                <p class="text-xs text-gray-500 mt-1">
                    <b><?php echo htmlspecialchars($version_name_cloud); ?></b>：续费云端服务 |
                    <b><?php echo htmlspecialchars($version_name_dg); ?></b>：续费代挂服务 |
                    <b><?php echo htmlspecialchars($version_name_qzone); ?></b>：续费QQ空间秒赞服务 |
                    <b><?php echo htmlspecialchars($version_name_cloud_all); ?></b>：云端+秒赞 |
                    <b><?php echo htmlspecialchars($version_name_dg_all); ?></b>：代挂+秒赞 |
                    <b><?php echo htmlspecialchars($version_name_tri_all); ?></b>：云端+代挂+秒赞
                </p>
            </div>

            <div id="goods-type-container">
                <label class="block text-sm font-medium text-gray-700 mb-1">接口分类</label>
                <select name="type" id="goods-type" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500" onchange="checkTypeAll()">
                    <?php foreach ($classes_cloud as $cls): ?>
                    <option value="<?php echo $cls['id']; ?>"><?php echo htmlspecialchars($cls['name']); ?></option>
                    <?php endforeach; ?>
                    <option value="9999">全部接口</option>
                </select>
                <p id="type-tip" class="hidden text-xs text-orange-500 mt-1">全部接口：用户购买后可在所有接口上登录</p>
            </div>
            <div id="goods-type-tri-container" class="hidden">
                <label class="block text-sm font-medium text-gray-700 mb-1">接口分类</label>
                <div class="grid grid-cols-2 gap-3">
                    <div>
                        <label class="block text-xs text-gray-500 mb-1"><?php echo htmlspecialchars($version_name_cloud); ?></label>
                        <select name="type_cloud" id="goods-type-cloud" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"></select>
                    </div>
                    <div>
                        <label class="block text-xs text-gray-500 mb-1"><?php echo htmlspecialchars($version_name_dg); ?></label>
                        <select name="type_dg" id="goods-type-dg" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"></select>
                    </div>
                </div>
                <p class="text-xs text-gray-500 mt-1">三版通用：将同时对云端分类与代挂分类续费，并叠加秒赞时长</p>
            </div>
            
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">时长数值</label>
                    <input type="number" name="num" id="goods-num" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" value="1" min="1" required>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">时长单位</label>
                    <select name="time_type" id="goods-time-type" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                        <option value="0">月</option>
                        <option value="1">天</option>
                        <option value="2">小时</option>
                        <option value="3">年</option>
                    </select>
                </div>
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">价格类型</label>
                <select name="is_fixed_price" id="is-fixed-price" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500" onchange="toggleFixedPrice()">
                    <option value="0">默认等级价格（按折扣计算）</option>
                    <option value="1">固定等级价格（每个等级单独定价）</option>
                </select>
                <p id="price-tip" class="text-xs text-gray-500 mt-1">默认等级价格：用户实际支付 = 基础价格 x 等级折扣</p>
            </div>
            
            <div id="fixed-prices-container" class="hidden">
                <label class="block text-sm font-medium text-gray-700 mb-2">各等级价格（元）</label>
                <div id="vip-prices-list" class="space-y-2">
                </div>
            </div>
            
            <div id="base-price-container">
                <label class="block text-sm font-medium text-gray-700 mb-1">基础价格 (元)</label>
                <input type="number" name="price" id="goods-price" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" step="0.01" placeholder="商品原价" required>
                <p class="text-xs text-gray-500 mt-1">用户实际支付 = 基础价格 x 等级折扣</p>
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">商品描述</label>
                <textarea name="desc" id="goods-desc" rows="2" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="可选"></textarea>
            </div>

            <div class="border-t border-gray-200 pt-4 mt-4">
                <div class="flex items-center justify-between mb-3">
                    <label class="text-sm font-medium text-gray-700">限购一次</label>
                    <label class="relative inline-flex items-center cursor-pointer">
                        <input type="hidden" name="limit_once" value="0">
                        <input type="checkbox" name="limit_once" value="1" id="limit-once" class="sr-only peer">
                        <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                    </label>
                </div>
            </div>

            <!-- 活动设置 -->
            <div class="border-t border-gray-200 pt-4 mt-4">
                <div class="flex items-center justify-between mb-3">
                    <label class="text-sm font-medium text-gray-700">开启活动</label>
                    <label class="relative inline-flex items-center cursor-pointer">
                        <input type="checkbox" name="activity_enabled" id="activity-enabled" class="sr-only peer" onchange="toggleActivityFields()">
                        <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                    </label>
                </div>
                <div id="activity-fields" class="hidden space-y-3">
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">活动开始时间</label>
                            <input type="datetime-local" name="activity_start" id="activity-start" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">活动结束时间</label>
                            <input type="datetime-local" name="activity_end" id="activity-end" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm">
                        </div>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">活动折扣 (%)</label>
                        <div class="flex items-center gap-2">
                            <input type="number" name="activity_discount" id="activity-discount" class="w-24 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" min="1" max="100" value="100" placeholder="1-100">
                            <span class="text-sm text-gray-500">%（如8折输入80）</span>
                        </div>
                        <p class="text-xs text-gray-500 mt-1">活动期间价格 = 原价 × 折扣%</p>
                    </div>
                </div>
            </div>

            <div class="flex justify-end gap-3 pt-4">
                <button type="button" onclick="closeModal()" class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium rounded-lg transition">取消</button>
                <button type="submit" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition">保存</button>
            </div>
        </form>
    </div>
</div>

<!-- 确认删除模态框 -->
<div id="confirm-modal" class="fixed inset-0 bg-black/50 hidden items-center justify-center z-50 p-4">
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-md">
        <div class="p-4 border-b border-gray-200 flex items-center justify-between">
            <h3 class="text-base md:text-lg font-semibold">确认删除</h3>
            <button onclick="closeConfirmModal()" class="text-gray-400 hover:text-gray-600">
                <i class="fas fa-times text-xl"></i>
            </button>
        </div>
        <div class="p-4 md:p-6">
            <p class="text-gray-700 mb-4">确定要删除此商品吗？</p>
        </div>
        <div class="flex justify-end gap-3 p-4 border-t border-gray-200">
            <button onclick="closeConfirmModal()" class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium rounded-lg transition">取消</button>
            <button id="confirm-delete-btn" onclick="confirmDelete()" class="px-4 py-2 bg-red-600 hover:bg-red-700 text-white font-medium rounded-lg transition">确定</button>
        </div>
    </div>
</div>

<!-- 同步活动模态框 -->
<div id="sync-modal" class="fixed inset-0 bg-black/50 z-[60] p-4" style="display:none;">
    <div class="flex items-center justify-center w-full h-full">
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-lg max-h-[90vh] overflow-y-auto">
        <div class="p-4 border-b border-gray-200 flex items-center justify-between sticky top-0 bg-white">
            <h3 class="text-base md:text-lg font-semibold">同步活动到同分类商品</h3>
            <button onclick="closeSyncModal()" class="text-gray-400 hover:text-gray-600">
                <i class="fas fa-times text-xl"></i>
            </button>
        </div>
        <form onsubmit="syncActivity(this);return false;" class="p-4 md:p-6 space-y-4">
            <div class="bg-blue-50 border border-blue-200 rounded-lg p-3 mb-4">
                <p class="text-sm text-blue-700"><i class="fas fa-info-circle mr-1"></i>将活动设置同步到指定接口分类下的所有商品</p>
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">选择接口分类</label>
                <select name="sync_cid" id="sync-cid" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500" required>
                    <option value="">请选择分类</option>
                    <?php foreach ($classes as $cls): ?>
                    <option value="<?php echo $cls['id']; ?>"><?php echo htmlspecialchars($cls['name']); ?></option>
                    <?php endforeach; ?>
                    <option value="9999">全部接口</option>
                    <option value="qzone">秒赞版商品</option>
                    <option value="cloud">云端版商品</option>
                    <option value="all">所有商品</option>
                </select>
            </div>

            <div class="border-t border-gray-200 pt-4">
                <div class="flex items-center justify-between mb-3">
                    <label class="text-sm font-medium text-gray-700">开启活动</label>
                    <label class="relative inline-flex items-center cursor-pointer">
                        <input type="checkbox" name="sync_activity_enabled" id="sync-activity-enabled" class="sr-only peer" onchange="toggleSyncActivityFields()">
                        <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                    </label>
                </div>
                <div id="sync-activity-fields" class="hidden space-y-3">
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">活动开始时间</label>
                            <input type="datetime-local" name="sync_activity_start" id="sync-activity-start" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">活动结束时间</label>
                            <input type="datetime-local" name="sync_activity_end" id="sync-activity-end" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm">
                        </div>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">活动折扣 (%)</label>
                        <div class="flex items-center gap-2">
                            <input type="number" name="sync_activity_discount" id="sync-activity-discount" class="w-24 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" min="1" max="100" value="100" placeholder="1-100">
                            <span class="text-sm text-gray-500">% (如8折输入80)</span>
                        </div>
                    </div>
                </div>
            </div>

            <div class="flex justify-end gap-3 pt-4">
                <button type="button" onclick="closeSyncModal()" class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium rounded-lg transition">取消</button>
                <button type="submit" class="px-4 py-2 bg-orange-600 hover:bg-orange-700 text-white font-medium rounded-lg transition">同步</button>
            </div>
        </form>
    </div>
    </div>
</div>

<?php include 'foot.php'; ?>

<script>
var currentPage = 1;
var pageSize = 30;
var totalPages = 1;
var classCloud = <?php echo json_encode($classes_cloud, JSON_UNESCAPED_UNICODE); ?>;
var classDg = <?php echo json_encode($classes_dg, JSON_UNESCAPED_UNICODE); ?>;
var vipData = <?php echo json_encode(isset($vip_list) ? $vip_list : []); ?>;
var goodsBiz = <?php echo json_encode($biz, JSON_UNESCAPED_UNICODE); ?>;

var timeTypeMap = {0: '月', 1: '天', 2: '小时', 3: '年'};

function escapeHtml(str) {
    return String(str)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}

$(document).ready(function() {
    loadGoodsList();
    loadVipList();
});

function loadVipList() {
    showLoading();
    $.ajax({
        type: 'GET',
        url: '../api.php?act=get_vip_list',
        dataType: 'json',
        success: function(data) {
            hideLoading();
            if (data.code == 1 && data.data) {
                vipData = data.data;
            }
        },
        error: function() {
            hideLoading();
        }
    });
}

function loadGoodsList() {
    showLoading();
    $.ajax({
        type: 'GET',
        url: 'ajax_goods.php?act=list',
        data: {page: currentPage, limit: pageSize, offset: (currentPage - 1) * pageSize, biz: goodsBiz},
        dataType: 'json',
        success: function(data) {
            hideLoading();
            renderGoodsList(data.rows || []);
            $('#total').text(data.total || 0);
            totalPages = Math.ceil((data.total || 0) / pageSize) || 1;
            $('#current-page').text(currentPage);
        },
        error: function() {
            hideLoading();
            showMsg('加载失败', 2);
        }
    });
}

function renderGoodsList(list) {
    var html = '';
    var versionMap = {
        'cloud': <?php echo json_encode($version_name_cloud); ?>,
        'dg': <?php echo json_encode($version_name_dg); ?>,
        'qzone': <?php echo json_encode($version_name_qzone); ?>,
        'cloud_all': <?php echo json_encode($version_name_cloud_all); ?>,
        'dg_all': <?php echo json_encode($version_name_dg_all); ?>,
        'tri_all': <?php echo json_encode($version_name_tri_all); ?>,
        'all': <?php echo json_encode($version_name_cloud_all); ?>
    };
    if (list.length === 0) {
        html = '<tr><td colspan="10" class="px-4 py-8 text-center text-gray-500">暂无商品</td></tr>';
    } else {
        $.each(list, function(i, v) {
            var statusHtml = v.status == 1 
                ? '<span class="px-2 py-1 text-xs bg-green-100 text-green-700 rounded cursor-pointer" onclick="toggleStatus(' + v.id + ', 0)">上架中</span>'
                : '<span class="px-2 py-1 text-xs bg-gray-100 text-gray-500 rounded cursor-pointer" onclick="toggleStatus(' + v.id + ', 1)">已下架</span>';
            
            var timeText = v.num + (timeTypeMap[v.time_type] || '月');
            
            var displayPrice = v.price;
            if (v.is_fixed_price == 1 && v.fixed_prices) {
                try {
                    var fixedPrices = JSON.parse(v.fixed_prices);
                    var firstVip = Object.keys(fixedPrices)[0];
                    if (firstVip && fixedPrices[firstVip]) {
                        displayPrice = fixedPrices[firstVip];
                    }
                } catch(e) {}
            }
            var versionText = versionMap[v.version] || versionMap['cloud'];
            var versionClass = v.version == 'qzone'
                ? 'bg-orange-100 text-orange-700'
                : ((v.version == 'all' || v.version == 'cloud_all' || v.version == 'dg_all' || v.version == 'tri_all') ? 'bg-purple-100 text-purple-700' : 'bg-blue-100 text-blue-700');
            
            html += `<tr class="hover:bg-gray-50">
                <td class="px-4 py-3 text-sm text-gray-500 whitespace-nowrap">${v.sort || v.id}</td>
                <td class="px-4 py-3 whitespace-nowrap">
                    <span class="font-medium text-gray-800">${v.name}</span>
                </td>
                <td class="px-4 py-3 whitespace-nowrap">
                    <span class="px-2 py-1 text-xs ${versionClass} rounded">${versionText}</span>
                </td>
                <td class="px-4 py-3 whitespace-nowrap">
                    <span class="text-lg font-semibold text-blue-600">${displayPrice}</span>
                    <span class="text-sm text-gray-400">元</span>
                </td>
                <td class="px-4 py-3 text-sm text-gray-600 whitespace-nowrap">${timeText}</td>
                <td class="px-4 py-3 whitespace-nowrap">
                    <span class="px-2 py-1 text-xs bg-purple-100 text-purple-700 rounded">${v.names || '未分类'}</span>
                </td>
                <td class="px-4 py-3 whitespace-nowrap">${getActivityHtml(v)}</td>
                <td class="px-4 py-3 whitespace-nowrap">${getDiscountHtml(v)}</td>
                <td class="px-4 py-3 whitespace-nowrap">${statusHtml}</td>
                <td class="px-4 py-3 whitespace-nowrap">
                    <div class="flex items-center gap-2">
                        <button onclick='editGoods(${JSON.stringify(v)})' class="px-3 py-1 text-xs bg-blue-600 text-white rounded hover:bg-blue-700 whitespace-nowrap">编辑</button>
                        <button onclick="delGoods(${v.id})" class="px-3 py-1 text-xs bg-red-600 text-white rounded hover:bg-red-700 whitespace-nowrap">删除</button>
                    </div>
                </td>
            </tr>`;
        });
    }
    $('#goods-list').html(html);
}

function prevPage() {
    if (currentPage > 1) {
        currentPage--;
        loadGoodsList();
    }
}

function nextPage() {
    if (currentPage < totalPages) {
        currentPage++;
        loadGoodsList();
    }
}

function openAddModal() {
    $('#modal-title').text('添加商品');
    $('#goods-id').val(0);
    $('#goods-act').val('add');
    $('#goods-name').val('');
    var defaultVersion = goodsBiz === 'dg' ? 'dg' : (goodsBiz === 'qzone' ? 'qzone' : 'cloud');
    $('#goods-version').val(defaultVersion);
    $('#goods-type').val($('#goods-type option:first').val());
    $('#goods-num').val(1);
    $('#goods-time-type').val(0);
    $('#goods-price').val('');
    $('#goods-desc').val('');
    $('#is-fixed-price').val('0');
    $('#fixed-prices-container').addClass('hidden');
    $('#base-price-container').removeClass('hidden');
    $('#price-tip').text('默认等级价格：用户实际支付 = 基础价格 x 等级折扣');
    renderVipPrices({});
    checkTypeAll();
    toggleTypeByVersion();
    // 重置活动字段
    $('#activity-enabled').prop('checked', false);
    $('#activity-fields').addClass('hidden');
    $('#activity-start').val('');
    $('#activity-end').val('');
    $('#activity-discount').val(100);
    $('#limit-once').prop('checked', false);
    $('#goods-modal').removeClass('hidden').addClass('flex');
}

function editGoods(row) {
    $('#modal-title').text('编辑商品');
    $('#goods-id').val(row.id);
    $('#goods-act').val('edit');
    $('#goods-name').val(row.name);
    var v = row.version || 'cloud';
    if (v === 'all') v = 'cloud_all';
    $('#goods-version').val(v);
    $('#goods-type').val(row.type);
    $('#goods-type-cloud').data('selected', row.type_cloud || '');
    $('#goods-type-dg').data('selected', row.type_dg || '');
    $('#goods-num').val(row.num);
    $('#goods-time-type').val(row.time_type);
    $('#goods-price').val(row.price);
    $('#goods-desc').val(row.desc || '');
    $('#is-fixed-price').val(row.is_fixed_price || 0);
    
    var fixedPrices = {};
    if (row.fixed_prices) {
        try {
            fixedPrices = JSON.parse(row.fixed_prices);
        } catch(e) {
            fixedPrices = {};
        }
    }

    // 填充活动字段
    var activityEnabled = row.activity_enabled == 1;
    $('#activity-enabled').prop('checked', activityEnabled);
    if (activityEnabled) {
        $('#activity-fields').removeClass('hidden');
    } else {
        $('#activity-fields').addClass('hidden');
    }
    $('#activity-start').val(formatDateTimeLocal(row.activity_start));
    $('#activity-end').val(formatDateTimeLocal(row.activity_end));
    $('#activity-discount').val(row.activity_discount || 100);
    $('#limit-once').prop('checked', row.limit_once == 1);

    toggleFixedPrice();
    renderVipPrices(fixedPrices);
    checkTypeAll();
    toggleTypeByVersion();
    $('#goods-modal').removeClass('hidden').addClass('flex');
}

function closeModal() {
    $('#goods-modal').removeClass('flex').addClass('hidden');
}

function checkTypeAll() {
    if ($('#goods-type').val() == '9999') {
        $('#type-tip').removeClass('hidden');
    } else {
        $('#type-tip').addClass('hidden');
    }
}

function toggleTypeByVersion() {
    var version = $('#goods-version').val();
    if (version == 'qzone') {
        $('#goods-type-container').hide();
        $('#goods-type-tri-container').hide();
        return;
    }
    if (version == 'tri_all') {
        $('#goods-type-container').hide();
        $('#goods-type-tri-container').show();
        var htmlCloud = '';
        for (var i = 0; i < classCloud.length; i++) {
            htmlCloud += '<option value="' + classCloud[i].id + '">' + escapeHtml(classCloud[i].name) + '</option>';
        }
        htmlCloud += '<option value="9999">全部接口</option>';
        var htmlDg = '';
        for (var j = 0; j < classDg.length; j++) {
            htmlDg += '<option value="' + classDg[j].id + '">' + escapeHtml(classDg[j].name) + '</option>';
        }
        htmlDg += '<option value="9999">全部接口</option>';
        $('#goods-type-cloud').html(htmlCloud);
        $('#goods-type-dg').html(htmlDg);
        var cloudSelected = $('#goods-type-cloud').data('selected');
        if (cloudSelected && $('#goods-type-cloud option[value="' + cloudSelected + '"]').length) {
            $('#goods-type-cloud').val(cloudSelected);
        }
        var dgSelected = $('#goods-type-dg').data('selected');
        if (dgSelected && $('#goods-type-dg option[value="' + dgSelected + '"]').length) {
            $('#goods-type-dg').val(dgSelected);
        }
        var selectedCloud = $('#goods-type-cloud').val();
        if (selectedCloud) $('#goods-type').val(selectedCloud);
        $('#goods-type-cloud').off('change').on('change', function() {
            $('#goods-type').val($(this).val());
        });
        return;
    }
    $('#goods-type-tri-container').hide();
    $('#goods-type-container').show();

    var data = (version == 'dg' || version == 'dg_all') ? classDg : classCloud;
    var selected = $('#goods-type').val();
    var html = '';

    for (var i = 0; i < data.length; i++) {
        html += '<option value="' + data[i].id + '">' + escapeHtml(data[i].name) + '</option>';
    }
    html += '<option value="9999">全部接口</option>';

    $('#goods-type').html(html);
    if (selected && $('#goods-type option[value="' + selected + '"]').length) {
        $('#goods-type').val(selected);
    } else {
        $('#goods-type').val($('#goods-type option:first').val());
    }
    checkTypeAll();
}

function saveGoods(form) {
    showLoading();
    
    var isFixedPrice = $('#is-fixed-price').val() == '1';
    var fixedPrices = {};
    
    if (isFixedPrice) {
        var vipPrices = getVipPrices();
        var hasPrice = false;
        for (var vip in vipPrices) {
            if (vipPrices[vip] && vipPrices[vip] > 0) {
                fixedPrices[vip] = vipPrices[vip];
                hasPrice = true;
            }
        }
        
        if (!hasPrice) {
            hideLoading();
            showMsg('请至少设置一个等级的价格', 2);
            return;
        }
        
        $('input[name="fixed_prices"]').remove();
        $(form).append('<input type="hidden" name="fixed_prices" value=\'' + JSON.stringify(fixedPrices) + '\'>');
    }
    
    $.ajax({
        type: 'POST',
        url: 'ajax_goods.php?act=add',
        data: $(form).serialize(),
        dataType: 'json',
        success: function(data) {
            hideLoading();
            showMsg(data.msg, data.code == 1 ? 1 : 2);
            if (data.code == 1) {
                closeModal();
                loadGoodsList();
            }
        },
        error: function() {
            hideLoading();
            showMsg('服务器错误', 2);
        }
    });
}

function toggleStatus(id, status) {
    showLoading();
    $.ajax({
        type: 'POST',
        url: 'ajax_goods.php?act=edit',
        data: {type: 'zt', id: id, zt: status},
        dataType: 'json',
        success: function(data) {
            hideLoading();
            showMsg(data.msg, data.code == 1 ? 1 : 2);
            if (data.code == 1) {
                loadGoodsList();
            }
        }
    });
}

var currentDeleteId = 0;

function delGoods(id) {
    currentDeleteId = id;
    $('#confirm-modal').removeClass('hidden').addClass('flex');
}

function closeConfirmModal() {
    $('#confirm-modal').removeClass('flex').addClass('hidden');
    currentDeleteId = 0;
}

function confirmDelete() {
    if (currentDeleteId === 0) return;
    
    showLoading();
    $.ajax({
        type: 'POST',
        url: 'ajax_goods.php?act=edit',
        data: {type: 'del', id: currentDeleteId},
        dataType: 'json',
        success: function(data) {
            hideLoading();
            showMsg(data.msg, data.code == 1 ? 1 : 2);
            if (data.code == 1) {
                closeConfirmModal();
                loadGoodsList();
            }
        }
    });
}

function toggleFixedPrice() {
    var isFixed = $('#is-fixed-price').val() == '1';
    
    if (isFixed) {
        $('#fixed-prices-container').removeClass('hidden');
        $('#base-price-container').addClass('hidden');
        $('#price-tip').text('固定等级价格：每个等级单独设置价格，不使用折扣计算');
        $('#goods-price').removeAttr('required');
    } else {
        $('#fixed-prices-container').addClass('hidden');
        $('#base-price-container').removeClass('hidden');
        $('#price-tip').text('默认等级价格：用户实际支付 = 基础价格 x 等级折扣');
        $('#goods-price').attr('required', 'required');
    }
}

function renderVipPrices(fixedPrices) {
    var html = '';
    
    for (var vip in vipData) {
        var vipInfo = vipData[vip];
        var price = fixedPrices[vip] || '';
        
        html += `<div class="flex items-center gap-3">
            <div class="w-32 text-sm text-gray-600">
                <span class="font-medium">${vipInfo.name}</span>
            </div>
            <input type="number" 
                   name="vip_price_${vip}" 
                   id="vip_price_${vip}" 
                   class="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" 
                   step="0.01" 
                   min="0" 
                   placeholder="输入价格"
                   value="${price}">
            <span class="text-sm text-gray-500">元</span>
        </div>`;
    }
    
    $('#vip-prices-list').html(html);
}

function getVipPrices() {
    var prices = {};
    
    for (var vip in vipData) {
        var priceInput = $('#vip_price_' + vip);
        if (priceInput.length > 0) {
            var price = parseFloat(priceInput.val());
            if (!isNaN(price) && price > 0) {
                prices[vip] = price;
            }
        }
    }
    
    return prices;
}

// 活动相关函数
function toggleActivityFields() {
    var isChecked = $('#activity-enabled').is(':checked');
    if (isChecked) {
        $('#activity-fields').removeClass('hidden');
    } else {
        $('#activity-fields').addClass('hidden');
    }
}

function formatDateTimeLocal(dateStr) {
    if (!dateStr || dateStr == '0000-00-00 00:00:00') return '';
    var d = new Date(dateStr);
    if (isNaN(d.getTime())) return '';
    var year = d.getFullYear();
    var month = String(d.getMonth() + 1).padStart(2, '0');
    var day = String(d.getDate()).padStart(2, '0');
    var hours = String(d.getHours()).padStart(2, '0');
    var minutes = String(d.getMinutes()).padStart(2, '0');
    return year + '-' + month + '-' + day + 'T' + hours + ':' + minutes;
}

function getActivityHtml(v) {
    var activityEnabled = v.activity_enabled == 1;
    var now = new Date();
    var activityStart = v.activity_start ? new Date(v.activity_start) : null;
    var activityEnd = v.activity_end ? new Date(v.activity_end) : null;

    // 检查活动是否在有效期内
    var isActive = false;
    if (activityEnabled && activityStart && activityEnd) {
        if (now >= activityStart && now <= activityEnd) {
            isActive = true;
        }
    }

    if (activityEnabled) {
        if (isActive) {
            return '<span class="px-2 py-1 text-xs bg-green-100 text-green-700 rounded cursor-pointer" onclick="toggleActivity(' + v.id + ', 0)" title="活动进行中">开启中</span>';
        } else if (activityEnd && now > activityEnd) {
            return '<span class="px-2 py-1 text-xs bg-gray-100 text-gray-500 rounded" title="活动已结束">已结束</span>';
        } else if (activityStart && now < activityStart) {
            return '<span class="px-2 py-1 text-xs bg-yellow-100 text-yellow-700 rounded cursor-pointer" onclick="toggleActivity(' + v.id + ', 0)" title="活动未开始">未开始</span>';
        }
        return '<span class="px-2 py-1 text-xs bg-green-100 text-green-700 rounded cursor-pointer" onclick="toggleActivity(' + v.id + ', 0)">开启中</span>';
    } else {
        return '<span class="px-2 py-1 text-xs bg-gray-100 text-gray-500 rounded cursor-pointer" onclick="toggleActivity(' + v.id + ', 1)">未开启</span>';
    }
}

function getDiscountHtml(v) {
    var discount = v.activity_discount || 100;
    if (discount == 100 || discount == 0) {
        return '<span class="text-gray-400">-</span>';
    }
    return '<span class="px-2 py-1 text-xs bg-orange-100 text-orange-700 rounded cursor-pointer" onclick="editDiscount(' + v.id + ', ' + discount + ')" title="点击编辑">' + discount + '%</span>';
}

function toggleActivity(id, enable) {
    showLoading();
    $.ajax({
        type: 'POST',
        url: 'ajax_goods.php?act=edit',
        data: {type: 'activity_toggle', id: id, activity_enabled: enable},
        dataType: 'json',
        success: function(data) {
            hideLoading();
            showMsg(data.msg, data.code == 1 ? 1 : 2);
            if (data.code == 1) {
                loadGoodsList();
            }
        }
    });
}

function editDiscount(id, currentDiscount) {
    var newDiscount = prompt('请输入活动折扣百分比(1-100):', currentDiscount);
    if (newDiscount === null) return;
    newDiscount = parseInt(newDiscount);
    if (isNaN(newDiscount) || newDiscount < 1 || newDiscount > 100) {
        showMsg('请输入1-100之间的数字', 2);
        return;
    }
    showLoading();
    $.ajax({
        type: 'POST',
        url: 'ajax_goods.php?act=edit',
        data: {type: 'activity_discount', id: id, activity_discount: newDiscount},
        dataType: 'json',
        success: function(data) {
            hideLoading();
            showMsg(data.msg, data.code == 1 ? 1 : 2);
            if (data.code == 1) {
                loadGoodsList();
            }
        }
    });
}

// 同步活动相关函数
function openSyncModal() {
    $('#sync-modal').show();
    $('#sync-cid').val('');
    $('#sync-activity-enabled').prop('checked', false);
    $('#sync-activity-fields').addClass('hidden');
    $('#sync-activity-start').val('');
    $('#sync-activity-end').val('');
    $('#sync-activity-discount').val(100);
    console.log('openSyncModal called');
}

function closeSyncModal() {
    $('#sync-modal').hide();
}

function toggleSyncActivityFields() {
    var isChecked = $('#sync-activity-enabled').is(':checked');
    if (isChecked) {
        $('#sync-activity-fields').removeClass('hidden');
    } else {
        $('#sync-activity-fields').addClass('hidden');
    }
}

function syncActivity(form) {
    var cid = $('#sync-cid').val();
    if (!cid) {
        showMsg('请选择接口分类', 2);
        return;
    }

    var activityEnabled = $('#sync-activity-enabled').is(':checked') ? 1 : 0;
    var activityStart = $('#sync-activity-start').val();
    var activityEnd = $('#sync-activity-end').val();
    var activityDiscount = $('#sync-activity-discount').val();

    if (activityEnabled == 1) {
        if (!activityStart || !activityEnd) {
            showMsg('请设置活动开始和结束时间', 2);
            return;
        }
        if (activityDiscount < 1 || activityDiscount > 100) {
            showMsg('活动折扣必须在1-100之间', 2);
            return;
        }
    }

    showLoading();
    $.ajax({
        type: 'POST',
        url: 'ajax_goods.php?act=sync_activity',
        data: {
            cid: cid,
            activity_enabled: activityEnabled,
            activity_start: activityStart,
            activity_end: activityEnd,
            activity_discount: activityDiscount
        },
        dataType: 'json',
        success: function(data) {
            hideLoading();
            showMsg(data.msg, data.code == 1 ? 1 : 2);
            if (data.code == 1) {
                closeSyncModal();
                loadGoodsList();
            }
        },
        error: function() {
            hideLoading();
            showMsg('服务器错误', 2);
        }
    });
}
</script>
