刘帅
2026-09-29 8a89ba02db5c19db669a5cf9bb7d443223bdfb71
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
package com.dsh.activity.service.impl;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dsh.activity.entity.*;
import com.dsh.activity.feignclient.account.AppUserClient;
import com.dsh.activity.feignclient.account.StudentClient;
import com.dsh.activity.feignclient.account.model.AppUser;
import com.dsh.activity.feignclient.course.CoursePackageClient;
import com.dsh.activity.feignclient.course.model.CoursePackage;
import com.dsh.activity.feignclient.other.SiteClient;
import com.dsh.activity.feignclient.other.StoreClient;
import com.dsh.activity.feignclient.other.model.Site;
import com.dsh.activity.feignclient.other.model.StoreDetailOfCourse;
import com.dsh.activity.mapper.*;
import com.dsh.activity.model.ConponJsonRuleModel;
import com.dsh.activity.model.CouponDeductionQuery;
import com.dsh.activity.model.CouponDeductionVO;
import com.dsh.activity.model.CouponListVo;
import com.dsh.activity.model.request.CouponPackageReq;
import com.dsh.activity.model.response.CouponPackageResp;
import com.dsh.activity.service.UserCouponService;
import com.dsh.activity.util.DateUtil;
import com.dsh.activity.util.GDMapGeocodingUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
 
/**
 * <p>
 * 用户优惠券领取记录 服务实现类
 * </p>
 *
 * @author jqs
 * @since 2023-06-29
 */
@Service
public class UserCouponServiceImpl extends ServiceImpl<UserCouponMapper, UserCoupon> implements UserCouponService {
 
    private static final Logger LOGGER = LoggerFactory.getLogger(UserCouponServiceImpl.class);
 
    @Resource
    private CoursePackageClient coursePackageClient;
 
    @Autowired
    private GDMapGeocodingUtil gdMapGeocodingUtil;
    @Autowired
    private PointsMerchandiseMapper pointsMerchandiseMapper;
 
    @Resource
    private AppUserClient appClient;
 
    @Resource
    private StudentClient studentClient;
 
    @Resource
    private CouponMapper couponMapper;
 
    @Resource
    private CouponCityMapper couponCityMapper;
 
    @Resource
    private StoreClient storeClient;
 
    @Resource
    private CouponStoreMapper csMapper;
 
    @Resource
    private SiteClient siteClient;
 
    /**
     * 批量解析已核销优惠券的固定抵扣金额,避免统计页面逐条远程查询优惠券。
     *
     * @param query 用户优惠券领取记录 ID 集合
     * @return 每条领取记录对应的抵扣金额;无固定抵扣规则时返回 0
     */
    @Override
    public List<CouponDeductionVO> queryDeductionAmounts(CouponDeductionQuery query) {
        if (query == null || query.getUserCouponIds() == null || query.getUserCouponIds().isEmpty()) {
            return Collections.emptyList();
        }
 
        Set<Long> userCouponIds = new LinkedHashSet<>(query.getUserCouponIds());
        List<UserCoupon> userCoupons = this.list(new QueryWrapper<UserCoupon>()
                .in("id", userCouponIds));
        if (userCoupons.isEmpty()) {
            return Collections.emptyList();
        }
 
        Set<Integer> couponIds = userCoupons.stream()
                .map(UserCoupon::getCouponId)
                .filter(java.util.Objects::nonNull)
                .collect(Collectors.toSet());
        List<Coupon> coupons = couponIds.isEmpty()
                ? Collections.emptyList()
                : couponMapper.selectBatchIds(couponIds);
        Map<Integer, Coupon> couponMap = coupons.stream()
                .collect(Collectors.toMap(Coupon::getId, coupon -> coupon));
 
        List<CouponDeductionVO> result = new ArrayList<>();
        for (UserCoupon userCoupon : userCoupons) {
            CouponDeductionVO deduction = new CouponDeductionVO();
            deduction.setUserCouponId(userCoupon.getId());
            deduction.setDeductionAmount(getCouponDeductionAmount(couponMap.get(userCoupon.getCouponId())));
            result.add(deduction);
        }
        return result;
    }
 
    /** 解析优惠券规则中的固定抵扣金额。 */
    private BigDecimal getCouponDeductionAmount(Coupon coupon) {
        if (coupon == null || coupon.getContent() == null) {
            return BigDecimal.ZERO;
        }
        try {
            JSONObject content = JSON.parseObject(coupon.getContent());
            // 满减券使用 deductionAmount,代金券历史规则将抵扣额存放在 conditionalAmount。
            BigDecimal deductionAmount = Integer.valueOf(2).equals(coupon.getType())
                    ? content.getBigDecimal("conditionalAmount")
                    : content.getBigDecimal("deductionAmount");
            return deductionAmount == null ? BigDecimal.ZERO : deductionAmount.max(BigDecimal.ZERO);
        } catch (Exception e) {
            LOGGER.warn("解析优惠券抵扣规则失败,couponId={}", coupon.getId(), e);
            return BigDecimal.ZERO;
        }
    }
 
 
    /**
     * 获取购买课程可用优惠券列表
     *
     * @param uid
     * @param coursePackageId
     * @return
     */
    @Override
    public List<CouponListVo> queryAvailableCouponList(Integer uid, Integer coursePackageId, Double price, String lon, String lat) throws Exception {
        CoursePackage coursePackage = coursePackageClient.queryCoursePackageById(coursePackageId);
        Integer storeId = coursePackage.getStoreId();
        Map<String, String> geocode = gdMapGeocodingUtil.geocode(lon, lat);
        String provinceCode = geocode.get("provinceCode");
        String cityCode = geocode.get("cityCode");
        List<Map<String, Object>> userCoupons = this.baseMapper.queryAvailableCouponList(uid, storeId, provinceCode, cityCode);
        List<CouponListVo> listVos = new ArrayList<>();
        for (Map<String, Object> userCoupon : userCoupons) {
            Integer type = Integer.valueOf(userCoupon.get("type").toString());
            // 支付减免只支持满减券和代金券;体验券/抵扣券不能用于订单金额计算。
            if (type != 1 && type != 2) {
                continue;
            }
            CouponListVo couponListVo = new CouponListVo();
            couponListVo.setId(Long.valueOf(userCoupon.get("id").toString()));
            couponListVo.setName(userCoupon.get("name").toString());
            couponListVo.setType(type);
            couponListVo.setEffectiveTime(userCoupon.get("endTime").toString());
            String content = userCoupon.get("content").toString();
            if (type == 1) {//满减{"num1":1,"num2":1}
                JSONObject jsonObject = JSON.parseObject(content);
                Double num1 = jsonObject.getDouble("conditionalAmount");
                if (price.compareTo(num1) < 0) {
                    continue;
                }
                couponListVo.setUseCondition("满¥" + num1 + "元可用");
                couponListVo.setFavorable(jsonObject.getString("deductionAmount"));
            }
            if (type == 2) {//代金券{"num1":1}
                JSONObject jsonObject = JSON.parseObject(content);
                Double num1 = jsonObject.getDouble("conditionalAmount");
                if (num1 == null) {
                    num1 = 0d;
                }
                if (price.compareTo(num1) < 0) {
                    continue;
                }
                couponListVo.setUseCondition("");
                couponListVo.setFavorable(num1 + "");
            }
            if (type == 3) {//体验券{"num1":1}
                JSONObject jsonObject = JSON.parseObject(content);
                couponListVo.setUseCondition("");
                couponListVo.setFavorable(jsonObject.getString("experienceName"));
            }
            listVos.add(couponListVo);
        }
        return listVos;
    }
 
 
    /**
     * 获取预约场地可用优惠券列表
     *
     * @param siteId
     * @param price
     * @return
     * @throws Exception
     */
    @Override
    public List<CouponListVo> querySiteCouponList(Integer uid, Integer siteId, Double price, String lon, String lat) throws Exception {
        Site site = siteClient.querySiteById(siteId);
        return queryStoreCouponList(uid, site.getStoreId(), price, lon, lat);
    }
 
    @Override
    public List<CouponListVo> queryStoreCouponList(Integer uid, Integer storeId, Double price, String lon, String lat) throws Exception {
        Map<String, String> geocode = gdMapGeocodingUtil.geocode(lon, lat);
        String provinceCode = geocode.get("provinceCode");
        String cityCode = geocode.get("cityCode");
        List<Map<String, Object>> userCoupons = this.baseMapper.queryAvailableCouponList(uid, storeId, provinceCode, cityCode);
        List<CouponListVo> listVos = new ArrayList<>();
        for (Map<String, Object> userCoupon : userCoupons) {
            Integer type = Integer.valueOf(userCoupon.get("type").toString());
            if (type != 1 && type != 2) {
                continue;
            }
            CouponListVo couponListVo = new CouponListVo();
            couponListVo.setId(Long.valueOf(userCoupon.get("id").toString()));
            couponListVo.setName(userCoupon.get("name").toString());
            couponListVo.setType(type);
            couponListVo.setEffectiveTime(userCoupon.get("endTime").toString());
            String content = userCoupon.get("content").toString();
            BigDecimal orderAmount = BigDecimal.valueOf(price == null ? 0D : price).max(BigDecimal.ZERO);
            if (type == 1) {//满减{"num1":1,"num2":1}
                JSONObject jsonObject = JSON.parseObject(content);
                Double num1 = jsonObject.getDouble("conditionalAmount");
                if (price.compareTo(num1) < 0) {
                    continue;
                }
                couponListVo.setUseCondition("满" + num1 + "元可用");
                couponListVo.setFavorable(jsonObject.getString("deductionAmount"));
                BigDecimal discount = BigDecimal.valueOf(jsonObject.getDouble("deductionAmount"))
                        .min(orderAmount);
                couponListVo.setDiscountAmount(discount);
                couponListVo.setPayableAmount(orderAmount.subtract(discount));
            }
            if (type == 2) {//代金券{"num1":1}
                JSONObject jsonObject = JSON.parseObject(content);
                Double num1 = jsonObject.getDouble("conditionalAmount");
                if (num1 == null) {
                    num1 = 0d;
                }
                // 代金券可全额抵扣,面额超过订单金额时按订单金额抵扣,不应从列表中剔除。
                couponListVo.setUseCondition("");
                couponListVo.setFavorable(num1 + "");
                BigDecimal discount = BigDecimal.valueOf(num1).max(BigDecimal.ZERO).min(orderAmount);
                couponListVo.setDiscountAmount(discount);
                couponListVo.setPayableAmount(orderAmount.subtract(discount));
            }
            if (type == 3) {//体验券{"num1":1}
                JSONObject jsonObject = JSON.parseObject(content);
                couponListVo.setUseCondition("");
                couponListVo.setFavorable(jsonObject.getString("experienceName"));
            }
            listVos.add(couponListVo);
        }
        return listVos;
    }
 
    @Override
    public List<CouponPackageResp> queryCouponPackagesList(Integer uid, CouponPackageReq req) {
        List<CouponPackageResp> respList = new ArrayList<>();
        AppUser appUser = appClient.queryAppUser(uid);
        if (null != appUser) {
            List<UserCoupon> userCoupons = this.baseMapper.selectList(new QueryWrapper<UserCoupon>()
                    .eq("userId", appUser.getId())
                    .orderByDesc("insertTime"));
            if (userCoupons.size() > 0) {
                for (UserCoupon userCoupon : userCoupons) {
                    Coupon coupon = couponMapper.selectById(userCoupon.getCouponId());
                    CouponPackageResp packageResp = new CouponPackageResp();
                    packageResp.setId(coupon.getId());
                    packageResp.setName(coupon.getName());
                    packageResp.setType(coupon.getType());
                    packageResp.setUseCondition(coupon.getUseScope());
                    switch (coupon.getUseScope()) {
                        case 1:
                            packageResp.setAvailable("全国通用");
                            break;
                        case 2:
                            packageResp.setAvailable("指定城市可用");
                            List<CouponCity> couponId = couponCityMapper.selectList(new QueryWrapper<CouponCity>().eq("couponId", coupon.getId()));
                            StringBuilder stringBuilder = new StringBuilder();
                            for (CouponCity couponCity : couponId) {
                                stringBuilder.append(couponCity.getCity());
                            }
                            packageResp.setCityOrStore(String.valueOf(stringBuilder));
                            break;
                        case 3:
                            packageResp.setAvailable("指定门店可用");
                            CouponStore couponStore = csMapper.selectOne(new QueryWrapper<CouponStore>()
                                    .eq("couponId", coupon.getId()).last("limit 1"));
                            StoreDetailOfCourse courseOfStore = storeClient.getCourseOfStore(couponStore.getStoreId());
//                            packageResp.setCityOrStore(courseOfStore.getStoreName()+","+courseOfStore.getStoreAddr());
                            packageResp.setCityOrStore(courseOfStore.getStoreName());
                            break;
                        default:
                            break;
                    }
                    packageResp.setInstructionsForUse(coupon.getIllustrate());
                    ConponJsonRuleModel ruleModel = new ConponJsonRuleModel();
                    JSONObject jsonObject = JSON.parseObject(coupon.getContent());
                    switch (coupon.getType()) {
                        case 1:
//                        {"conditionalAmount":50,"deductionAmount":10,"experienceName":""}
//                            满减券
                            Double num1 = jsonObject.getDouble("conditionalAmount");
                            Double num2 = jsonObject.getDouble("deductionAmount");
                            ruleModel.setConditionalAmount("满" + num1 + "可用");
                            ruleModel.setDeductionAmount("¥ " + num2);
                            ruleModel.setExperienceName("");
                            break;
                        case 2:
//                            代金券
                            Double jsonObjectDouble = jsonObject.getDouble("conditionalAmount");
                            ruleModel.setConditionalAmount("");
                            ruleModel.setDeductionAmount("¥ " + jsonObjectDouble);
                            ruleModel.setExperienceName("");
                            break;
                        case 3:
//                            体验券
                            ruleModel.setConditionalAmount("");
                            ruleModel.setDeductionAmount("");
                            ruleModel.setExperienceName(jsonObject.getString("experienceName"));
                            break;
                            case 4:
//                            抵扣券
                                Integer goodsId = coupon.getGoodsId();
                                PointsMerchandise pointsMerchandise = pointsMerchandiseMapper.selectById(goodsId);
                                ruleModel.setConditionalAmount("");
                            ruleModel.setDeductionAmount("");
                            ruleModel.setExperienceName(pointsMerchandise.getName());
                            break;
                        default:
                            break;
                    }
                    packageResp.setRuleModel(ruleModel);
 
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    packageResp.setEffectiveTime(simpleDateFormat.format(coupon.getEndTime()));
 
                    if (userCoupon.getStatus() == 1) {
                        if (DateUtil.getDate().before(coupon.getEndTime())) {
                            packageResp.setUseStatus(1);
                        } else {
                            packageResp.setUseStatus(3);
                        }
                    }
                    if (userCoupon.getStatus() == 2) {
                        packageResp.setUseStatus(2);
                    }
                    if (userCoupon.getStatus() == 3) {
                        packageResp.setUseStatus(3);
                    }
                    respList.add(packageResp);
                }
                if (null != req.getCouponType()) {
                    respList = respList.stream()
                            .filter(couponPackageResp -> couponPackageResp.getType().equals(req.getCouponType()))
                            .collect(Collectors.toList());
                }
                if (null != req.getUseStatus()) {
                    respList = respList.stream()
                            .filter(couponPackageResp -> couponPackageResp.getUseStatus().equals(req.getUseStatus()))
                            .collect(Collectors.toList());
                }
            }
 
        }
        return respList;
    }
 
}