Pu Zhibing
2025-05-08 41600563b0ee8cfad746c359c4d3971169d1c931
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
package com.ruoyi.other.controller;
import java.math.BigDecimal;
import java.time.LocalDateTime;
 
 
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.account.api.dto.GrantCouponDto;
import com.ruoyi.account.api.feignClient.AppCouponClient;
import com.ruoyi.account.api.feignClient.AppUserClient;
import com.ruoyi.account.api.model.TAppCoupon;
import com.ruoyi.account.api.model.TAppUser;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.dto.AppGoodQuery;
import com.ruoyi.common.core.dto.ExchangeBackDto;
import com.ruoyi.common.core.dto.PointChangeDto;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.BasePage;
import com.ruoyi.common.core.web.page.PageInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.log.enums.OperatorType;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.annotation.Logical;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.order.api.feignClient.OrderClient;
import com.ruoyi.order.api.model.TShoppingOrder;
import com.ruoyi.other.api.domain.TCoupon;
import com.ruoyi.other.api.domain.TGoods;
import com.ruoyi.common.core.dto.ExchangeDto;
import com.ruoyi.other.api.dto.AdvertisingDTO;
import com.ruoyi.other.api.dto.GoodsDTO;
import com.ruoyi.other.service.TActivityService;
import com.ruoyi.other.service.TCouponService;
import com.ruoyi.other.service.TGoodsService;
import com.ruoyi.other.util.RedisLock;
import com.ruoyi.payment.api.feignClient.AliPaymentClient;
import com.ruoyi.payment.api.feignClient.WxPaymentClient;
import com.ruoyi.payment.api.vo.AliPaymentReq;
import com.ruoyi.payment.api.vo.AliPaymentResp;
import com.ruoyi.payment.api.vo.PaymentOrder;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
 
import javax.annotation.Resource;
import javax.swing.*;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
 
/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 无关风月
 * @since 2024-08-06
 */
@RestController
@RequestMapping("/t-goods")
public class TGoodsController {
    @Autowired
    private TGoodsService goodsService;
    @Autowired
    private TActivityService activityService;
    @Resource
    private TokenService tokenService;
    @Resource
    private AppUserClient appUserClient;
    @Resource
    private OrderClient orderClient;
    @Resource
    private AppCouponClient appCouponClient;
    @Resource
    private TCouponService couponService;
    @Resource
    private WxPaymentClient wxPaymentClient;
    @Resource
    private RedisService redisService;
    
    @Autowired
    public RedisTemplate redisTemplate;
 
 
    /**
     * 远程调用 根据商品名称查询商品ids
     * @param name
     * @return
     */
    @PostMapping("/getGoodsIdsByName/{name}")
    public R<List<Integer>> getGoodsIdsByName(@PathVariable("name")String name) {
        List<Integer> collect = goodsService.list(new QueryWrapper<TGoods>()
                .like("name", name)).stream().map(TGoods::getId).collect(Collectors.toList());
        return R.ok(collect);
    }
    
    
    @RequiresPermissions(value = {"/goods/add"}, logical = Logical.OR)
    @PostMapping("/saveGoods")
    @ApiOperation(tags = {"管理后台-商品管理"},value = "商品添加")
    @Log(title = "【商品管理】添加商品", businessType = BusinessType.INSERT)
    public AjaxResult saveActivity(@RequestBody TGoods dto) {
        goodsService.save(dto);
        return AjaxResult.success();
    }
    
    
    
    @RequiresPermissions(value = {"/goods/del"}, logical = Logical.OR)
    @GetMapping("/delete")
    @ApiOperation(tags = {"管理后台-商品管理"},value = "商品删除")
    @Log(title = "【商品管理】删除商品", businessType = BusinessType.DELETE)
    public AjaxResult delete(String ids) {
        goodsService.removeBatchByIds(Arrays.asList(ids.split(",")));
        return AjaxResult.success();
    }
    
    
    
    @RequiresPermissions(value = {"/goods/update"}, logical = Logical.OR)
    @PostMapping("/updateVip")
    @ApiOperation(tags = {"管理后台-商品管理"},value = "商品修改")
    @Log(title = "【商品管理】修改商品", businessType = BusinessType.UPDATE)
    public AjaxResult updateActivity(@RequestBody TGoods dto) {
        goodsService.updateById(dto);
        return AjaxResult.success();
    }
    
    
    @RequiresPermissions(value = {"/goods/select"}, logical = Logical.OR)
    @GetMapping("/getInfo")
    @ApiOperation(tags = {"管理后台-商品管理"},value = "商品查看详情")
    public AjaxResult<TGoods> getInfo(Integer id) {
        TGoods byId = goodsService.getById(id);
        return AjaxResult.ok(byId);
    }
    
    
    
    @GetMapping("/getInfoByType")
    @ApiOperation(tags = {"小程序-兑换商城"},value = "商品查看详情")
    public R getInfoByType(Integer goodType,Integer id,Integer type) {
        if (goodType==1){
        TGoods byId = goodsService.getById(id);
        if (byId==null||byId.getStatus()==2){
            return R.fail(2,"该商品已不存在");
        }
//            List<Integer> data = orderClient.getSalesCountByGoodsId(String.valueOf(id)).getData();
//            for (int i = 0; i < list.size(); i++) {
//                list.get(i).setSalesCount(data.get(i));
//            }
            Integer data = orderClient.getSalesCountByGoodsIdgetCount(byId.getId(), 1, type).getData();
            byId.setSalesCount(data);
        return R.ok(byId);
        }
        else {
            TCoupon byId = couponService.getById(id);
            if (byId==null||byId.getStatus()==2){
                return R.fail(2,"该商品已不存在");
            }
            Integer data = orderClient.getSalesCountByGoodsIdgetCount(byId.getId(),2, type).getData();
            byId.setSalesCount(data);
            return R.ok(byId);
            }
    }
    
    
    
    
    @RequiresPermissions(value = {"/goods"}, logical = Logical.OR)
    @ApiOperation(tags = {"管理后台-商品管理"},value = "商品列表分页查询")
    @PostMapping(value = "/pageList")
    public AjaxResult<PageInfo<TGoods>> pageList(@RequestBody GoodsDTO dto) {
        return AjaxResult.ok(goodsService.pageList(dto));
    }
    
    
    @ApiOperation(tags = {"小程序-兑换商城"},value = "商品列表分页查询")
    @PostMapping(value = "/app/pageList")
    public AjaxResult<PageInfo<TGoods>> apppageList(@RequestBody AppGoodQuery appGoodQuery) {
        return AjaxResult.ok(goodsService.pageList1(appGoodQuery));
    }
    
    
    @ApiOperation(tags = {"小程序-兑换商城"},value = "积分兑换商品检查数量")
    @PostMapping(value = "/app/shop/check")
    public R check(@RequestBody ExchangeDto exchangeDto) {
        //检查当前用户积分是否够
        Long userId = tokenService.getLoginUserApplet().getUserId();
        Integer point = 0;
        if (exchangeDto.getGoodType()==1) {
            //查询当前商品信息
            TGoods good = goodsService.getById(exchangeDto.getGoodId());
            point = good.getRedeemPoints();
            //检查当前用户是否到达兑换上限
            Long count = orderClient.getExchangeById(exchangeDto.getGoodId(), userId,exchangeDto.getGoodType()).getData();
            if (good.getLimitExchangeTimes() != -1 && count >= good.getLimitExchangeTimes()) {
                return R.fail("当前用户已兑换"+count+"张");
            }
            TAppUser user = appUserClient.getUserById(userId).getData();
            if (user.getPoints()<good.getRedeemPoints()){
                return R.fail("当前用户积分不足");
            }
        }else {
            TCoupon coupon = couponService.getById(exchangeDto.getGoodId());
            point = coupon.getRedeemPoints();
 
            Long count = orderClient.getExchangeById(exchangeDto.getGoodId(), userId,exchangeDto.getGoodType()).getData();
            if (coupon.getInventoryQuantity() != -1 && count >= coupon.getInventoryQuantity()) {
                return R.fail("当前用户已到达兑换"+coupon+"次");
            }
    }
        return R.ok();
 
    }
    
    
    @Log(title = "【我的】积分兑换商品", businessType = BusinessType.INSERT,operatorType = OperatorType.MOBILE)
    @ApiOperation(tags = {"小程序-兑换商城"},value = "积分兑换商品")
    @PostMapping(value = "/app/shop")
    public AjaxResult<PageInfo<TGoods>> shop(@RequestBody ExchangeDto exchangeDto) {
        //redis锁 和支付使用同一个锁
        RedisLock redisLock = new RedisLock(redisTemplate, "POINT_EXCHANGE_LOCK", 5, 30000);
        try {
            redisLock.lock();
            Long userId = tokenService.getLoginUserApplet().getUserId();
            Integer point = 0;
            TAppUser user = appUserClient.getUserById(userId).getData();
            if (exchangeDto.getGoodType()==1) {
                //查询当前商品信息
                TGoods good = goodsService.getById(exchangeDto.getGoodId());
                point = good.getRedeemPoints();
                if (user.getPoints().compareTo(good.getRedeemPoints()) < 0){
                    return AjaxResult.error("当前用户积分不足");
                }
                //检查当前用户是否到达兑换上限
                Long count = orderClient.getExchangeById(exchangeDto.getGoodId(), userId,exchangeDto.getGoodType()).getData();
                if (good.getLimitExchangeTimes() != -1 && count >= good.getLimitExchangeTimes()) {
                    return AjaxResult.error("当前用户已兑换"+count+"张");
                }else {
                    //减少库存
                    if (good.getInventory()!=-1) {
                        good.setInventory(good.getInventory() - exchangeDto.getNum());
                        goodsService.updateById(good);
                    }
                }
            }else {
                TCoupon coupon = couponService.getById(exchangeDto.getGoodId());
                point = coupon.getRedeemPoints();
                if (user.getPoints().compareTo(coupon.getRedeemPoints()) < 0){
                    return AjaxResult.error("当前用户积分不足");
                }
                Long count = orderClient.getExchangeById(exchangeDto.getGoodId(), userId,exchangeDto.getGoodType()).getData();
                if (coupon.getInventoryQuantity() != -1 && count >= coupon.getInventoryQuantity()) {
                    return AjaxResult.error("当前用户已到达兑换"+coupon+"次");
                }else {
                    if (coupon.getInventoryQuantity()!=-1) {
                        coupon.setInventoryQuantity(coupon.getInventoryQuantity() - 1);
                        couponService.updateById(coupon);
                    }
                }
            }
            exchangeDto.setPoint(point);
            exchangeDto.setUserId(userId);
            //生成积分兑换成功的订单
            R<ExchangeBackDto> longR = orderClient.exchangeCreate(exchangeDto);
            if (exchangeDto.getGoodType()==2) {
                TCoupon coupon = couponService.getById(exchangeDto.getGoodId());
        
                //如果是优惠卷,赠送优惠卷给用户
                GrantCouponDto grantCouponDto = new GrantCouponDto();
                grantCouponDto.setUserIds(userId.toString());
                grantCouponDto.setCouponId(exchangeDto.getGoodId());
                grantCouponDto.setWaysToObtain(1);
                grantCouponDto.setEndTime(LocalDateTime.now());
                grantCouponDto.setType(3);
                switch (coupon.getValidityPeriodMode()){
                    case 1:
                        grantCouponDto.setEndTime(coupon.getEndTime());
                        break;
                    case 2:
                        grantCouponDto.setEndTime(LocalDateTime.now().plusDays(coupon.getDays()));
                        break;
                }
                appCouponClient.grantCoupon(grantCouponDto);
            }
            //生成消耗积分的记录
            PointChangeDto pointChangeDto = new PointChangeDto();
            pointChangeDto.setUserId(userId);
            pointChangeDto.setPoints(point);
            pointChangeDto.setRemark(String.valueOf(longR.getData().getId()));
            pointChangeDto.setType(6);
            pointChangeDto.setCode(longR.getData().getCode());
            appUserClient.changeDown(pointChangeDto);
            return AjaxResult.success(longR.getData().getId());
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //解锁
            redisLock.unlock();
        }
        return AjaxResult.success();
 
    }
 
    @Resource
    private AliPaymentClient aliPaymentClient;
    
    @Log(title = "【我的】支付商品", businessType = BusinessType.UPDATE,operatorType = OperatorType.MOBILE)
    @ApiOperation(tags = {"小程序-现金商城"},value = "支付商品")
    @PostMapping(value = "/app/pay")
    public Object pay(@RequestBody ExchangeDto exchangeDto) {
        Long userId = tokenService.getLoginUserApplet().getUserId();
        TAppUser user = appUserClient.getUserById(userId).getData();
        boolean isVip = false;
        if (user.getVipEndTime()!=null&&user.getVipEndTime().isAfter(LocalDateTime.now())){
            isVip = true;
        }
        //计算价格
        BigDecimal orderPrice = new BigDecimal(0);
        BigDecimal payPrice = new BigDecimal(0);
        BigDecimal discountPrice = new BigDecimal(0);
        BigDecimal vipDiscount = new BigDecimal(0);
        if (exchangeDto.getGoodType()==1){
            TGoods good = goodsService.getById(exchangeDto.getGoodId());
            if (good.getStatus()==2){
                return R.fail("当前商品已下架");
            }
            BigDecimal originalPrice = good.getPreferentialPrice();
            exchangeDto.setTitle("【商品购买】"+good.getName());
            if (isVip){
                if (good.getVipPrice()!=null){
                    vipDiscount = originalPrice.subtract(good.getVipPrice()).multiply(BigDecimal.valueOf(exchangeDto.getNum()));
                    originalPrice = good.getVipPrice();
                }
            }
            orderPrice =  orderPrice.add(originalPrice.multiply(BigDecimal.valueOf(exchangeDto.getNum())));
        }else {
 
            TCoupon coupon = couponService.getById(exchangeDto.getGoodId());
            if (coupon.getStatus()==2){
                return R.fail("当前商品已下架");
            }
            exchangeDto.setTitle("【优惠卷购买】"+coupon.getName());
            BigDecimal originalPrice = coupon.getPaymentAmount();
            if (isVip){
                if (coupon.getVipPaymentAmount()!=null) {
                    vipDiscount = originalPrice.subtract(coupon.getVipPaymentAmount()).multiply(BigDecimal.valueOf(exchangeDto.getNum()));
                    originalPrice = coupon.getVipPaymentAmount();
                }
            }
            orderPrice  = orderPrice.add(originalPrice);
        }
 
        exchangeDto.setOrderPrice(orderPrice);
        //查看是否使用优惠券
        if(exchangeDto.getCouponId()!=null) {
            TAppCoupon appCoupon = appUserClient.couponGetById(exchangeDto.getCouponId()).getData();
            TCoupon coupon = JSON.toJavaObject(JSON.parseObject(appCoupon.getCouponJson()), TCoupon.class);
            if (coupon.getValidityPeriodMode()==1){
                if (orderPrice.compareTo(coupon.getMeetTheConditions())<0){
                    return R.fail("不满足使用优惠券条件");
                }
 
            }
            payPrice = orderPrice.subtract(coupon.getDiscountAmount());
            discountPrice = coupon.getDiscountAmount();
        }else {
            payPrice = orderPrice;
        }
        exchangeDto.setPayPrice(payPrice);
        exchangeDto.setDiscountPrice(discountPrice);
        exchangeDto.setVipDiscount(vipDiscount);
        exchangeDto.setUserId(userId);
        exchangeDto.setPhone(user.getPhone());
        //创建订单
        TShoppingOrder shopOrder = orderClient.shopCreate(exchangeDto).getData();
        if (exchangeDto.getPayMethod()==1) {
            //调起支付
            PaymentOrder paymentOrder = new PaymentOrder();
            paymentOrder.setCode(shopOrder.getCode());
            paymentOrder.setAmount(exchangeDto.getPayPrice());
            paymentOrder.setOpenId(user.getWxOpenid());
            paymentOrder.setDescription("购买商品");
            R<Map<String, Object>> mapR = wxPaymentClient.orderPay(paymentOrder);
            mapR.getData().put("orderId",shopOrder.getId().toString());
            return    mapR;
        }else {
            AliPaymentReq req = new AliPaymentReq();
            req.setOutTradeNo(shopOrder.getCode());
            req.setTotalAmount(shopOrder.getPaymentAmount().toString());
            req.setSubject("购买商品");
            req.setBuyerOpenId(user.getAliOpenid());
            req.setBody("购买商品");
            req.setNotifyUrl("/payment/ali/callBack");
            AliPaymentResp data = aliPaymentClient.payment(req).getData();
            if(null != data){
                data.setOrderId(shopOrder.getId().toString());
                return AjaxResult.success(data);
            }
        }
        return AjaxResult.success();
    }
 
    
    /**
     * 根据id获取商品信息
     * @param id
     * @return
     */
    @PostMapping("/getGoodsById/{id}")
    public R<TGoods> getGoodsById(@PathVariable Integer id){
        TGoods goods = goodsService.getById(id);
        return R.ok(goods);
    }
    
    
    /**
     * 修改商品
     * @param goods
     * @return
     */
    @PostMapping("/updateGoods")
    public R updateGoods(@RequestBody TGoods goods){
        goodsService.updateById(goods);
        return R.ok();
    }
}