<?php
$title='自助购买';
include __DIR__ . '/head.php';
if($conf['buy_type'] == 1){
	exit("<script>window.location.href='./shop_km.php';</script>");
}

// 活动公告
$shop_activity_show = ($conf['shop_activity_show'] ?? '0') == '1';
$shop_activity_notice = $conf['shop_activity_notice'] ?? '';
?>
<?php if ($shop_activity_show && !empty($shop_activity_notice)): ?>
<div class="bg-gradient-to-r from-red-500 to-orange-500 rounded-xl shadow-sm overflow-hidden mb-4">
    <div class="p-4 text-white">
        <div class="flex items-center gap-3">
            <div class="w-10 h-10 bg-white/20 rounded-full flex items-center justify-center flex-shrink-0">
                <i class="fas fa-bullhorn text-lg"></i>
            </div>
            <div class="flex-1 overflow-hidden">
                <?php echo html_entity_decode($shop_activity_notice); ?>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>
<div class="grid grid-cols-1 lg:grid-cols-3 gap-4">
    <div class="lg:col-span-2">
        <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
            <div class="px-4 py-3 bg-gray-50 border-b border-gray-100 flex items-center gap-2">
                <i class="fas fa-shopping-bag text-indigo-500"></i>
                <h3 class="font-medium text-gray-800">商品购买</h3>
            </div>
            <div class="p-4">
                <form id="add" onsubmit="buy(this);return false;">
                    <div class="space-y-3">
                        <?php 
                        $qzone_enabled = $QZONE_ENABLED;
                        $cloud_enabled = $CLOUD_ENABLED;
                        $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_qzone_goods = $DB->getColumn("SELECT COUNT(*) FROM pre_goods WHERE status='1' AND (version='qzone' OR version='')");
                        $has_cloud_goods = $DB->getColumn("SELECT COUNT(*) FROM pre_goods WHERE status='1' AND version='cloud'");
                        $dg_enabled = $DG_ENABLED;
                        $has_dg_goods = $DB->getColumn("SELECT COUNT(*) FROM pre_goods WHERE status='1' AND version='dg'");

                        $show_qzone = $qzone_enabled && $has_qzone_goods > 0;
                        $show_cloud = $cloud_enabled && $has_cloud_goods > 0;
                        $show_dg = $dg_enabled && $has_dg_goods > 0;
                        $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_version_select = $show_qzone || $show_cloud || $show_dg || $show_cloud_all || $show_dg_all || $show_tri_all;
                        $req_version = isset($_GET['version']) ? daddslashes($_GET['version']) : '';
                        if(!in_array($req_version, ['cloud','dg','qzone','cloud_all','dg_all','tri_all','all'], true)) $req_version = '';
                        $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')))));
                        if($req_version){
                            if($req_version === 'cloud' && $show_cloud) $default_version = 'cloud';
                            if($req_version === 'dg' && $show_dg) $default_version = 'dg';
                            if($req_version === 'qzone' && $show_qzone) $default_version = 'qzone';
                            if($req_version === 'cloud_all' && $show_cloud_all) $default_version = 'cloud_all';
                            if($req_version === 'dg_all' && $show_dg_all) $default_version = 'dg_all';
                            if($req_version === 'tri_all' && $show_tri_all) $default_version = 'tri_all';
                            if($req_version === 'all' && $show_cloud_all) $default_version = 'cloud_all';
                        }

                        if($show_version_select): ?>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">产品版本</label>
                            <select class="w-full px-3 py-2 bg-gray-50 border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500" id="version" onchange="loadGoodsByVersion()">
                                <?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>
                            <p class="text-xs text-gray-500 mt-1"><?php if($show_cloud) echo htmlspecialchars($version_name_cloud).'：续费云端 | '; ?><?php if($show_dg) echo htmlspecialchars($version_name_dg).'：续费代挂 | '; ?><?php if($show_qzone) echo htmlspecialchars($version_name_qzone).'：续费空间秒赞 | '; ?><?php if($show_cloud_all) echo htmlspecialchars($version_name_cloud_all).'：云端+秒赞 | '; ?><?php if($show_dg_all) echo htmlspecialchars($version_name_dg_all).'：代挂+秒赞 | '; ?><?php if($show_tri_all) echo htmlspecialchars($version_name_tri_all).'：云端+代挂+秒赞'; ?></p>
                        </div>
                        <?php elseif($show_qzone): ?>
                        <input type="hidden" id="version" value="qzone">
                        <?php elseif($show_cloud): ?>
                        <input type="hidden" id="version" value="cloud">
                        <?php elseif($show_dg): ?>
                        <input type="hidden" id="version" value="dg">
                        <?php else: ?>
                        <div class="text-center py-8 text-gray-500">暂无可购买的商品，请联系管理员</div>
                        <?php endif; ?>
                        <div id="type-container">
                            <label class="block text-sm font-medium text-gray-700 mb-1">商品分类</label>
                            <select class="w-full px-3 py-2 bg-gray-50 border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500" id="type"></select>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">选择商品</label>
                            <select class="w-full px-3 py-2 bg-gray-50 border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500" name="goods"></select>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">下单QQ</label>
                            <div class="flex gap-2 overflow-hidden">
                                <input type="number" class="flex-1 w-full px-3 py-2 bg-gray-50 border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500" name="qq" required placeholder="输入QQ账号" style="min-width:0">
                                <?php
                                $qq_sources = get_user_qq_sources($userrow['zid']);
                                $cloud_qqs = $qq_sources['cloud'];
                                $dg_qqs = $qq_sources['dg'];
                                $qzone_qqs = $qq_sources['qzone'];
                                $option = array();
                                $cur_ver = $default_version;
                                $list = ($cur_ver === 'qzone') ? $qzone_qqs : (($cur_ver === 'dg' || $cur_ver === 'dg_all') ? $dg_qqs : (($cur_ver === 'tri_all') ? array_values(array_unique(array_merge($cloud_qqs, $dg_qqs))) : $cloud_qqs));
                                foreach($list as $q){ $option[] = '<option value="'.$q.'">'.$q.'</option>'; }
                                if(count($option)>0){
                                    echo '<select class="shrink-0 px-2 py-2 bg-gray-50 border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 text-sm" id="getqq">'.implode('',$option).'</select>';
                                }
                                ?>
                            </div>
                        </div>
                        <script>var cloudQqs=<?php echo json_encode($cloud_qqs);?>;var dgQqs=<?php echo json_encode($dg_qqs);?>;var qzoneQqs=<?php echo json_encode($qzone_qqs);?>;</script>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">商品价格</label>
                            <input type="text" class="w-full px-3 py-2 bg-gray-50 border border-gray-200 rounded-lg" id="need" disabled>
                        </div>
                        <div id="alert" class="hidden">
                            <div id="alert_frame" class="bg-gradient-to-r from-green-400 to-cyan-400 text-white font-medium p-3 rounded-lg text-sm"></div>
                        </div>
                        <?php if($conf['show_free']==1){ ?>
                        <div class="bg-amber-50 border-l-4 border-amber-400 p-3 rounded-r-lg">
                            <p class="text-amber-700 text-sm"><i class="fas fa-info-circle mr-1"></i>每个QQ号都可以免费体验 <?php echo $conf['is_free']; ?> 次，一号一次</p>
                        </div>
                        <?php } ?>
                        <div class="pt-2 flex flex-wrap gap-2">
                            <button type="button" id="buyBtn" class="flex-1 min-w-[120px] bg-indigo-600 hover:bg-indigo-700 text-white font-medium py-2.5 px-4 rounded-lg transition-colors flex items-center justify-center gap-1.5 disabled:bg-gray-300 disabled:cursor-not-allowed" onclick="showPaymentOptions()">
                                <i class="fas fa-wallet text-sm"></i><span>立即购买</span>
                            </button>
                            <?php if($conf['kami_open'] == 1){ ?>
                            <button type="button" class="flex-1 min-w-[120px] bg-green-600 hover:bg-green-700 text-white font-medium py-2.5 px-4 rounded-lg transition-colors flex items-center justify-center gap-1.5" onclick="kami()">
                                <i class="fas fa-key text-sm"></i><span>卡密兑换</span>
                            </button>
                            <?php } ?>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="lg:col-span-1">
        <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
            <div class="px-4 py-3 bg-gray-50 border-b border-gray-100 flex items-center gap-2">
                <i class="fas fa-info-circle text-indigo-500"></i>
                <h3 class="font-medium text-gray-800">购买须知</h3>
            </div>
            <div class="p-4 space-y-2 text-sm text-gray-600">
                <div class="flex gap-2"><i class="fas fa-check-circle text-green-500 mt-0.5"></i><p>请确保输入的QQ账号正确无误</p></div>
                <div class="flex gap-2"><i class="fas fa-check-circle text-green-500 mt-0.5"></i><p>购买成功后可在账号管理中查看</p></div>
                <div class="flex gap-2"><i class="fas fa-check-circle text-green-500 mt-0.5"></i><p>如有疑问请联系客服</p></div>
                <div class="flex gap-2"><i class="fas fa-check-circle text-green-500 mt-0.5"></i><p>商品一经购买，不支持退款</p></div>
            </div>
            <div class="px-4 pb-4">
                <?php
                $max_vip = $DB->getColumn("SELECT MAX(vip) FROM pre_user_vip");
                if($userrow['vip'] < $max_vip){
                ?>
                <div class="bg-gray-50 p-3 rounded-lg">
                    <p class="text-gray-600 text-sm mb-2">提升代理等级，享受更多优惠</p>
                    <a href="./upgrade.php" class="block w-full bg-gradient-to-r from-orange-500 to-pink-500 hover:from-orange-600 hover:to-pink-600 text-white font-medium py-2 rounded-lg text-center text-sm transition-colors">
                        <i class="fas fa-arrow-up mr-1"></i>立即升级
                    </a>
                </div>
                <?php } else { ?>
                <div class="bg-gray-50 p-3 rounded-lg text-center">
                    <div class="bg-gradient-to-r from-purple-500 to-indigo-500 text-white font-medium py-2 rounded-lg text-sm">
                        <i class="fas fa-crown mr-1"></i>最高等级会员
                    </div>
                </div>
                <?php } ?>
            </div>
        </div>
    </div>
</div>

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

<div id="appModal" class="fixed inset-0 z-50 hidden">
    <div class="fixed inset-0 bg-black/50 backdrop-blur-sm" onclick="closeModal()"></div>
    <div class="fixed inset-0 flex items-center justify-center p-4">
        <div class="bg-white rounded-2xl shadow-2xl w-full max-w-md max-h-[85vh] flex flex-col">
            <div class="flex items-center justify-between px-5 py-4 border-b border-gray-100 bg-gray-50/50 rounded-t-2xl">
                <h3 id="modalTitle" class="text-lg font-semibold text-gray-800"></h3>
                <button onclick="closeModal()" class="w-8 h-8 flex items-center justify-center rounded-full hover:bg-gray-200 text-gray-400 hover:text-gray-600 transition-colors"><i class="fas fa-times"></i></button>
            </div>
            <div id="modalBody" class="px-5 py-4 overflow-y-auto"></div>
            <div id="modalFooter" class="px-5 py-3 border-t border-gray-100 hidden"></div>
        </div>
    </div>
</div>

<script>
var showSelectTip = <?php echo ((string)($conf['login_select_str'] ?? '1') === '0') ? 'false' : 'true'; ?>;

function openModal(title, content, footerCallback) {
    document.getElementById('modalTitle').textContent = title;
    document.getElementById('modalBody').innerHTML = content;
    const modalFooter = document.getElementById('modalFooter');
    if (footerCallback) {
        modalFooter.innerHTML = footerCallback();
        modalFooter.classList.remove('hidden');
    } else {
        modalFooter.classList.add('hidden');
    }
    document.getElementById('appModal').classList.remove('hidden');
    document.body.style.overflow = 'hidden';
}

function closeModal() {
    document.getElementById('appModal').classList.add('hidden');
    document.body.style.overflow = '';
}

function showPaymentOptions() {
    var goodsId = $('select[name="goods"]').val();
    var qq = $('input[name="qq"]').val();
    var goodsType = $('select[name="goods"]').find("option:selected").attr("type");
    var goodsName = $('select[name="goods"]').find("option:selected").text();
    var goodsPrice = $('select[name="goods"]').find("option:selected").attr("price");

    if(!goodsId) { showToast('请选择商品'); return; }
    if(!qq) { showToast('请输入QQ账号'); return; }

    showLoading();
    $.ajax({
        type: 'GET',
        url: 'ajax.php?act=get_available_payments',
        dataType: 'json',
        success: function(data) {
            hideLoading();
            var payments = (data.code == 1 && data.data) ? data.data : [];
            var html = '<div class="space-y-3">';
            html += '<div class="bg-indigo-50 rounded-lg p-3">';
            html += '<div class="flex justify-between items-center mb-1"><span class="text-xs text-gray-600">商品名称</span><span class="text-xs font-medium text-gray-800 truncate max-w-[200px]">' + goodsName + '</span></div>';
            html += '<div class="flex justify-between items-center"><span class="text-xs text-gray-600">支付金额</span><span class="text-lg font-bold text-indigo-700">¥' + goodsPrice + '</span></div>';
            html += '<div class="flex justify-between items-center pt-1 mt-1 border-t border-indigo-100"><span class="text-xs text-gray-600">下单QQ</span><span class="text-xs font-medium text-gray-800">' + qq + '</span></div>';
            html += '</div>';
            html += '<button onclick="balancePayShop(' + goodsId + ', \'' + qq + '\', \'' + goodsType + '\')" class="w-full flex items-center justify-between bg-indigo-50 hover:bg-indigo-100 text-indigo-700 font-medium py-2.5 px-4 rounded-lg transition-colors">';
            html += '<div class="flex items-center gap-2"><i class="fas fa-wallet"></i><span>余额支付</span></div>';
            html += '<span class="text-sm text-gray-500">余额: <?php echo $userrow['rmb']; ?>元</span></button>';
            
            if(payments.length > 0){
                html += '<div class="pt-3 border-t border-gray-100"><p class="text-xs text-gray-500 mb-2 text-center">在线支付</p><div class="grid grid-cols-2 gap-2">';
                for(var i=0; i<payments.length; i++){
                    var item = payments[i];
                    var icon = 'alipay.png', color = 'text-blue-600', label = item.name || '支付宝';
                    if(item.pay_type == 'wxpay'){ icon = 'wxpay.png'; color = 'text-green-600'; label = item.name || '微信支付'; }
                    if(item.pay_type == 'qqpay'){ icon = 'qqpay.png'; color = 'text-sky-600'; label = item.name || 'QQ钱包'; }
                    html += '<button onclick="dopay(' + goodsId + ', ' + item.interface_id + ', \'' + qq + '\', \'' + goodsType + '\')" class="flex items-center justify-center gap-2 bg-gray-50 hover:bg-gray-100 '+color+' font-medium py-2.5 px-4 rounded-lg transition-colors">';
                    html += '<img src="../assets/img/'+icon+'" style="width:24px;"><span>'+label+'</span></button>';
                }
                html += '</div></div>';
            }
            html += '</div>';
            openModal('选择支付方式', html, function() {
                return '<button onclick="closeModal()" class="w-full py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg font-medium transition-colors">取消</button>';
            });
        },
        error: function(){ hideLoading(); showToast('服务器错误'); }
    });
}

function balancePayShop(goodsId, qq, goodsType) {
    closeModal();
    showLoading();
    $.ajax({
        type: 'POST',
        url: 'ajax.php?act=pay',
        data: { goods: goodsId, qq: qq, type: goodsType },
        dataType: 'json',
        success: function(data) {
            hideLoading();
            if(data.code == '1'){
                var loginUrl = (data.version === 'qzone') ? './qzone.php' : ((data.version === 'dg') ? ('./add.php?biz=dg&qq='+qq) : ('./add.php?qq='+qq));
                var tmp = '<p class="text-center">'+data.msg+'</p><div class="grid gap-2 mt-4"><a class="block py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg font-medium text-center text-sm" href="./">返回首页</a><a class="block py-2 bg-gray-600 hover:bg-gray-700 text-white rounded-lg font-medium text-center text-sm" href="'+loginUrl+'">前去登录QQ</a></div>';
                openModal('操作成功', tmp, function(){ return '<button onclick="closeModal();location.reload();" class="w-full py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg font-medium transition-colors">确定</button>'; });
            }else if(data.code == '-2'){
                openModal('提示', data.msg, function(){ return '<div class="flex gap-2"><button onclick="closeModal()" class="flex-1 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg font-medium transition-colors">取消</button><a href="./recharge.php" class="flex-1 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg font-medium text-center transition-colors">前往充值</a></div>'; });
            }else if(data.code == '-3'){
                openModal('提示', data.msg, function(){ return '<div class="flex gap-2"><button onclick="closeModal()" class="flex-1 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg font-medium transition-colors">取消</button><a href="./" class="flex-1 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg font-medium text-center transition-colors">前往找回</a></div>'; });
            }else{ showToast(data.msg); }
        },
        error: function(){ hideLoading(); showToast('服务器错误'); }
    });
}

function dopay(id, interface_id, qq, grade) {
    if(!qq){ showToast('QQ号不能为空'); return; }
    showLoading();
    $.get("ajax.php?act=dopay&interface_id="+interface_id+"&id="+id+"&qq="+qq+'&grade='+grade, function(data){
        hideLoading();
        if(data.code == 0){
            window.location.href='../other/submit.php?type='+data.type+'&orderid='+data.trade_no;
        }else if(data.code == '-3'){
            openModal('提示', data.msg, function(){ return '<div class="flex gap-2"><button onclick="closeModal()" class="flex-1 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg font-medium transition-colors">取消</button><a href="./" class="flex-1 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg font-medium text-center transition-colors">前往找回</a></div>'; });
        }else{ showToast(data.msg); }
    }, 'json').fail(function(){ hideLoading(); showToast('服务器错误'); });
}

var $_GET = (function(){
    var url = window.document.location.href.toString();
    var u = url.split("?");
    if(typeof(u[1]) == "string"){
        u = u[1].split("&");
        var get = {};
        for(var i in u){ var j = u[i].split("="); get[j[0]] = j[1]; }
        return get;
    }
    return '';
})();

function kami(){
    var qq = $('input[name="qq"]').val();
    if(!qq){ showToast('请输入QQ'); return; }
    var html = '<div class="space-y-3">';
    html += '<div class="bg-indigo-50 rounded-lg p-3"><div class="flex justify-between items-center"><span class="text-xs text-gray-600">下单QQ</span><span class="text-xs font-medium text-gray-800">' + qq + '</span></div></div>';
    html += '<input type="text" id="kamiInput" class="w-full px-3 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500" placeholder="输入卡密"></div>';
    openModal('卡密兑换', html, function(){
        return '<div class="flex gap-2"><button onclick="closeModal()" class="flex-1 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg font-medium transition-colors">取消</button><button onclick="submitKami(\''+qq+'\')" class="flex-1 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg font-medium transition-colors">确定</button></div>';
    });
}

function submitKami(qq){
    var text = document.getElementById('kamiInput').value;
    if(!text){ showToast('请输入卡密'); return; }
    closeModal();
    showLoading();
    $.ajax({
        type: 'POST',
        url: 'ajax.php?act=pay_kami',
        data: { qq: qq, km: text },
        dataType: 'json',
        success: function(data) {
            hideLoading();
            if(data.code == '1'){
                var loginUrl = (data.version === 'qzone') ? './qzone.php' : ((data.version === 'dg') ? ('./add.php?biz=dg&qq='+qq) : ('./add.php?qq='+qq));
                var tmp = '<p class="text-center">'+data.msg+'</p><div class="grid gap-2 mt-4"><a class="block py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg font-medium text-center text-sm" href="./">返回首页</a><a class="block py-2 bg-gray-600 hover:bg-gray-700 text-white rounded-lg font-medium text-center text-sm" href="'+loginUrl+'">前去登录QQ</a></div>';
                openModal('操作成功', tmp, function(){ return '<button onclick="closeModal();location.reload();" class="w-full py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg font-medium transition-colors">确定</button>'; });
            }else if(data.code == '-3'){
                openModal('提示', data.msg, function(){ return '<div class="flex gap-2"><button onclick="closeModal()" class="flex-1 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg font-medium transition-colors">取消</button><a href="./" class="flex-1 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg font-medium text-center transition-colors">前往找回</a></div>'; });
            }else{ showToast(data.msg); }
        },
        error: function(){ hideLoading(); showToast('服务器错误'); }
    });
}

function buy(obj){
    var qq = $('input[name="qq"]').val();
    showLoading();
    $.ajax({
        type: 'POST',
        url: 'ajax.php?act=pay',
        data: $(obj).serialize()+'&type='+$('select[name="goods"]').find("option:selected").attr("type"),
        dataType: 'json',
        success: function(data) {
            hideLoading();
            if(data.code == '1'){
                var loginUrl = (data.version === 'qzone') ? './qzone.php' : ((data.version === 'dg') ? ('./add.php?biz=dg&qq='+qq) : ('./add.php?qq='+qq));
                var tmp = '<p class="text-center">'+data.msg+'</p><div class="grid gap-2 mt-4"><a class="block py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg font-medium text-center text-sm" href="./">返回首页</a><a class="block py-2 bg-gray-600 hover:bg-gray-700 text-white rounded-lg font-medium text-center text-sm" href="'+loginUrl+'">前去登录QQ</a></div>';
                openModal('操作成功', tmp, function(){ return '<button onclick="closeModal();location.reload();" class="w-full py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg font-medium transition-colors">确定</button>'; });
            }else if(data.code == '-2'){
                openModal('提示', data.msg, function(){ return '<div class="flex gap-2"><button onclick="closeModal()" class="flex-1 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg font-medium transition-colors">取消</button><a href="./recharge.php" class="flex-1 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg font-medium text-center transition-colors">前往充值</a></div>'; });
            }else if(data.code == '-3'){
                openModal('提示', data.msg, function(){ return '<div class="flex gap-2"><button onclick="closeModal()" class="flex-1 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg font-medium transition-colors">取消</button><a href="./" class="flex-1 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg font-medium text-center transition-colors">前往找回</a></div>'; });
            }else{ showToast(data.msg); }
        },
        error: function(){ hideLoading(); showToast('服务器错误'); }
    });
}

var goodsdata;
var allGoodsData = null;
var allClassData = null;
var show_apiclass = 0;
$(document).ready(function(){
    get_goods();
    $('#type').change(function(){
        if($('#type').val() == 99){
            openModal('提示', '此分类是提升账号级别的<br>级别越高价钱就越低<hr>下单QQ随便填写即可', function(){ return '<button onclick="closeModal()" class="w-full py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg font-medium transition-colors">确定</button>'; });
        }
        goods_point();
    });
    $('select[name="goods"]').change(function(){ get_point(); });
    $('#getqq').change(function(){ $('input[name="qq"]').val($('#getqq').val()); });
    if($_GET['qq']){
        $('input[name="qq"]').val($_GET['qq']);
        $('#getqq').val($_GET['qq']);
    }else if($('#getqq').length > 0){
        $('input[name="qq"]').val($('#getqq').val());
    }
});

function get_goods(){
    showLoading();
    $.ajax({
        type: 'GET',
        url: 'ajax.php?act=get_goods',
        dataType: 'json',
        success: function(data) {
            hideLoading();
            allGoodsData = data.data;
            allClassData = data.class;
            show_apiclass = data.show_apiclass || 0;
            loadGoodsByVersion();
        },
        error: function(){ hideLoading(); showToast('服务器错误'); }
    });
}

function loadGoodsByVersion(){
    var version = $('#version').val() || 'cloud';
    var getqq = $('#getqq');
    if (getqq.length && typeof cloudQqs !== 'undefined' && typeof dgQqs !== 'undefined' && typeof qzoneQqs !== 'undefined') {
        var arr = (version === 'qzone') ? qzoneQqs : ((version === 'dg' || version === 'dg_all') ? dgQqs : (version === 'tri_all' ? Array.from(new Set((cloudQqs || []).concat(dgQqs || []))) : cloudQqs));
        getqq.empty();
        for (var i = 0; i < arr.length; i++) { getqq.append('<option value="'+arr[i]+'">'+arr[i]+'</option>'); }
        if (arr.length > 0) { $('input[name="qq"]').val(arr[0]); getqq.val(arr[0]); }
    }
    
    // 初始化 goodsdata，防止后续操作报错
    goodsdata = {};

    if(version == 'qzone'){
        $('#type-container').hide();
        var qzoneGoods = [];
        $.each(allGoodsData, function(typeId, items){
            if(items){
                items.forEach(function(item){
                    if(item.version == 'qzone'){
                        qzoneGoods.push(item);
                    }
                });
            }
        });
        if(qzoneGoods.length > 0){
            goodsdata['qzone'] = qzoneGoods;
            $('select[name="goods"]').html('');
            qzoneGoods.forEach(function(obj){
                var activityAttr = '';
                if(obj.activity_active == 1){
                    activityAttr = ' activity="1" activity_discount="'+obj.activity_discount+'" activity_start="'+(obj.activity_start_text||'')+'" activity_end="'+(obj.activity_end_text||'')+'"';
                }
                $('select[name="goods"]').append('<option value="'+ obj.id +'" price="'+ obj.price +'" base_price="'+(obj.base_price||obj.price)+'" user_discount_price="'+(obj.user_discount_price||obj.price)+'" desc="'+ encodeURI(obj.desc || '') +'" type="'+ obj.type +'" limit_once="'+(obj.limit_once||0)+'"'+activityAttr+'>'+ obj.name +'</option>');
            });
            $('#buyBtn').prop('disabled', false);
            get_point();
        } else {
            $('select[name="goods"]').html('<option>暂无秒赞版商品，请先在后台添加秒赞版商品</option>');
            $('#buyBtn').prop('disabled', true);
            $('#need').val('暂无商品');
        }
        return;
    }

    if(show_apiclass == 1){
        $('#type-container').hide();
        // 隐藏分类模式下，合并显示所有可见分类的商品
        goodsdata['all_merged'] = [];
        $.each(allGoodsData, function(typeId, items){
            if(typeId == 'qzone' || !items) return true;
            items.forEach(function(item){
                var match = false;
                if(version == 'cloud'){
                    match = item.version == 'cloud' || !item.version || item.version == '';
                } else if(version == 'dg'){
                    match = item.version == 'dg';
                } else if(version == 'cloud_all'){
                    match = item.version == 'cloud_all' || item.version == 'all';
                } else if(version == 'dg_all'){
                    match = item.version == 'dg_all';
                } else if(version == 'tri_all'){
                    match = item.version == 'tri_all';
                }
                if(match){
                    // 避免重复添加（如果商品同时在多个可见分类或聚合分类中）
                    var exists = goodsdata['all_merged'].some(function(g){ return g.id == item.id; });
                    if(!exists) goodsdata['all_merged'].push(item);
                }
            });
        });
    }else{
        $('#type-container').show();
    }
    $('#type').html('');
    
    if(showSelectTip && show_apiclass == 0){
        $('#type').append('<option value="">请选择分类</option>');
    }

    $.each(allClassData, function(k,v){
        if(v.id == 99) return;
        if(allGoodsData[v.id]){
            var filteredGoods = allGoodsData[v.id].filter(function(item){
                if(version == 'cloud'){
                    return item.version == 'cloud' || !item.version || item.version == '';
                } else if(version == 'dg'){
                    return item.version == 'dg';
                } else if(version == 'cloud_all'){
                    return item.version == 'cloud_all' || item.version == 'all';
                } else if(version == 'dg_all'){
                    return item.version == 'dg_all';
                } else if(version == 'tri_all'){
                    return item.version == 'tri_all';
                }
                return false;
            });
            if(filteredGoods.length > 0){
                if(show_apiclass == 0) goodsdata[v.id] = filteredGoods;
                $('#type').append('<option value="'+v.id+'">'+v.name+'</option>');
            }
        }
    });

    if(show_apiclass == 1){
        if(goodsdata['all_merged'] && goodsdata['all_merged'].length > 0){
            goods_point('all_merged');
        } else {
            $('select[name="goods"]').html('<option>暂无商品</option>');
            $('#buyBtn').prop('disabled', true);
            $('#need').val('暂无商品');
        }
        return;
    }

    if($('#type option').length == 0 || ($('#type option').length == 1 && showSelectTip && show_apiclass == 0)){
        $('select[name="goods"]').html('<option>暂无商品</option>');
        $('#buyBtn').prop('disabled', true);
        $('#need').val('暂无商品');
        return;
    }

    if(showSelectTip){
        $('#type').val('');
        $('select[name="goods"]').html('<option value="">请选择商品</option>');
        $('#buyBtn').prop('disabled', true);
        $('#need').val('');
    }else{
        goods_point();
    }
}

function goods_point(customType){
    var type = customType || $('#type option:selected').val();
    $('select[name="goods"]').html('');
    if(!type){
        $('select[name="goods"]').append('<option value="">请选择商品</option>');
        $('#buyBtn').prop('disabled', true);
        $('#need').val('');
        $('#alert').addClass('hidden');
        return;
    }
    if(goodsdata[type] == undefined){
        $('select[name="goods"]').append('<option>该分类下没有商品</option>');
        $('#buyBtn').prop('disabled', true);
    }else{
        if(showSelectTip){
            $('select[name="goods"]').append('<option value="">请选择商品</option>');
        }
        $.each(goodsdata[type], function(idx,obj){
            var activityAttr = '';
            if(obj.activity_active == 1){
                activityAttr = ' activity="1" activity_discount="'+obj.activity_discount+'" activity_start="'+(obj.activity_start_text||'')+'" activity_end="'+(obj.activity_end_text||'')+'"';
            }
            $('select[name="goods"]').append('<option value="'+ obj.id +'" price="'+ obj.price +'" base_price="'+(obj.base_price||obj.price)+'" user_discount_price="'+(obj.user_discount_price||obj.price)+'" desc="'+ encodeURI(obj.desc) +'" type="'+ obj.type +'" limit_once="'+(obj.limit_once||0)+'"'+activityAttr+'>'+ obj.name +'</option>');
        });
        if(showSelectTip){
            $('select[name="goods"]').val('');
            $('#buyBtn').prop('disabled', true);
            $('#need').val('');
            $('#alert').addClass('hidden');
        }else{
            $('#buyBtn').prop('disabled', false);
            get_point();
        }
    }
}

function get_point(){
    var selectedGoods = $('select[name="goods"]').val();
    if(!selectedGoods){
        $('#need').val('');
        $('#buyBtn').prop('disabled', true);
        $('#alert').addClass('hidden');
        return;
    }
    var $opt = $('select[name="goods"]').find("option:selected");
    var price = $opt.attr("price");
    var userDiscountPrice = $opt.attr('user_discount_price');
    var limitOnce = $opt.attr('limit_once');
    var desc = $opt.attr('desc');
    var hasDesc = desc && desc !== 'null';
    $('#buyBtn').prop('disabled', false);

    var limitTag = '<div class="mt-1 text-xs text-amber-600"><i class="fas fa-exclamation-circle mr-1"></i>该商品限购一次，且不支持生成卡密</div>';

    // 检查活动信息
    var activity = $opt.attr('activity');
    var activityDiscount = $opt.attr('activity_discount');
    var activityStart = $opt.attr('activity_start');
    var activityEnd = $opt.attr('activity_end');

    if(activity == '1' && activityDiscount && activityDiscount < 100){
        // price 已经是后端计算好的活动折扣价格
        // 活动价格 = (商品原价 × 用户等级折扣) × 活动折扣
        // userDiscountPrice = 商品原价 × 用户等级折扣
        // price = userDiscountPrice × 活动折扣
        // activityDiscount 是百分比，如80表示8折
        var discountText = (activityDiscount / 10).toFixed(1).replace(/\.0$/, '');
        $('#need').val('￥'+price + ' (原价￥'+userDiscountPrice+', 活动'+discountText+'折)');

        var activityHtml = '<div class="flex items-center text-green-600"><i class="fas fa-gift mr-2"></i><span>活动进行中！'+discountText+'折优惠</span></div>';
        if(activityStart && activityEnd){
            activityHtml += '<div class="text-xs text-gray-500 mt-1">活动时间：'+activityStart+' 至 '+activityEnd+'</div>';
        }
        var parts = [activityHtml];
        if(hasDesc){
            parts.push('<div class="mt-2 pt-2 border-t border-gray-100 text-sm text-gray-600">' + decodeURI(desc) + '</div>');
        }
        if(limitOnce == '1'){
            parts.push(limitTag);
        }
        $('#alert').removeClass('hidden');
        $('#alert_frame').html(parts.join(''));
    }else{
        $('#need').val('￥'+price);
        var parts = [];
        if(hasDesc){
            parts.push(decodeURI(desc));
        }
        if(limitOnce == '1'){
            parts.push(limitTag);
        }
        if(parts.length){
            $('#alert').removeClass('hidden');
            $('#alert_frame').html(parts.join(''));
        }else{
            $('#alert').addClass('hidden');
        }
    }
}
</script>
