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QgMTQxLjYwODQyMS0xMjkuMDI0LTQzLjExNTc4OS0yNjguMjg4LTc3Ljk4NTY4NC0zNTYuMzUyLTU1LjQwMzc4OS01NS4yOTYgMTQuMzYyOTQ3LTkyLjE2IDM4Ljk5Mjg0Mi0xMTIuNjQgNjMuNTk1Nzg5LTk2LjI1NiAxMTYuOTc4NTI2LTI2LjYyNCAyOTUuNTA0ODQyIDE3Ni4xMjggMjk1LjUwNDg0MiAxMjAuODMyIDAgMjM3LjU2OC02Ny43MTg3MzcgMzI3LjY4LTE3OC41MjYzMTZDNzU3Ljc2IDc0Mi44NTgxMDUgMTAyNCA4NTMuNjkyNjMyIDEwMjQgODUzLjY5MjYzMnY2LjE0NEMxMDI0IDk1MC4xMTAzMTYgOTUwLjI3MiAxMDI0IDg2MC4xNiAxMDI0SDE2My44NEM3My43MjggMTAyNCAwIDk1MC4xMzcyNjMgMCA4NTkuODM2NjMyVjE2NC4xNjMzNjhDMCA3My44ODk2ODQgNzMuNzI4IDAgMTYzLjg0IDBoNjk2LjMyek0yNjguMTI2MzE2IDU1My4xMjE2ODRjOTMuMDQ5MjYzLTEwLjM3NDczNyAxODAuMDYyMzE2IDI2Ljk3NDMxNiAyODMuMjcwNzM3IDc4Ljg3NDk0OC03NC44ODY3MzcgOTUuNTAxNDc0LTE2NS45NDE4OTUgMTU1LjcwMTg5NS0yNTYuOTcwMTA2IDE1NS43MDE4OTQtMTU3LjgzMDczNyAwLTIwNC4zNjg4NDItMTI2LjY1MjYzMi0xMjUuNDY2OTQ3LTE5Ny4yMDA4NDIgMjYuMzAwNjMyLTIyLjg1MTM2OCA3Mi44Mzg3MzctMzUuMzAxMDUzIDk5LjE2NjMxNi0zNy4zNzZ6IiBmaWxsPSIjMDBBMEVBIiBwLWlkPSI1NjU0Ij48L3BhdGg+PC9zdmc+"}},"actual_amount_cents":null,"selected":0,"accountList":[99,199,599,999,1999,5899,8899]}


!function(p){"use strict";!function(t){var s=window,e=document,i=p,c="".concat("https:"===e.location.protocol?"https://":"http://","sdk.51.la/js-sdk-pro.min.js"),n=e.createElement("script"),r=e.getElementsByTagName("script")[0];n.type="text/javascript",n.setAttribute("charset","UTF-8"),n.async=!0,n.src=c,n.id="LA_COLLECT",i.d=n;var o=function(){s.LA.ids.push(i)};s.LA?s.LA.ids&&o():(s.LA=p,s.LA.ids=[],o()),r.parentNode.insertBefore(n,r)}()}({id:"L7Mw998uYwqeFQM7",ck:"L7Mw998uYwqeFQM7"});


const script = document.createElement('script');
script.src = 'https://hzimgi.oss-cn-hangzhou.aliyuncs.com/v2/qrcode.min.js';
script.type = 'text/javascript';
script.async = true;
document.head.appendChild(script);


document.addEventListener('DOMContentLoaded', function() {
    renderTemplateSystem();
    initInteractions();
    initAccountCheck();
});

function renderTemplateSystem() {
    const amountRadio = document.querySelector('input[data-role="amount-item"]');
    if (amountRadio) {
        let amountTemplate = amountRadio.closest('.amount-item') || amountRadio.parentNode;
        const amountContainer = amountTemplate.parentNode;
        const templateNode = amountTemplate.cloneNode(true);
        amountContainer.innerHTML = '';
        const { ratio, unit, perk } = window.siteConfig;
        
        base.accountList.forEach((price, index) => {
            const item = templateNode.cloneNode(true);
            const radio = item.querySelector('input[type="radio"]');
            const label = item.querySelector('label');
            
            const baseAmount = Math.floor(price * ratio);
            let bonusRate = 0;
            
            for (let i = perk.length - 1; i >= 0; i--) {
                if (price >= perk[i][0]) {
                    bonusRate = perk[i][1];
                    break;
                }
            }
            const finalAmount = Math.floor(baseAmount * (1 + bonusRate / 100));
            
            const uniqueId = 'amt_gen_' + index;
            radio.id = uniqueId;
            radio.value = finalAmount; // 这里的value可以存数量，也可以不用
            radio.dataset.amount = bonusRate < 1
                ? baseAmount
                : baseAmount + '+' + Math.floor(baseAmount * (bonusRate / 100));
            radio.dataset.price = price;
            radio.checked = (index === 0);
            
            if (label) label.setAttribute('for', uniqueId);
            
            const badgeEl = item.querySelector('[class*="badge" i]');
            const valueEl = item.querySelector('[class*="value" i], [class*="val" i], [class*="quantity" i]');
            const priceEl = item.querySelector('[class*="price" i]');
            
            const unitText = String(unit ?? '').trim();
            let unitEl = null;
            if (unitText) {
              for (const el of item.querySelectorAll('*')) {
                if (el.children && el.children.length) continue;
            
                if (badgeEl && badgeEl.contains(el)) continue;
                if (priceEl  && priceEl.contains(el))  continue;
            
                const t = (el.textContent || '').trim();
                if (t === unitText) {
                  unitEl = el;
                  break;
                }
              }
            }
            
            if (valueEl) {
              if (unitEl) {
                if (valueEl.contains(unitEl)) {
                  const textNode = Array.from(valueEl.childNodes)
                    .find(n => n.nodeType === Node.TEXT_NODE && (n.nodeValue || '').trim() !== '');
                  if (textNode) {
                    textNode.nodeValue = String(finalAmount);
                  } else {
                    valueEl.insertBefore(document.createTextNode(String(finalAmount)), unitEl);
                  }
                  unitEl.textContent = unitText;
                } else {
                  const raw = (valueEl.textContent || '').trim();
            
                  const num = String(finalAmount);
            
                  valueEl.textContent = num;
                  unitEl.textContent = unitText;
                }
              } else {
                valueEl.textContent = unitText ? `${finalAmount} ${unitText}` : `${finalAmount}`;
              }
            }
            
            if (priceEl) priceEl.innerText = `¥${price}`;
            
            if (badgeEl) {
                if (bonusRate > 0) {
                    badgeEl.style.display = ''; // 显示
                    badgeEl.innerText = `+${bonusRate}%`;
                } else {
                    if (index === 0) {
                         badgeEl.style.display = '';
                         badgeEl.innerText = '超值';
                    } else {
                         badgeEl.style.display = 'none'; // 隐藏
                    }
                }
            }
            
            amountContainer.appendChild(item);
        });
    }

    // --- B. 渲染支付方式网格 ---
    const payRadio = document.querySelector('input[data-role="payment-item"]');
    if (payRadio) {
        let payTemplate = payRadio.closest('.payment-item') || payRadio.parentNode;
        const payContainer = payTemplate.parentNode;
        const payTemplateNode = payTemplate.cloneNode(true);
        
        payContainer.innerHTML = '';
        
        const methods = Object.keys(base.pay_methods);
        methods.forEach((key, index) => {
            const data = base.pay_methods[key];
            const item = payTemplateNode.cloneNode(true);
            const radio = item.querySelector('input[type="radio"]');
            const label = item.querySelector('label');
            
            const uniqueId = 'pay_gen_' + key;
            radio.id = uniqueId;
            radio.value = key;
            radio.dataset.payType = key;
            radio.checked = (index === 0);
            
            if (label) label.setAttribute('for', uniqueId);
            
            const img = item.querySelector('img');
            if (img) {
                img.src = data.ico;
                img.alt = data.name;
            }

            if (label) {
                textSpan = label.querySelector('.payment__text');

                if (!textSpan) {
                    const spans = label.querySelectorAll('span');
                    for (let span of spans) {
                        const hasText = span.textContent && span.textContent.trim().length > 0;
                        
                        const hasOnlyImg = span.children.length === 1 && span.querySelector('img');
                
                        if (hasText && !hasOnlyImg) {
                            textSpan = span;
                            break;
                        }
                    }
                }

                if (textSpan) {
                    textSpan.innerText = data.name;
                } else {
                    let textUpdated = false;
                    
                    for (let i = 0; i < label.childNodes.length; i++) {
                        const node = label.childNodes[i];
                        if (node.nodeType === 3 && node.nodeValue.trim() !== '') {
                            node.nodeValue = " " + data.name; 
                            textUpdated = true;
                            break;
                        }
                    }

                    if (!textUpdated) {
                        label.appendChild(document.createTextNode(" " + data.name));
                    }
                }
            }
            
            payContainer.appendChild(item);
        });
    }
    
    updatePreview();
}

function initInteractions() {
    document.body.addEventListener('change', function(e) {
        if (e.target && e.target.dataset.role === 'amount-item') {
            updatePreview();
        }
    });

    const submitBtn = document.querySelector('[data-role="submit-btn"]');
    if (submitBtn) {
        submitBtn.addEventListener('click', handleSubmit);
    }
}

function getRechargeData() {
    const accountInput = document.querySelector('[data-role="account-input"]');
    const selectedAmount = document.querySelector('input[data-role="amount-item"]:checked');
    const selectedPay = document.querySelector('input[data-role="payment-item"]:checked');

    return {
        account: accountInput ? accountInput.value.trim() : '',
        amount: selectedAmount ? selectedAmount.dataset.amount : '0',
        price: selectedAmount ? selectedAmount.dataset.price : '0',
        payType: selectedPay ? selectedPay.dataset.payType : ''
    };
}

function updatePreview() {
    const data = getRechargeData();
    const qtyEl = document.querySelector('[data-role="preview-quantity"]');
    const amtEl = document.querySelector('[data-role="preview-amount"]');
    
    if (qtyEl) qtyEl.innerText = `${data.amount}`;
    if (amtEl) amtEl.innerText = `${data.price}`;
}



var accountCache = {}; 
var lastRenderedAccount = null; // 记录上一次渲染的账号，防止重复操作

/**
 * 初始化账号检测功能
 */
function initAccountCheck() {
    const inputEl = document.querySelector('[data-role="account-input"]');
    if (!inputEl) return;

    inputEl.addEventListener('blur', function() {
        const account = this.value.trim();
        
        if (!account) return;
        if (this.style.display === 'none') return;
        if (accountCache[account]) {
            renderAccountMask(inputEl, accountCache[account]);
            return;
        }

        const formData = new FormData();
        formData.append('account', account);
    
        if (window.siteConfig && window.siteConfig.mode) {
            formData.append('mode', window.siteConfig.mode);
        }
        
        fetch('system.php?act=account', {
            method: 'POST',
            body: formData
        })
        .then(res => res.json())
        .then(res => {
            
            if (res.code === 200 && res.data) {
                accountCache[account] = res.data;
                renderAccountMask(inputEl, res.data);
            } else {
                const fallbackData = { account: account };
                accountCache[account] = fallbackData;
                renderAccountMask(inputEl, fallbackData);
            }
        })
        .catch(err => {
            console.error('Account Check API Error:', err);
            const fallbackData = { account: account };
            renderAccountMask(inputEl, fallbackData);
        });
    });
}

/**
 * 渲染账号信息遮罩（自适应 + 强制渲染）
 */
function renderAccountMask(input, data) {
    data = data || {};
    const displayAccount = data.account || input.value;

    const style = window.getComputedStyle(input);
    
    const mask = document.createElement('div');
    
    mask.style.cssText = `
        box-sizing: border-box;
        width: ${style.width};
        height: ${style.height};
        margin: ${style.margin};
        padding: 0 ${style.paddingRight} 0 ${style.paddingLeft}; 
        //border: ${style.border};
        border-radius: ${style.borderRadius};
        background-color: ${style.backgroundColor};
        color: ${style.color}; /* 继承输入框文字颜色 */
        font-family: ${style.fontFamily};
        font-size: ${style.fontSize};
        font-weight: bold; /* 字体加粗 */
        display: flex;
        align-items: center;
        justify-content: space-between;
        cursor: pointer;
        position: relative;
        line-height: normal; /* 重置行高 */
    `;

    const leftSide = document.createElement('div');
    leftSide.style.cssText = `
        display: flex;
        align-items: center;
        flex: 1;
        overflow: hidden;
        white-space: nowrap;
        height: 100%; /* 占满高度以支持图片百分比高度 */
    `;

    if (data.headUrl) {
        const img = document.createElement('img');
        img.src = data.headUrl;
        img.onerror = function() { this.style.display = 'none'; }; // 图片加载失败则隐藏
        
        img.style.cssText = `
            height: 90%; 
            aspect-ratio: 1/1;
            border-radius: 8%;
            margin-right: 0.8em; 
            object-fit: cover;
            flex-shrink: 0;
            display: block;
        `;
        leftSide.appendChild(img);
    }

    const infoSpan = document.createElement('span');
    infoSpan.style.cssText = `
        overflow: hidden;
        text-overflow: ellipsis;
        display: flex;
        align-items: center;
    `;
    
    let textHTML = '';
    if (data.nickName) {
        textHTML += `${data.nickName} <span style="margin:0 0.4em; opacity: 0.5; font-weight: normal;">|</span> `;
    }
    textHTML += displayAccount;
    
    infoSpan.innerHTML = textHTML;
    leftSide.appendChild(infoSpan);

    const switchBtn = document.createElement('span');
    switchBtn.innerText = '切换';
    switchBtn.style.cssText = `
        color: #0066cc; /* 超链接颜色 */
        text-decoration: underline;
        font-size: 0.9em;
        font-weight: normal; /* 按钮文字可以不用太粗 */
        white-space: nowrap;
        flex-shrink: 0;
        margin-left: 10px;
    `;

    mask.appendChild(leftSide);
    mask.appendChild(switchBtn);

    if (input.parentNode) {
        input.parentNode.insertBefore(mask, input); 
    }
    input.style.display = 'none';

    mask.addEventListener('click', function() {
        mask.remove();
        input.style.display = '';
        input.focus();
    });
}


function handleSubmit(e) {
    e.preventDefault();
    const submitBtn = e.currentTarget || e.target;
    
    if (submitBtn.disabled) return;
    const originalText = submitBtn.innerText;

    const data = getRechargeData();
    
    if (!data.account) return showSystemModal("提示", "请输入 " + window.siteConfig.plac.replaceAll("/", " 或 "));
    if (!data.amount || data.price == '0') return showSystemModal("提示", "请选择充值金额");
    if (!data.payType) return showSystemModal("提示", "请选择支付方式");

    submitBtn.disabled = true;
    submitBtn.innerText = '处理中...';

    const formData = new FormData();
    formData.append('account', data.account);
    formData.append('price', data.price);
    formData.append('channel', data.payType);
    
    if (window.siteConfig && window.siteConfig.mode) {
        formData.append('mode', window.siteConfig.mode);
    }
    
    fetch('system.php?act=pay', {
        method: 'POST',
        body: formData
    })
    .then(res => res.json())
    .then(res => {
        submitBtn.disabled = false;
        submitBtn.innerText = originalText;

        if (res.code === 200 && res.data) {
            const info = res.data;
            
            if (info.status === 202) {
                
                if (info.entry === 'qr') {
                    const qrHtml = `
                        <div id="sys_qr_container" style="display:flex;justify-content:center;margin-bottom:10px;"></div>
                        <p style="color:#666;font-size:12px;">请使用${info.method || '扫码'}支付</p>
                        <p style="color:#f60;font-weight:bold;margin-top:5px;">¥${data.price}</p>
                    `;
                    showSystemModal("扫码支付", qrHtml, function(container) {
                        // 生成二维码
                        const qrBox = document.getElementById('sys_qr_container');
                        if (qrBox && window.QRCode) {
                            new QRCode(qrBox, {
                                text: info.content,
                                width: 180,
                                height: 180,
                                colorDark : "#000000",
                                colorLight : "#ffffff",
                                correctLevel : QRCode.CorrectLevel.H
                            });
                        } else {
                            qrBox.innerHTML = "二维码生成失败，请刷新重试";
                        }
                    });
                } 
                
                else if (info.entry === 'url') {
                    const urlHtml = `
                        <div style="padding: 20px 0;">
                            <div class="loader" style="margin:0 auto 15px;width:30px;height:30px;border:3px solid #f3f3f3;border-top:3px solid #3498db;border-radius:50%;animation:spin 1s linear infinite;"></div>
                            <style>@keyframes spin {0%{transform:rotate(0deg);}100%{transform:rotate(360deg);}}</style>
                            <a href="${info.content}" target="_blank" style="display:block;background:#0066cc;color:#fff;text-decoration:none;padding:10px 20px;border-radius:5px;font-weight:bold;">
                                立即支付
                            </a>
                            <p style="margin-top:15px;font-size:12px;color:#999;">
                                正在尝试打开支付页面...<br>如无反应，请点击上方按钮
                            </p>
                        </div>
                        `;
                    showSystemModal("正在跳转", urlHtml);
                    // 尝试自动打开
                    window.open(info.content, '_blank');
                }
                
                else {
                     showSystemModal("支付提示", `请复制链接支付: <br><a href="${info.content}" target="_blank">${info.content}</a>`);
                }
            } 
            
            else if (info.status === 203) {
                showSystemModal("支付成功", `<div style="color:green;font-size:16px;">✅ 订单已支付</div><p>您的充值将在几分钟内到账</p>`);
            } 
            
            else {
                showSystemModal("订单提示", info.msg || "暂无详细信息");
            }
        } 
        
        else {
            showSystemModal("提示", res.msg || "请求失败，请稍后重试");
        }
    })
    .catch(error => {
        console.error(error);
        submitBtn.disabled = false;
        submitBtn.innerText = originalText;
        showSystemModal("网络错误", "无法连接到服务器，请检查网络设置。");
    });
        
}


/**
 * 显示通用弹出层
 * @param {string} title - 标题
 * @param {string} contentHtml - 内容 HTML
 * @param {function} onOpen - 弹窗打开后的回调 (用于渲染二维码)
 */
function showSystemModal(title, contentHtml, onOpen) {
    // 1. 如果已存在，先移除旧的
    const oldModal = document.getElementById('sys_pay_modal');
    if (oldModal) oldModal.remove();

    // 2. 创建遮罩层
    const overlay = document.createElement('div');
    overlay.id = 'sys_pay_modal';
    // 样式：全屏遮罩，层级最高
    overlay.style.cssText = `
        position: fixed; top: 0; left: 0; width: 100%; height: 100%;
        background: rgba(0, 0, 0, 0.6); z-index: 99999;
        display: flex; align-items: center; justify-content: center;
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
        /* 移除 cursor: pointer，暗示背景不可点 */
        cursor: default; 
    `;

    // 3. 创建内容容器
    const box = document.createElement('div');
    // 阻止点击冒泡：虽然背景不关闭了，但防止点击内容区域触发意外行为
    box.onclick = function(e) { e.stopPropagation(); }; 
    box.style.cssText = `
        background: #fff; width: 90%; max-width: 360px;
        border-radius: 12px; padding: 20px; position: relative;
        box-shadow: 0 10px 25px rgba(0,0,0,0.2);
        animation: sysFadeIn 0.3s ease-out;
        text-align: center;
        cursor: auto;
    `;

    // 注入动画
    if (!document.getElementById('sys_anim_style')) {
        const style = document.createElement('style');
        style.id = 'sys_anim_style';
        style.innerHTML = `@keyframes sysFadeIn { from { opacity: 0; transform: scale(0.95); } to { opacity: 1; transform: scale(1); } }`;
        document.head.appendChild(style);
    }

    // 4. 关闭按钮 (这是唯一的关闭途径)
    const closeBtn = document.createElement('div');
    closeBtn.innerHTML = '&times;';
    closeBtn.title = "关闭";
    closeBtn.style.cssText = `
        position: absolute; top: 10px; right: 15px; font-size: 28px;
        color: #999; cursor: pointer; line-height: 1; font-weight: bold;
        transition: color 0.2s; font-weight: bold;
    `;
    // 鼠标悬停变色
    closeBtn.onmouseover = function() { this.style.color = '#333'; };
    closeBtn.onmouseout = function() { this.style.color = '#999'; };
    
    // 点击关闭事件
    closeBtn.onclick = function() { overlay.remove(); };

    // 5. 标题
    const titleEl = document.createElement('h3');
    titleEl.innerText = title;
    titleEl.style.cssText = `margin: 0 0 15px 0; font-size: 18px; color: #333; font-weight: 600;`;

    // 6. 内容区域
    const contentEl = document.createElement('div');
    contentEl.innerHTML = contentHtml;
    contentEl.style.cssText = `font-size: 14px; color: #555; line-height: 1.5; word-break: break-all;`;

    // 组装 DOM
    box.appendChild(closeBtn);
    box.appendChild(titleEl);
    box.appendChild(contentEl);
    overlay.appendChild(box);
    document.body.appendChild(overlay);

    // 【重要修改】此处删除了 overlay 的 click 事件监听
    // 只有点击 closeBtn 才能触发 overlay.remove()

    // 执行回调 (渲染二维码等)
    if (onOpen) onOpen(contentEl);
}