迁移商店弹窗脚本

This commit is contained in:
2026-04-25 14:56:04 +08:00
parent 66a9e8ad23
commit b622053bc2
3 changed files with 706 additions and 364 deletions
@@ -583,7 +583,8 @@
}
</style>
<div id="shop-modal">
<div id="shop-modal" data-shop-items-url="{{ route('shop.items') }}" data-shop-buy-url="{{ route('shop.buy') }}"
data-shop-rename-url="{{ route('shop.rename') }}">
<div id="shop-modal-inner" style="position:relative;">
{{-- 标题栏 --}}
@@ -638,348 +639,7 @@
</div>
</div>
<script>
/**
* 商店弹窗逻辑
* 工具栏点击「商店」按钮触发,全屏模态展示
*/
(function() {
let shopLoaded = false;
/** 打开商店弹窗 */
window.openShopModal = function() {
document.getElementById('shop-modal').style.display = 'flex';
if (!shopLoaded) {
shopLoaded = true;
fetchShopData();
}
};
/** 关闭商店弹窗 */
window.closeShopModal = function() {
document.getElementById('shop-modal').style.display = 'none';
};
// 点击遮罩层关闭弹窗
document.getElementById('shop-modal').addEventListener('click', function(e) {
if (e.target === this) closeShopModal();
});
/** 拉取商品数据 */
function fetchShopData() {
fetch('{{ route('shop.items') }}', {
headers: {
'Accept': 'application/json',
'X-CSRF-TOKEN': _csrf()
}
})
.then(r => r.json())
.then(data => renderShop(data))
.catch(() => showShopToast('⚠ 加载失败,请重试', false));
}
/** 渲染商品列表(2列网格) */
function renderShop(data) {
// 更新余额
document.getElementById('shop-jjb').textContent = Number(data.user_jjb).toLocaleString();
// 周卡状态
const badge = document.getElementById('shop-week-badge');
if (data.active_week_effect) {
const icons = {
fireworks: '🎆',
rain: '🌧',
lightning: '⚡',
snow: '❄️',
sakura: '🌸',
meteors: '🌠',
'gold-rain': '🪙',
hearts: '💖',
confetti: '🎊',
fireflies: '✨'
};
badge.textContent = (icons[data.active_week_effect] ?? '') + ' 周卡生效中';
badge.style.display = 'inline-block';
}
const ringCounts = data.ring_counts || {};
const groups = [{
label: '⚡ 单次特效卡',
desc: '立即播放一次',
type: 'instant'
},
{
label: '📅 周卡 7天登录自动播放',
desc: '同时只能激活一种,购新旧失效不退款',
type: 'duration'
},
{
label: '💍 求婚戒指',
desc: '存入背包,求婚时消耗(被拒则遗失)',
type: 'ring'
},
{
label: '🎣 自动钓鱼卡',
desc: '激活后自动收篼,无需手动点击浮漂',
type: 'auto_fishing'
},
{
label: '🎭 道具',
desc: '',
type: 'tools'
},
];
const list = document.getElementById('shop-items-list');
list.innerHTML = '';
groups.forEach(g => {
const items = data.items.filter(i => g.type === 'tools' ? ['one_time', 'sign_repair'].includes(i.type) : i.type === g.type);
if (!items.length) return;
// 分组标题(独占一整行)
const header = document.createElement('div');
header.className = 'shop-group-header';
// 分组标题徽章:
// - auto_fishing:显示剩余时间(紫色)
// - duration:显示当前已激活的周卡名称(绿色)
let groupSuffix = '';
if (g.type === 'auto_fishing' && (data.auto_fishing_minutes_left || 0) > 0) {
const left = data.auto_fishing_minutes_left;
const leftStr = left >= 60 ? Math.floor(left / 60) + ' 小时' : left + ' 分钟';
groupSuffix =
` <span style="display:inline-block;margin-left:8px;padding:1px 8px;background:#7c3aed;color:#fff;border-radius:10px;font-size:10px;font-weight:bold;vertical-align:middle;">⏳ 剩余 ${leftStr}</span>`;
} else if (g.type === 'duration' && data.active_week_effect) {
// active_week_effect 是 effectKey 字符串,从 items 列表反查对应商品名称
const effKey = data.active_week_effect;
const effItem = data.items.find(i => i.type === 'duration' && i.slug.includes(effKey));
const effName = effItem ? effItem.name : effKey;
groupSuffix =
` <span style="display:inline-block;margin-left:8px;padding:1px 8px;background:#16a34a;color:#fff;border-radius:10px;font-size:10px;font-weight:bold;vertical-align:middle;">✅ 已激活:${effName}</span>`;
} else if (g.type === 'tools' && (data.sign_repair_card_count || 0) > 0) {
groupSuffix =
` <span style="display:inline-block;margin-left:8px;padding:1px 8px;background:#0f766e;color:#fff;border-radius:10px;font-size:10px;font-weight:bold;vertical-align:middle;">🎫 可用 ${data.sign_repair_card_count} 张</span>`;
}
header.innerHTML = `${g.label}${groupSuffix}${g.desc ? ` <span>${g.desc}</span>` : ''}`;
list.appendChild(header);
items.forEach(item => {
const isRename = item.slug === 'rename_card';
const canUse = isRename && data.has_rename_card;
const isRing = item.type === 'ring';
const ownedQty = isRing ? (ringCounts[item.id] || 0) : 0;
const card = document.createElement('div');
card.className = 'shop-card';
// 顶部:图标 + 名称(戒指加持有数徽章,其余正常显示)
const isAutoFishing = item.type === 'auto_fishing';
let iconHtml;
if (isRing && ownedQty > 0) {
iconHtml = `<span style="position:relative;display:inline-block;">
<span class="shop-card-icon">${item.icon}</span>
<span style="position:absolute;top:-4px;right:-6px;background:#f43f5e;color:#fff;font-size:9px;font-weight:800;min-width:15px;height:15px;border-radius:8px;text-align:center;line-height:15px;padding:0 2px;">${ownedQty}</span>
</span>`;
} else {
iconHtml = `<span class="shop-card-icon">${item.icon}</span>`;
}
const durationLabel = isAutoFishing && item.duration_minutes > 0 ?
`<div style="font-size:9px;margin-top:3px;color:#7c3aed;">⏱ 有效期 ${item.duration_minutes >= 60 ? Math.floor(item.duration_minutes / 60) + ' 小时' : item.duration_minutes + ' 分钟'}</div>` :
'';
card.innerHTML = `
<div class="shop-card-top">
${iconHtml}
<span class="shop-card-name">${item.name}</span>
</div>
<div class="shop-card-desc">${item.description ?? ''}</div>
${isRing && (item.intimacy_bonus > 0 || item.charm_bonus > 0) ? `
<div style="font-size:9px;margin-top:3px;display:flex;gap:8px;">
${item.intimacy_bonus > 0 ? `<span style="color:#f43f5e;">💞 亲密 +${item.intimacy_bonus}</span>` : ''}
${item.charm_bonus > 0 ? `<span style="color:#a855f7;">✨ 魅力 +${item.charm_bonus}</span>` : ''}
</div>` : ''}
${durationLabel}
`;
// 按钮
const btn = document.createElement('button');
if (canUse) {
btn.className = 'shop-btn shop-btn-use';
btn.textContent = '✦ 使用改名卡';
btn.onclick = openRenameModal;
} else if (item.type === 'instant') {
// 单次卡:打开送礼弹框
btn.className = 'shop-btn';
btn.innerHTML = `💰 ${Number(item.price).toLocaleString()}`;
btn.onclick = () => openGiftDialog(item);
} else {
// 周卡、道具、戒指、自动钓鱼卡:弹确认窗口再购买
btn.className = 'shop-btn';
btn.innerHTML = `💰 ${Number(item.price).toLocaleString()}`;
btn.onclick = async () => {
let quantity = 1;
if (item.type === 'sign_repair') {
quantity = await window.promptSignRepairQuantity?.(item);
if (quantity === null || quantity === undefined) return;
}
const confirmMsg =
`确认花费 💰 ${Number(item.price * quantity).toLocaleString()} 金币购买\n【${item.name}】${quantity > 1 ? ' × ' + quantity : ''} 吗?`;
const ok = await window.chatDialog.confirm(confirmMsg, '确认购买');
if (ok) buyItem(item.id, item.name, item.price, 'all', '', quantity);
};
}
card.appendChild(btn);
list.appendChild(card);
});
});
}
/**
* 打开送礼弹框(仅单次特效卡)
* 让用户填写:送给谁 + 说一句话
*/
let _giftItem = null;
window.openGiftDialog = function(item) {
_giftItem = item;
// 重置内容
document.getElementById('gift-recipient').value = '';
document.getElementById('gift-message').value = '';
document.getElementById('gift-err').textContent = '';
document.getElementById('gift-item-name').textContent =
`${item.icon} ${item.name}(💰 ${Number(item.price).toLocaleString()}`;
document.getElementById('gift-dialog').style.display = 'flex';
};
window.closeGiftDialog = function() {
document.getElementById('gift-dialog').style.display = 'none';
_giftItem = null;
};
/** 送礼确认,提交购买 */
window.confirmGift = function() {
if (!_giftItem) return;
const recipient = document.getElementById('gift-recipient').value.trim();
const message = document.getElementById('gift-message').value.trim();
document.getElementById('gift-err').textContent = '';
// 先将商品数据保存到局部变量,再关闭弹框(closeGiftDialog 会把 _giftItem 设为 null
const item = _giftItem;
closeGiftDialog();
buyItem(item.id, item.name, item.price, recipient, message);
};
/** 购买商品(最终执行) */
window.buyItem = function(itemId, name, price, recipient, message, quantity = 1) {
const roomId = window.chatContext?.roomId ?? 0;
fetch('{{ route('shop.buy') }}', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRF-TOKEN': _csrf()
},
body: JSON.stringify({
item_id: itemId,
recipient: recipient || 'all',
message: message || '',
quantity: quantity || 1,
room_id: roomId,
}),
})
.then(r => r.json())
.then(data => {
if (data.status === 'success') {
// 更新金币
if (data.jjb !== undefined)
document.getElementById('shop-jjb').textContent = Number(data.jjb)
.toLocaleString();
// 购买成功提示
showShopToast(`✅ ${name} 购买成功!`, true);
// 播放本地特效(购买者自己必须也能看到)
if (data.play_effect && window.EffectManager) {
window.EffectManager.play(data.play_effect);
}
// 延迟刷新商品数据(保持商店开着让用户看到状态更新)
shopLoaded = false;
setTimeout(() => {
fetchShopData();
shopLoaded = true;
}, 1000);
} else {
showShopToast(data.message, false);
}
})
.catch(() => showShopToast('⚠ 网络异常,请重试', false));
};
/** Toast 通知 */
window.showShopToast = function(msg, ok) {
const el = document.getElementById('shop-toast');
el.textContent = msg;
el.style.display = 'block';
el.style.background = ok ? '#064e3b' : '#7f1d1d';
el.style.color = ok ? '#6ee7b7' : '#fca5a5';
clearTimeout(el._t);
el._t = setTimeout(() => {
el.style.display = 'none';
}, 3500);
};
/** 打开改名框 */
window.openRenameModal = function() {
const m = document.getElementById('shop-rename-overlay');
m.style.display = 'flex';
document.getElementById('rename-input').focus();
document.getElementById('rename-err').textContent = '';
};
/** 关闭改名框 */
window.closeRenameModal = function() {
document.getElementById('shop-rename-overlay').style.display = 'none';
};
/** 提交改名 */
window.submitRename = function() {
const newName = document.getElementById('rename-input').value.trim();
if (!newName) {
document.getElementById('rename-err').textContent = '请输入新昵称';
return;
}
fetch('{{ route('shop.rename') }}', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRF-TOKEN': _csrf()
},
body: JSON.stringify({
new_name: newName
}),
})
.then(r => r.json())
.then(data => {
if (data.status === 'success') {
closeRenameModal();
showShopToast(data.message, true);
shopLoaded = false;
setTimeout(() => window.location.reload(), 2000);
} else {
document.getElementById('rename-err').textContent = data.message;
}
})
.catch(() => {
document.getElementById('rename-err').textContent = '网络异常,请重试';
});
};
function _csrf() {
return document.querySelector('meta[name="csrf-token"]')?.content ?? '';
}
})();
</script>
{{-- 商店弹窗业务脚本已迁移到 resources/js/chat-room/shop-controls.js --}}
{{-- ═══════════ 会员中心弹窗 ═══════════ --}}
<style>