Files
ai_dianshang/miniprogram/pages/coupon/coupon-center/index.js

173 lines
4.5 KiB
JavaScript
Raw Normal View History

2025-11-17 13:32:54 +08:00
import { request } from '../../../services/_utils/request';
Page({
data: {
availableCoupons: [], // 可领取的优惠券列表
loading: false,
refreshing: false,
},
onLoad() {
this.fetchAvailableCoupons();
},
onShow() {
// 页面显示时刷新数据,以防用户已领取某些优惠券
this.fetchAvailableCoupons();
},
// 刷新数据
onRefresh() {
this.setData({ refreshing: true });
this.fetchAvailableCoupons().finally(() => {
this.setData({ refreshing: false });
});
},
// 获取可领取优惠券列表
async fetchAvailableCoupons() {
try {
this.setData({ loading: true });
const response = await request({
url: '/coupons',
method: 'GET'
});
const coupons = response.data || [];
const formattedCoupons = this.formatCoupons(coupons);
this.setData({
availableCoupons: formattedCoupons,
loading: false
});
} catch (error) {
console.error('获取可领取优惠券失败:', error);
this.setData({ loading: false });
wx.showToast({
title: '获取优惠券失败',
icon: 'none'
});
}
},
// 格式化优惠券数据
formatCoupons(coupons) {
return coupons.map(coupon => {
return {
id: coupon.id,
name: coupon.name,
type: coupon.type,
value: coupon.value,
minAmount: coupon.min_amount,
desc: this.getCouponDesc(coupon),
timeLimit: this.formatTimeLimit(coupon.start_time, coupon.end_time),
status: 'default', // 可领取状态
totalCount: coupon.total_count,
usedCount: coupon.used_count,
remainingCount: coupon.total_count > 0 ? coupon.total_count - coupon.used_count : -1,
isReceived: coupon.is_received || false // 是否已领取
};
});
},
// 获取优惠券描述
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 || '优惠券';
},
// 格式化时间限制
formatTimeLimit(startTime, endTime) {
const start = new Date(startTime);
const end = new Date(endTime);
const formatDate = (date) => {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}.${month}.${day}`;
};
return `${formatDate(start)} - ${formatDate(end)}`;
},
// 领取优惠券
async receiveCoupon(e) {
const { couponid } = e.currentTarget.dataset;
if (!couponid) return;
// 检查优惠券是否还有库存
const coupon = this.data.availableCoupons.find(c => c.id == couponid);
if (!coupon || coupon.remainingCount === 0) {
wx.showToast({
title: '优惠券已抢完',
icon: 'none'
});
return;
}
// 检查是否已领取
if (coupon.isReceived) {
wx.showToast({
title: '您已领取过该优惠券',
icon: 'none'
});
return;
}
try {
wx.showLoading({ title: '领取中...' });
const response = await request({
url: `/coupons/${couponid}/receive`,
method: 'POST'
});
wx.hideLoading();
wx.showToast({
title: '领取成功',
icon: 'success'
});
// 设置刷新标识,确保返回其他页面时能刷新优惠券数据
wx.setStorageSync('shouldRefreshCoupons', true);
// 重新获取优惠券列表
this.fetchAvailableCoupons();
} catch (error) {
wx.hideLoading();
console.error('领取优惠券失败:', error);
wx.showToast({
title: error.message || '领取失败,请重试',
icon: 'none'
});
}
},
// 下拉刷新
onPullDownRefresh() {
this.setData({ refreshing: true });
this.fetchAvailableCoupons().finally(() => {
this.setData({ refreshing: false });
wx.stopPullDownRefresh();
});
},
// 查看优惠券详情
viewCouponDetail(e) {
const { couponid } = e.currentTarget.dataset;
wx.navigateTo({
url: `/pages/coupon/coupon-detail/index?id=${couponid}`
});
},
});