<?php
$title='卡密管理';
include __DIR__ . '/head.php';
?>

<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">
                <h2 class="text-base md:text-lg font-semibold text-gray-800">卡密管理</h2>
                <div class="flex flex-wrap items-center gap-2 w-full md:w-auto">
                    <form onsubmit="searchOrder();return false;" class="flex flex-wrap items-center gap-2 w-full md:w-auto">
                        <input type="text" class="flex-1 min-w-[120px] px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm" name="kw" placeholder="输入卡密信息">
                        <select class="px-3 py-2 border border-gray-300 rounded-lg text-sm" name="type">
                            <option value="-1">全部</option>
                            <option value="-2">全部除自己</option>
                            <option value="0">未使用</option>
                            <option value="1">已使用</option>
                            <option value="2" selected="selected">自己的卡密</option>
                            <option value="3">自己_已使用</option>
                            <option value="4">自己_未使用</option>
                            <option value="5">常规卡</option>
                            <option value="6">特殊卡</option>
                        </select>
                        <button type="submit" class="px-3 py-2 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition text-sm whitespace-nowrap">
                            <i class="fas fa-search mr-1"></i>搜索
                        </button>
                    </form>
                    <button type="button" class="px-3 py-2 bg-green-600 hover:bg-green-700 text-white font-medium rounded-lg transition text-sm whitespace-nowrap" onclick="openAddModal()">
                        <i class="fas fa-plus mr-1"></i>生成
                    </button>
                    <button type="button" class="px-3 py-2 bg-yellow-600 hover:bg-yellow-700 text-white font-medium rounded-lg transition text-sm whitespace-nowrap" onclick="add_rmb_km()">
                        <i class="fas fa-coins mr-1"></i>余额卡密
                    </button>
                    <button type="button" class="px-3 py-2 bg-red-600 hover:bg-red-700 text-white font-medium rounded-lg transition text-sm whitespace-nowrap" onclick="qk()">
                        <i class="fas fa-trash mr-1"></i>清空
                    </button>
                    <button type="button" class="px-3 py-2 bg-red-600 hover:bg-red-700 text-white font-medium rounded-lg transition text-sm whitespace-nowrap" onclick="do_qk(99)">
                        <i class="fas fa-trash-alt mr-1"></i>清空已使用
                    </button>
                    <button type="button" class="px-3 py-2 bg-gray-600 hover:bg-gray-700 text-white font-medium rounded-lg transition text-sm whitespace-nowrap" onclick="clearSpecialKami()">
                        <i class="fas fa-broom mr-1"></i>清空特殊卡
                    </button>
                </div>
            </div>
        </div>
        
        <div class="p-3 md:p-6">
            <?php
            if($conf['kami_open'] != 1) {
                echo '<div class="alert alert-warning mb-4"><i class="fas fa-exclamation-triangle mr-2"></i>卡密功能已关闭，可在【系统设置-网站信息配置】里面开启</div>';
            }
            ?>
            <input type="hidden" id="isgoods" value="">
            <div class="overflow-x-auto">
                <table class="w-full">
                    <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">使用QQ</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="kami-list" class="divide-y divide-gray-200">
                    </tbody>
                </table>
            </div>
            
            <!-- 分页和数量显示 -->
            <div class="px-4 py-3 border-t border-gray-200 flex flex-col sm:flex-row sm:items-center justify-between gap-3 text-sm">
                <div class="text-gray-500">
                    共 <span id="totalCount">0</span> 条记录
                </div>
                <div class="flex items-center gap-2">
                    <select class="px-2.5 py-1 border border-gray-300 rounded text-xs" name="pageSize" onchange="refreshTable()">
                        <option value="30">30</option>
                        <option value="50">50</option>
                        <option value="100">100</option>
                        <option value="200">200</option>
                        <option value="500">500</option>
                    </select>
                    <button onclick="prevPage()" id="prevPage" disabled 
                            class="px-2.5 py-1 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded text-xs transition-colors">
                        <i class="fas fa-chevron-left"></i>
                    </button>
                    <span class="text-gray-500">第 <span id="currentPage">1</span> / <span id="totalPages">1</span> 页</span>
                    <button onclick="nextPage()" id="nextPage" disabled 
                            class="px-2.5 py-1 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded text-xs transition-colors">
                        <i class="fas fa-chevron-right"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="show" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">卡密生成</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="km_form" onsubmit="return false;">
                    <?php
                    $version_name_cloud = $conf['version_name_cloud'] ?? '云端版';
                    $version_name_dg = $conf['version_name_dg'] ?? '代挂版';
                    $version_name_qzone = $conf['version_name_qzone'] ?? '秒赞版';
                    $version_name_cloud_all = $conf['version_name_cloud_all'] ?? (preg_replace('/版$/u', '', $version_name_cloud) . '·秒赞');
                    $version_name_dg_all = $conf['version_name_dg_all'] ?? (preg_replace('/版$/u', '', $version_name_dg) . '·秒赞');
                    $version_name_tri_all = $conf['version_name_tri_all'] ?? '三版通用';
                    $has_cloud_all_goods = $DB->getColumn("SELECT COUNT(*) FROM pre_goods WHERE status='1' AND (version='cloud_all' OR version='all')");
                    $has_dg_all_goods = $DB->getColumn("SELECT COUNT(*) FROM pre_goods WHERE status='1' AND version='dg_all'");
                    $has_tri_all_goods = $DB->getColumn("SELECT COUNT(*) FROM pre_goods WHERE status='1' AND version='tri_all'");
                    $has_dg_goods = $DB->getColumn("SELECT COUNT(*) FROM pre_goods WHERE status='1' AND version='dg'");
                    $qzone_enabled = (($conf['qzone_open'] ?? ($conf['qzone_enabled'] ?? '0')) == '1');
                    $cloud_enabled = (($conf['cloud_enabled'] ?? '1') == '1');
                    $dg_enabled = (($conf['dg_open'] ?? '0') == '1');
                    $show_cloud_all = $has_cloud_all_goods > 0 && $qzone_enabled && $cloud_enabled;
                    $show_dg_all = $has_dg_all_goods > 0 && $qzone_enabled && $dg_enabled;
                    $show_tri_all = $has_tri_all_goods > 0 && $qzone_enabled && $cloud_enabled && $dg_enabled;
                    $show_dg = $dg_enabled && $has_dg_goods > 0;
                    $show_cloud = $cloud_enabled;
                    $show_qzone = $qzone_enabled;
                    $default_version = $show_cloud ? 'cloud' : ($show_dg ? 'dg' : ($show_qzone ? 'qzone' : ($show_cloud_all ? 'cloud_all' : ($show_dg_all ? 'dg_all' : ($show_tri_all ? 'tri_all' : 'cloud')))));
                    ?>
                    <div class="input-group mb-3">
                        <div class="input-group-text">产品版本</div>
                        <select class="form-select" name="version" id="km-version">
                            <?php if($show_cloud): ?>
                            <option value="cloud" <?php echo $default_version==='cloud'?'selected':''; ?>><?php echo htmlspecialchars($version_name_cloud); ?></option>
                            <?php endif; ?>
                            <?php if($show_dg): ?>
                            <option value="dg" <?php echo $default_version==='dg'?'selected':''; ?>><?php echo htmlspecialchars($version_name_dg); ?></option>
                            <?php endif; ?>
                            <?php if($show_qzone): ?>
                            <option value="qzone" <?php echo $default_version==='qzone'?'selected':''; ?>><?php echo htmlspecialchars($version_name_qzone); ?></option>
                            <?php endif; ?>
                            <?php if($show_cloud_all): ?>
                            <option value="cloud_all" <?php echo $default_version==='cloud_all'?'selected':''; ?>><?php echo htmlspecialchars($version_name_cloud_all); ?></option>
                            <?php endif; ?>
                            <?php if($show_dg_all): ?>
                            <option value="dg_all" <?php echo $default_version==='dg_all'?'selected':''; ?>><?php echo htmlspecialchars($version_name_dg_all); ?></option>
                            <?php endif; ?>
                            <?php if($show_tri_all): ?>
                            <option value="tri_all" <?php echo $default_version==='tri_all'?'selected':''; ?>><?php echo htmlspecialchars($version_name_tri_all); ?></option>
                            <?php endif; ?>
                        </select>
                    </div>
                    <div class="input-group mb-3">
                        <div class="input-group-text">卡种类型</div>
                        <select class="form-select" name="card_type" id="km-card-type">
                            <option value="0">常规卡</option>
                            <option value="1">特殊卡</option>
                        </select>
                    </div>
                    <small class="form-text text-muted d-block mb-3 ps-1">常规卡：一卡一次，同QQ可多次激活同类商品<br>特殊卡：同QQ只能激活一次同一商品的卡密</small>
                    <div class="input-group mb-3" id="admin-kami-cid-row">
                        <div class="input-group-text">商品分类</div>
                        <select class="form-select" name="cid" id="cid"></select>
                    </div>
                    <div class="input-group mb-3">
                        <div class="input-group-text">商品列表</div>
                        <select class="form-select" name="goods" id="goods"></select>
                    </div>
                    <div class="input-group mb-3" style="display: none;" id="_time">
                        <div class="input-group-text">卡密时长</div>
                        <input type="number" class="form-control" name="time_num" placeholder="请输入数值">
                        <select class="input-group-text" name="time">
                            <option value="0">月</option>
                            <option value="1">天</option>
                            <option value="2">时</option>
                            <option value="3">年</option>
                        </select>
                    </div>
                    <div class="input-group mb-3">
                        <div class="input-group-text">生成数量</div>
                        <input type="number" class="form-control" name="num" value="1" min="1" max="9999">
                    </div>
                    <div class="input-group mb-3">
                        <div class="input-group-text">卡密前缀</div>
                        <input type="text" class="form-control" name="kmqz" placeholder="可留空、仅支持数英">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-success" id="btn-km-form" onclick="add_kami('km_form')">确定</button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="show_rmb" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">生成余额卡密</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="km_form_rmb" onsubmit="return false;">
                    <div class="input-group mb-3">
                        <span class="input-group-text">卡密金额</span>
                        <input type="text" class="form-control" name="rmb" placeholder="金额">
                    </div>
                    <div class="input-group mb-3">
                        <span class="input-group-text">生成数量</span>
                        <input type="number" class="form-control" name="num" value="1">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-success" id="btn-km-form-rmb" onclick="add_kami('km_form_rmb')">确定</button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="show_result" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="result_title">生成结果</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <textarea id="txt_km" class="form-control" rows="10" style="font-size: 12px;"></textarea>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-success" onclick="copyKami()">复制全部</button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="show_confirm" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">确认</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p id="confirm_message"></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirm_ok">确定</button>
            </div>
        </div>
    </div>
</div>

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

<script>

var pagesize = 30;
var page = 1;
var totalPages = 1;
var confirmCallback = null;

function refreshTable() {
    pagesize = $('select[name="pageSize"]').val();
    get_kami_list(1);
}

function prevPage() {
    if (page > 1) {
        get_kami_list(page - 1);
    }
}

function nextPage() {
    if (page < totalPages) {
        get_kami_list(page + 1);
    }
}

function copyKami() {
    var text = $('#txt_km').val();
    if (!text) {
        showToast('没有可复制的内容', 'warning');
        return;
    }
    
    if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(text).then(function() {
            showToast('复制成功', 'success');
        }).catch(function(err) {
            showToast('复制失败，请手动复制', 'error');
            console.error('复制失败:', err);
        });
    } else {
        var textarea = document.getElementById('txt_km');
        textarea.select();
        textarea.setSelectionRange(0, 99999);
        
        try {
            var successful = document.execCommand('copy');
            if (successful) {
                showToast('复制成功', 'success');
            } else {
                showToast('复制失败，请手动复制', 'error');
            }
        } catch (err) {
            showToast('复制失败，请手动复制', 'error');
            console.error('复制失败:', err);
        }
        
        window.getSelection().removeAllRanges();
    }
}

$(document).ready(function() {
    $('.modal').on('hidden.bs.modal', function () {
        document.activeElement.blur();
        document.body.focus();
        // 重置弹窗内的按钮状态
        $('#btn-km-form, #btn-km-form-rmb').each(function() {
            var $btn = $(this);
            if ($btn.data('original-text')) {
                $btn.prop('disabled', false).html($btn.data('original-text'));
            }
        });
    });
    
    $('#show_result').on('hidden.bs.modal', function () {
        get_kami_list(1);
    });
    
    $('#confirm_ok').on('click', function() {
        var confirmModalEl = document.getElementById('show_confirm');
        var confirmModal = bootstrap.Modal.getInstance(confirmModalEl);
        if (confirmModal) {
            confirmModal.hide();
        }
        if (confirmCallback) {
            confirmCallback();
            confirmCallback = null;
        }
    });
    
    get_kami_list(1);
});

function showConfirm(message, callback) {
    $('#confirm_message').text(message);
    confirmCallback = callback;
    var confirmModal = new bootstrap.Modal(document.getElementById('show_confirm'));
    confirmModal.show();
}

function get_kami_list(p, query) {
    p = p || 1;
    query = query || '';
    var kw = $('input[name="kw"]').val();
    var type = $('select[name="type"]').val() || '2';
    
    // 显示加载状态
    var loadingHtml = '<div class="loading-overlay" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.8); z-index: 9999; display: flex; justify-content: center; align-items: center;"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">加载中...</span></div></div>';
    $('body').append(loadingHtml);
    
    $.ajax({
        type: 'POST',
        url: 'ajax.php?act=get_kami',
        data: {
            kw: kw,
            type: type,
            pagesize: pagesize,
            page: p
        },
        dataType: 'json',
        success: function(data) {
            // 隐藏加载状态
            $('.loading-overlay').remove();
            
            if (data && data.data) {
                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); ?>
                };
                var cardTypeMap = {'0': '常规卡', '1': '特殊卡'};
                var html = '';
                $.each(data.data, function(index, row) {
                    var statusClass = row.isuse == 1 ? 'bg-red-100 text-red-700' : 'bg-blue-100 text-blue-700';
                    var statusText = row.isuse == 1 ? '已使用' : '未使用';
                    var versionText = versionMap[row.version] || '云端版';
                    var versionClass = row.version == 'qzone' ? 'bg-orange-100 text-orange-700' : ((row.version == 'all' || row.version == 'cloud_all' || row.version == 'dg_all' || row.version == 'tri_all') ? 'bg-purple-100 text-purple-700' : (row.version == 'dg' ? 'bg-emerald-100 text-emerald-700' : 'bg-blue-100 text-blue-700'));
                    var cardType = row.card_type || '0';
                    var cardTypeText = cardTypeMap[cardType] || '常规卡';
                    var cardTypeClass = cardType == '1' ? 'bg-yellow-100 text-yellow-700' : 'bg-gray-100 text-gray-700';

                    html += '<tr class="hover:bg-gray-50">';
                    html += '<td class="px-4 py-3 text-sm font-medium text-gray-800 whitespace-nowrap">' + row.km + '</td>';
                    html += '<td class="px-4 py-3 whitespace-nowrap"><span class="px-2 py-1 text-xs ' + versionClass + ' rounded">' + versionText + '</span></td>';
                    html += '<td class="px-4 py-3 whitespace-nowrap"><span class="px-2 py-1 text-xs ' + cardTypeClass + ' rounded">' + cardTypeText + '</span></td>';
                    html += '<td class="px-4 py-3 text-sm text-gray-600 whitespace-nowrap">' + row.zid + '</td>';
                    html += '<td class="px-4 py-3 text-sm whitespace-nowrap">' + row.name + '</td>';
                    html += '<td class="px-4 py-3 whitespace-nowrap"><span class="px-2 py-1 text-xs ' + statusClass + ' rounded">' + statusText + '</span></td>';
                    html += '<td class="px-4 py-3 text-sm text-gray-600 whitespace-nowrap">' + row.rmb + '</td>';
                    html += '<td class="px-4 py-3 text-sm text-gray-600 whitespace-nowrap">' + (row.qq || '-') + '</td>';
                    html += '<td class="px-4 py-3 text-sm text-gray-600 whitespace-nowrap">' + (row.usetime || '-') + '</td>';
                    html += '<td class="px-4 py-3 text-sm text-gray-600 whitespace-nowrap">' + row.addtime + '</td>';
                    html += '<td class="px-4 py-3 whitespace-nowrap"><button onclick="del(' + row.id + ')" class="px-3 py-1 text-xs bg-red-600 text-white rounded hover:bg-red-700 whitespace-nowrap">删除</button></td>';
                    html += '</tr>';
                });
                $('#kami-list').html(html);
                
                // 更新分页信息
                if (data.total !== undefined) {
                    $('#totalCount').text(data.total);
                    totalPages = Math.ceil(data.total / pagesize) || 1;
                    page = parseInt(p);  // 更新全局变量
                    $('#totalPages').text(totalPages);
                    $('#currentPage').text(page);
                    
                    $('#prevPage').prop('disabled', page <= 1);
                    $('#nextPage').prop('disabled', page >= totalPages);
                }
            }
        },
        error: function() {
            // 隐藏加载状态
            $('.loading-overlay').remove();
            showToast('服务器错误', 'error');
        }
    });
}

function searchOrder() {
    get_kami_list(1);
}

function openAddModal() {
    var myModalEl = document.getElementById('show');
    
    if (!myModalEl) {
        return;
    }
    
    var myModal = new bootstrap.Modal(myModalEl);
    myModal.show();
    
    $('#km-version').off('change').on('change', function() {
        renderGoodsData();
    });
    
    if($('#isgoods').val() != '1') {
        $('#isgoods').val('1');
        loadGoodsData();
    } else {
        renderGoodsData();
    }
}

function add_kami(act) {
    // 通过按钮 id 直接选择按钮
    var btnId = act === 'km_form' ? 'btn-km-form' : 'btn-km-form-rmb';
    var $btn = $('#' + btnId);
    
    // 防止重复点击
    if ($btn.length && $btn.prop('disabled')) return;
    if ($btn.length) {
        $btn.prop('disabled', true).data('original-text', $btn.html()).html('<i class="fas fa-spinner fa-spin mr-1"></i>生成中...');
    }
    showLoading();
    $.ajax({
        type: 'POST',
        data: $('#'+act).serialize(),
        url: 'ajax.php?act=add_kami',
        dataType: 'json',
        success: function(data) {
            hideLoading();
            if(data.code == 1) {
                var modalId = act == 'km_form' ? 'show' : 'show_rmb';
                var myModalEl = document.getElementById(modalId);
                if (myModalEl) {
                    var myModal = bootstrap.Modal.getInstance(myModalEl);
                    if (myModal) {
                        myModal.hide();
                    }
                }
                
                $('#result_title').text(data.msg);
                $('#txt_km').val(data.km);
                
                var resultModalEl = document.getElementById('show_result');
                var resultModal = bootstrap.Modal.getInstance(resultModalEl);
                if (resultModal) {
                    resultModal.dispose();
                }
                resultModal = new bootstrap.Modal(resultModalEl);
                resultModal.show();
                // 成功后不恢复按钮状态，因为弹窗已关闭
            } else {
                showToast(data.msg, 'error');
                // 失败时恢复按钮状态
                if ($btn.length) {
                    $btn.prop('disabled', false).html($btn.data('original-text'));
                }
            }
        },
        error: function() {
            hideLoading();
            showToast('服务器错误', 'error');
            if ($btn.length) {
                $btn.prop('disabled', false).html($btn.data('original-text'));
            }
        }
    });
}

var goodsData = null;

function loadGoodsData() {
    if (goodsData) {
        renderGoodsData();
        return;
    }
    
    showLoading();
    $.ajax({
        type: 'GET',
        url: 'ajax.php?act=get_goods_kami',
        dataType: 'json',
        success: function(data) {
            hideLoading();
            
            if (data.code == 1) {
                goodsData = data.data || {};
                goodsData.class = data.class || {};
                renderGoodsData();
            } else {
                showToast('加载商品数据失败：' + (data.msg || '未知错误'), 'error');
            }
        },
        error: function(xhr, status, error) {
            hideLoading();
            showToast('加载商品数据失败：' + error, 'error');
        }
    });
}

function renderGoodsData() {
    if (!goodsData || !goodsData.class) {
        return;
    }
    var version = $('#km-version').val() || 'cloud';
    var goodsSelect = $('#goods');
    goodsSelect.empty();

    if (version === 'qzone') {
        $('#admin-kami-cid-row').hide();
        $('#cid').val('');
        var qzoneGoods = (goodsData['qzone'] && $.isArray(goodsData['qzone'])) ? goodsData['qzone'] : [];
        if (qzoneGoods.length === 0) {
            $.each(goodsData, function(key, list) {
                if (key === 'class' || !list || !$.isArray(list)) return;
                $.each(list, function(k, v) {
                    var vv = (v.version || '').toString().toLowerCase();
                    if (vv === 'qzone') qzoneGoods.push(v);
                });
            });
        }
        if (qzoneGoods.length > 0) {
            $.each(qzoneGoods, function(k, v) {
                goodsSelect.append('<option value="' + v.id + '">' + v.name + '</option>');
            });
        } else {
            goodsSelect.append('<option value="">暂无秒赞版商品</option>');
        }
        $('#_time').hide();
        return;
    }

    $('#admin-kami-cid-row').show();
    var cidSelect = $('#cid');
    cidSelect.empty();
    if (version === 'tri_all') {
        // 构建“云端分类 + 代挂分类”组合选项（去重）
        var combined = {};
        $.each(goodsData, function(key, list) {
            if (key === 'class' || !list || !$.isArray(list)) return;
            list.forEach(function(v) {
                var vv = (v.version || '').toString().toLowerCase();
                if (vv !== 'tri_all') return;
                var cloudId = parseInt(v.type_cloud || v.type || 0);
                var dgId = parseInt(v.type_dg || 0);
                if (!cloudId || !dgId) return;
                var cName = goodsData.class[cloudId] || ('云端(' + cloudId + ')');
                var dName = goodsData.class[dgId] || ('代挂(' + dgId + ')');
                var keyPair = cloudId + ':' + dgId;
                if (cloudId === 9999 && dgId === 9999) {
                    combined[keyPair] = cName; // 两个都是“全部接口”时只显示一个
                } else if (cName === dName) {
                    combined[keyPair] = cName;
                } else {
                    combined[keyPair] = cName + ' + ' + dName;
                }
            });
        });
        var hasPair = false;
        $.each(combined, function(val, label) {
            cidSelect.append('<option value="' + val + '">' + label + '</option>');
            hasPair = true;
        });
        if (!hasPair) {
            cidSelect.append('<option value="tri_all">三版通用</option>');
        }
    } else {
        $.each(goodsData.class, function(i, value) {
            if (i == '9999') return;
            var list = goodsData[i];
            if (!list || !list.length) return;
            var filtered = list.filter(function(v) {
                var vv = (v.version || 'cloud').toLowerCase();
                if (version === 'cloud') return vv === 'cloud' || !v.version;
                if (version === 'dg') return vv === 'dg';
                if (version === 'cloud_all') return vv === 'cloud_all' || vv === 'all';
                if (version === 'dg_all') return vv === 'dg_all';
                return false;
            });
            if (filtered.length > 0) {
                cidSelect.append('<option value="' + i + '">' + value + '</option>');
            }
        });
        cidSelect.append('<option value="9999">全部接口</option>');
    }
    updateGoodsList();
    cidSelect.off('change').on('change', function() {
        updateGoodsList();
    });
    $('#goods').off('change').on('change', function() {
        if ($(this).val() == '-1') {
            $('#_time').show();
        } else {
            $('#_time').hide();
        }
    });
}

function updateGoodsList() {
    var cid = $('#cid').val();
    var version = $('#km-version').val() || 'cloud';
    var goodsSelect = $('#goods');
    
    if (goodsSelect.length == 0) {
        return;
    }
    
    goodsSelect.empty();
    
    if (version === 'tri_all') {
        // 依据“云端:代挂”组合筛选 tri_all 商品
        var pair = (cid || '').split(':');
        var cloudId = parseInt(pair[0] || 0);
        var dgId = parseInt(pair[1] || 0);
        var list = [];
        $.each(goodsData, function(key, arr) {
            if (key === 'class' || !arr || !$.isArray(arr)) return;
            arr.forEach(function(v) {
                var vv = (v.version || '').toString().toLowerCase();
                if (vv !== 'tri_all') return;
                var vCloud = parseInt(v.type_cloud || v.type || 0);
                var vDg = parseInt(v.type_dg || 0);
                if (cloudId && dgId) {
                    if (vCloud === cloudId && vDg === dgId) list.push(v);
                } else {
                    list.push(v);
                }
            });
        });
        $.each(list, function(k, v) {
            goodsSelect.append('<option value="' + v.id + '">' + v.name + '</option>');
        });
    } else if (goodsData && goodsData[cid]) {
        var list2 = goodsData[cid].filter(function(v) {
            var vv = (v.version || 'cloud').toLowerCase();
            if (version === 'cloud') return vv === 'cloud' || !v.version;
            if (version === 'dg') return vv === 'dg';
            if (version === 'qzone') return vv === 'qzone';
            if (version === 'cloud_all') return vv === 'cloud_all' || vv === 'all';
            if (version === 'dg_all') return vv === 'dg_all';
            return false;
        });
        $.each(list2, function(k, v) {
            goodsSelect.append('<option value="' + v.id + '">' + v.name + '</option>');
        });
    }
    if (version !== 'tri_all') {
        goodsSelect.append('<option value="-1">自定义</option>');
    }
    
    if (cid == '9999') {
        $('#_time').show();
    } else {
        $('#_time').hide();
    }
}

function add_rmb_km() {
    var myModal = new bootstrap.Modal(document.getElementById('show_rmb'));
    myModal.show();
}

function qk() {
    showConfirm('确定要清空所有卡密吗？', function() {
        showLoading();
        $.ajax({
            type: 'POST',
            url: 'ajax.php?act=kami_qk',
            data: {kami_qk_type: 0},
            dataType: 'json',
            success: function(data) {
                hideLoading();
                showToast(data.msg, data.code == 1 ? 'success' : 'error');
                if(data.code == 1) {
                    get_kami_list(1);
                }
            }
        });
    });
}

function do_qk(type) {
    showConfirm('确定要清空已使用的卡密吗？', function() {
        showLoading();
        $.ajax({
            type: 'POST',
            url: 'ajax.php?act=kami_qk',
            data: {kami_qk_type: 99},
            dataType: 'json',
            success: function(data) {
                hideLoading();
                showToast(data.msg, data.code == 1 ? 'success' : 'error');
                if(data.code == 1) {
                    get_kami_list(1);
                }
            }
        });
    });
}

function del(id) {
    showConfirm('确定要删除这个卡密吗？', function() {
        showLoading();
        $.ajax({
            type: 'POST',
            url: 'ajax.php?act=del_kami',
            data: {id: id},
            dataType: 'json',
            success: function(data) {
                hideLoading();
                showToast(data.msg, data.code == 1 ? 'success' : 'error');
                if(data.code == 1) {
                    get_kami_list(1);
                }
            }
        });
    });
}

function clearSpecialKami() {
    showConfirm('确定要清空所有特殊卡吗？此操作不可恢复！', function() {
        showLoading();
        $.ajax({
            type: 'POST',
            url: 'ajax.php?act=clear_kami_special',
            dataType: 'json',
            success: function(data) {
                hideLoading();
                showToast(data.msg, data.code == 1 ? 'success' : 'error');
                if(data.code == 1) {
                    get_kami_list(1);
                }
            }
        });
    });
}
</script>
