init
This commit is contained in:
345
miniprogram/pages/coupon/coupon-center/index-browser.js
Normal file
345
miniprogram/pages/coupon/coupon-center/index-browser.js
Normal file
@@ -0,0 +1,345 @@
|
||||
// 浏览器环境下的优惠券中心页面逻辑
|
||||
|
||||
// API配置
|
||||
const API_CONFIG = {
|
||||
// 生产环境
|
||||
production: 'https://tral.cc/api/v1',
|
||||
// 开发环境
|
||||
development: 'http://localhost:8080/api/v1'
|
||||
};
|
||||
|
||||
// 当前环境 - 根据域名自动判断
|
||||
const CURRENT_ENV = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1'
|
||||
? 'development'
|
||||
: 'production';
|
||||
|
||||
const config = {
|
||||
apiBase: API_CONFIG[CURRENT_ENV]
|
||||
};
|
||||
|
||||
// 模拟请求函数
|
||||
async function request(options) {
|
||||
const { url, method = 'GET', data } = options;
|
||||
const fullUrl = config.apiBase + url;
|
||||
|
||||
try {
|
||||
const response = await fetch(fullUrl, {
|
||||
method,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': localStorage.getItem('token') || ''
|
||||
},
|
||||
body: data ? JSON.stringify(data) : undefined
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.error('请求失败:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// 页面数据
|
||||
let pageData = {
|
||||
availableCoupons: [],
|
||||
loading: false
|
||||
};
|
||||
|
||||
// 页面初始化
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
// 设置测试用的JWT token
|
||||
const testToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE3NjEwMzE0ODQsImlhdCI6MTc2MDk0NTA4NH0.JAi7VnVTsA-qPegR9DCINr1nISrxakaQxf6aY4EZykU';
|
||||
localStorage.setItem('token', testToken);
|
||||
|
||||
fetchAvailableCoupons();
|
||||
});
|
||||
|
||||
// 获取可领取优惠券列表
|
||||
async function fetchAvailableCoupons() {
|
||||
try {
|
||||
setLoading(true);
|
||||
|
||||
// 调用真实API获取优惠券数据
|
||||
const response = await request({
|
||||
url: '/coupons',
|
||||
method: 'GET'
|
||||
});
|
||||
|
||||
const coupons = response.data || [];
|
||||
const formattedCoupons = formatCoupons(coupons);
|
||||
pageData.availableCoupons = formattedCoupons;
|
||||
|
||||
renderCouponList(formattedCoupons);
|
||||
setLoading(false);
|
||||
} catch (error) {
|
||||
console.error('获取可领取优惠券失败:', error);
|
||||
setLoading(false);
|
||||
showToast('获取优惠券失败,请稍后重试');
|
||||
}
|
||||
}
|
||||
|
||||
// 格式化优惠券数据
|
||||
function formatCoupons(coupons) {
|
||||
return coupons.map(coupon => {
|
||||
const remainingCount = coupon.total_count > 0 ? coupon.total_count - coupon.used_count : -1;
|
||||
|
||||
return {
|
||||
id: coupon.id,
|
||||
name: coupon.name,
|
||||
type: coupon.type,
|
||||
value: coupon.value,
|
||||
minAmount: coupon.min_amount,
|
||||
desc: getCouponDesc(coupon),
|
||||
timeLimit: formatTimeLimit(coupon.start_time, coupon.end_time),
|
||||
status: 'default',
|
||||
totalCount: coupon.total_count,
|
||||
usedCount: coupon.used_count,
|
||||
remainingCount: remainingCount
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// 获取优惠券描述
|
||||
function getCouponDesc(coupon) {
|
||||
if (coupon.type === 1) { // 满减券
|
||||
if (coupon.min_amount > 0) {
|
||||
return `满${(coupon.min_amount / 100).toFixed(0)}元减${(coupon.value / 100).toFixed(0)}元`;
|
||||
}
|
||||
return `立减${(coupon.value / 100).toFixed(0)}元`;
|
||||
} else if (coupon.type === 2) { // 折扣券
|
||||
return `${coupon.value / 10}折`;
|
||||
} else if (coupon.type === 3) { // 免邮券
|
||||
return '免运费';
|
||||
}
|
||||
return coupon.description || '优惠券';
|
||||
}
|
||||
|
||||
// 格式化时间限制
|
||||
function formatTimeLimit(startTime, endTime) {
|
||||
return `${startTime} - ${endTime}`;
|
||||
}
|
||||
|
||||
// 渲染优惠券列表
|
||||
function renderCouponList(coupons) {
|
||||
const couponListElement = document.getElementById('couponList');
|
||||
const emptyStateElement = document.getElementById('emptyState');
|
||||
|
||||
if (!coupons || coupons.length === 0) {
|
||||
couponListElement.innerHTML = '';
|
||||
emptyStateElement.style.display = 'flex';
|
||||
return;
|
||||
}
|
||||
|
||||
emptyStateElement.style.display = 'none';
|
||||
|
||||
const couponHTML = coupons.map(coupon => {
|
||||
const valueDisplay = coupon.type === 1
|
||||
? `<span class="value-number">${coupon.value / 100}</span><span class="value-unit">元</span>`
|
||||
: coupon.type === 2
|
||||
? `<span class="value-number">${coupon.value / 10}</span><span class="value-unit">折</span>`
|
||||
: `<span class="value-text">免邮</span>`;
|
||||
|
||||
const stockText = coupon.remainingCount > 0
|
||||
? `剩余 ${coupon.remainingCount} 张`
|
||||
: '已抢完';
|
||||
|
||||
const isDisabled = coupon.remainingCount === 0;
|
||||
|
||||
return `
|
||||
<div class="coupon-item">
|
||||
<div class="coupon-card">
|
||||
<div class="coupon-main">
|
||||
<div class="coupon-left">
|
||||
<div class="coupon-value">
|
||||
${valueDisplay}
|
||||
</div>
|
||||
<div class="coupon-desc">${coupon.desc}</div>
|
||||
</div>
|
||||
|
||||
<div class="coupon-right">
|
||||
<div class="coupon-name">${coupon.name}</div>
|
||||
<div class="coupon-time">${coupon.timeLimit}</div>
|
||||
<div class="coupon-stock">${stockText}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="coupon-action">
|
||||
<button class="receive-btn ${isDisabled ? 'disabled' : ''}"
|
||||
data-coupon-id="${coupon.id}"
|
||||
${isDisabled ? 'disabled' : ''}>
|
||||
${isDisabled ? '已抢完' : '立即领取'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
couponListElement.innerHTML = couponHTML;
|
||||
|
||||
// 添加事件委托处理按钮点击
|
||||
couponListElement.removeEventListener('click', handleCouponListClick);
|
||||
couponListElement.addEventListener('click', handleCouponListClick);
|
||||
}
|
||||
|
||||
// 处理优惠券列表点击事件
|
||||
function handleCouponListClick(event) {
|
||||
const target = event.target;
|
||||
|
||||
// 检查是否点击了领取按钮
|
||||
if (target.classList.contains('receive-btn') && !target.disabled) {
|
||||
const couponId = target.getAttribute('data-coupon-id');
|
||||
if (couponId) {
|
||||
receiveCoupon(event, parseInt(couponId));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 领取优惠券
|
||||
async function receiveCoupon(event, couponId) {
|
||||
// 阻止事件冒泡和默认行为
|
||||
if (event) {
|
||||
event.stopPropagation();
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
}
|
||||
|
||||
if (!couponId) return;
|
||||
|
||||
// 检查优惠券是否还有库存
|
||||
const coupon = pageData.availableCoupons.find(c => c.id == couponId);
|
||||
if (!coupon || coupon.remainingCount === 0) {
|
||||
showToast('优惠券已抢完', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
// 防止重复点击
|
||||
const button = event.target;
|
||||
if (button.disabled) return;
|
||||
|
||||
button.disabled = true;
|
||||
button.textContent = '领取中...';
|
||||
|
||||
try {
|
||||
showLoading('正在领取优惠券...');
|
||||
|
||||
const response = await request({
|
||||
url: `/coupons/${couponId}/receive`,
|
||||
method: 'POST'
|
||||
});
|
||||
console.log('优惠券领取成功:', response);
|
||||
|
||||
hideLoading();
|
||||
|
||||
// 显示成功提示
|
||||
showToast(`🎉 ${coupon.name} 领取成功!`, 'success');
|
||||
|
||||
// 重新获取优惠券列表以确保数据同步
|
||||
await fetchAvailableCoupons();
|
||||
|
||||
} catch (error) {
|
||||
hideLoading();
|
||||
console.error('领取优惠券失败:', error);
|
||||
showToast(error.message || '领取失败,请重试', 'error');
|
||||
|
||||
// 重新获取列表以确保状态正确
|
||||
await fetchAvailableCoupons();
|
||||
}
|
||||
}
|
||||
|
||||
// 查看优惠券详情
|
||||
function viewCouponDetail(couponId) {
|
||||
showToast(`查看优惠券详情: ${couponId}`);
|
||||
}
|
||||
|
||||
// 返回
|
||||
function goBack() {
|
||||
if (window.history.length > 1) {
|
||||
window.history.back();
|
||||
} else {
|
||||
showToast('返回上一页');
|
||||
}
|
||||
}
|
||||
|
||||
// 设置加载状态
|
||||
function setLoading(loading) {
|
||||
pageData.loading = loading;
|
||||
const loadingElement = document.getElementById('loadingState');
|
||||
const couponListElement = document.getElementById('couponList');
|
||||
|
||||
if (loading) {
|
||||
loadingElement.style.display = 'flex';
|
||||
couponListElement.style.display = 'none';
|
||||
} else {
|
||||
loadingElement.style.display = 'none';
|
||||
couponListElement.style.display = 'block';
|
||||
}
|
||||
}
|
||||
|
||||
// 显示提示
|
||||
function showToast(message, type = 'info') {
|
||||
// 创建toast元素
|
||||
const toast = document.createElement('div');
|
||||
toast.style.cssText = `
|
||||
position: fixed;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
background: ${type === 'success' ? '#4CAF50' : type === 'error' ? '#f44336' : '#333'};
|
||||
color: white;
|
||||
padding: 12px 24px;
|
||||
border-radius: 4px;
|
||||
z-index: 10000;
|
||||
font-size: 14px;
|
||||
max-width: 80%;
|
||||
text-align: center;
|
||||
`;
|
||||
toast.textContent = message;
|
||||
|
||||
document.body.appendChild(toast);
|
||||
|
||||
setTimeout(() => {
|
||||
document.body.removeChild(toast);
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
// 显示加载中
|
||||
function showLoading(message = '加载中...') {
|
||||
const loading = document.createElement('div');
|
||||
loading.id = 'globalLoading';
|
||||
loading.style.cssText = `
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 10001;
|
||||
color: white;
|
||||
font-size: 16px;
|
||||
`;
|
||||
|
||||
loading.innerHTML = `
|
||||
<div style="width: 40px; height: 40px; border: 3px solid #f3f3f3; border-top: 3px solid #fff; border-radius: 50%; animation: spin 1s linear infinite; margin-bottom: 16px;"></div>
|
||||
<div>${message}</div>
|
||||
`;
|
||||
|
||||
document.body.appendChild(loading);
|
||||
}
|
||||
|
||||
// 隐藏加载中
|
||||
function hideLoading() {
|
||||
const loading = document.getElementById('globalLoading');
|
||||
if (loading) {
|
||||
document.body.removeChild(loading);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user