xuhy
2024-12-13 a50c7d1497d7f707b79597553d9db978ba7e9dd5
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
435
436
package com.ruoyi.web.controller.api;
 
 
import cn.hutool.http.HttpException;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.BasePage;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.dto.TVideoDto;
import com.ruoyi.system.service.*;
import com.ruoyi.system.vx.WeChatConfig;
import com.ruoyi.system.vx.WeChatUtil;
import com.ruoyi.web.controller.query.CourseQuery;
import com.ruoyi.web.controller.query.DeclareNoticeQuery;
import com.ruoyi.web.controller.query.PayDto;
import com.ruoyi.web.controller.query.VideoAddDto;
import com.ruoyi.web.controller.tool.AlipayTradePagePay;
import com.ruoyi.web.controller.tool.AlipayTradeQuery;
import com.wechat.pay.java.core.exception.MalformedMessageException;
import com.wechat.pay.java.core.exception.ServiceException;
import com.wechat.pay.java.service.partnerpayments.app.model.PrepayResponse;
import com.wechat.pay.java.service.payments.nativepay.NativePayService;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
 
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
 
/**
 * <p>
 * 课程列表 前端控制器
 * </p>
 *
 * @author luodangjia
 * @since 2024-09-19
 */
@RestController
@RequestMapping("/t-course")
public class TCourseController {
 
    @Resource
    private TCourseService courseService;
    @Resource
    private TRegionService regionService;
    @Resource
    private TTechnicalTitleService tTechnicalTitleService;
    @Resource
    private TTitleMajorService majorService;
 
    @Resource
    private TCoursePartService coursePartService;
    @Resource
    private TokenService tokenService;
    @Resource
    private WeChatConfig weChatConfig;
    @Resource
    private TOrderService orderService;
    @Resource
    private NativePayService nativePayService;
    @Resource
    private RedisCache redisCache;
 
 
    @ApiOperation(value = "添加",tags = "后台-教学视频管理")
    @PostMapping(value = "/add")
    public R add(@RequestBody TCourse course) {
        courseService.save(course);
        return R.ok();
    }
 
    @Resource
    private TCourseCommentService courseCommentService;
    @ApiOperation(value = "删除",tags = "后台-教学视频管理")
    @PostMapping(value = "/delete")
    public R delete(String ids) {
        String[] split = ids.split(",");
        for (String id : split) {
 
        courseService.removeById(id);
        coursePartService.remove(Wrappers.lambdaQuery(TCoursePart.class).eq(TCoursePart::getCourseId,id));
            courseCommentService.remove(Wrappers.lambdaQuery(TCourseComment.class).eq(TCourseComment::getCourseId,id));
 
        }
        return R.ok();
    }
    //编辑
    @ApiOperation(value = "编辑",tags = "后台-教学视频管理")
    @PostMapping(value = "/edit")
    public R edit(@RequestBody TCourse course) {
        courseService.updateById(course);
        return R.ok();
    }
    //列表
    @ApiOperation(value = "查询",tags = {"后台-教学视频管理","web教学视频查询"})
    @PostMapping(value = "/list")
    public R<Page<TCourse>> list(@RequestBody CourseQuery informationQuery) {
        Long userId = tokenService.getLoginUser().getUserId();
        Page<TCourse> page;
        if (informationQuery.getSortType()==1){
            page = courseService.lambdaQuery()
                    .like(!StringUtils.isEmpty(informationQuery.getName()), TCourse::getCourseName, informationQuery.getName())
                    .eq(informationQuery.getRegionId() != null, TCourse::getRegionId, informationQuery.getRegionId())
                    .eq(informationQuery.getTechnicalId() != null, TCourse::getTechnicalId, informationQuery.getTechnicalId())
                    .eq(informationQuery.getMajorId() != null, TCourse::getMajorId, informationQuery.getMajorId())
                    .eq(informationQuery.getLevel() != null, TCourse::getLevel, informationQuery.getLevel())
                    .orderByDesc(TCourse::getCreateTime)
                    .page(Page.of(informationQuery.getPageNum(), informationQuery.getPageSize()));
        }else {
            page = courseService.lambdaQuery()
                    .like(!StringUtils.isEmpty(informationQuery.getName()), TCourse::getCourseName, informationQuery.getName())
                    .eq(informationQuery.getRegionId() != null, TCourse::getRegionId, informationQuery.getRegionId())
                    .eq(informationQuery.getTechnicalId() != null, TCourse::getTechnicalId, informationQuery.getTechnicalId())
                    .eq(informationQuery.getMajorId() != null, TCourse::getMajorId, informationQuery.getMajorId())
                    .eq(informationQuery.getLevel() != null, TCourse::getLevel, informationQuery.getLevel())
                    .orderByDesc(TCourse::getCommitteeSort)
                    .page(Page.of(informationQuery.getPageNum(), informationQuery.getPageSize()));
        }
 
        Set<Long> cacheSet = redisCache.getCacheSet("COURSE:" + userId);
 
        for (TCourse record : page.getRecords()) {
            TRegion byId = regionService.getById(record.getRegionId());
            record.setRegionName(byId.getProvinceName()+"-"+byId.getName());
            TTechnicalTitle byId1 = tTechnicalTitleService.getById(record.getTechnicalId() );
            TTitleMajor byId2 = majorService.getById(record.getMajorId());
            record.setTechnicalName(byId1.getTitileName()+"-"+byId2.getMajorName());
            if (cacheSet!=null){
                if (cacheSet.contains(record.getId())){
                    record.setIsCollect(1);
                }else {
                    record.setIsCollect(0);
                }
            }else {
                record.setIsCollect(0);
            }
 
            Set<Object> cacheSet1 = redisCache.getCacheSet("STUDY:" + record.getId());
            if (cacheSet1==null){
                record.setStudyNum(0);
            }else {
                record.setStudyNum(cacheSet1.size());
            }
 
            Long count = orderService.lambdaQuery()
                    .eq(TOrder::getGoodId, record.getId())
                    .eq(TOrder::getGoodType, 1)
                    .eq(TOrder::getPaymentStatus, 2).count();
            record.setBuyNum(Integer.parseInt(String.valueOf(count)));
 
        }
        return R.ok(page);
    }
 
 
    @ApiOperation(value = "其他课程推荐",tags = {"web教学视频查询"})
    @PostMapping(value = "/other")
    public R<List<TCourse>> other(@RequestParam Long id) {
        List<TCourse> list = courseService.lambdaQuery().ne(TCourse::getId, id).last("limit 3").list();
 
        for (TCourse record : list) {
            TRegion byId = regionService.getById(record.getRegionId());
            record.setRegionName(byId.getProvinceName()+"-"+byId.getName());
            TTechnicalTitle byId1 = tTechnicalTitleService.getById(record.getTechnicalId() );
            TTitleMajor byId2 = majorService.getById(record.getMajorId());
            record.setTechnicalName(byId1.getTitileName()+"-"+byId2.getMajorName());
        }
        return R.ok(list);
    }
 
 
 
    @ApiOperation(value = "章节管理设置",tags = "后台-教学视频管理")
    @PostMapping(value = "/video")
    public R video(@RequestBody VideoAddDto videoAddDto) {
        //先删除所有数据
        coursePartService.remove(Wrappers.lambdaQuery(TCoursePart.class).eq(TCoursePart::getCourseId, videoAddDto.getCourseId()));
        //然后一次新增
        for (TCoursePart coursePart : videoAddDto.getCourseParts()) {
            coursePart.setCourseId(videoAddDto.getCourseId());
            coursePart.setVedioJson(JSONObject.toJSONString(coursePart.getVideoDtos()));
            coursePart.setId(null);
        }
        coursePartService.saveBatch(videoAddDto.getCourseParts());
        return R.ok();
    }
 
 
 
    @ApiOperation(value = "获取章节列表",tags = {"后台-教学视频管理","web教学视频查询"})
    @PostMapping(value = "/detail/video")
    public R<List<TCoursePart>> video(Long courseId) {
 
        List<TCoursePart> list = coursePartService.lambdaQuery().eq(TCoursePart::getCourseId,courseId).orderByAsc(TCoursePart::getIndex1).list();
        for (TCoursePart tCoursePart : list) {
            tCoursePart.setVideoDtos(JSONArray.parseArray(tCoursePart.getVedioJson(), TVideoDto.class));
        }
        return R.ok(list);
 
    }
 
 
    @ApiOperation(value = "获取课程详情",tags = {"后台-教学视频管理","web教学视频查询"})
    @PostMapping(value = "/detail")
    public R<TCourse> detail(Long courseId) {
 
        TCourse record = courseService.getById(courseId);
 
        TRegion byId = regionService.getById(record.getRegionId());
        record.setRegionName(byId.getProvinceName()+"-"+byId.getName());
        TTechnicalTitle byId1 = tTechnicalTitleService.getById(record.getTechnicalId() );
        TTitleMajor byId2 = majorService.getById(record.getMajorId());
        record.setTechnicalName(byId1.getTitileName()+"-"+byId2.getMajorName());
 
 
        Long userId = tokenService.getLoginUser().getUserId();
        Set<Long> cacheSet = redisCache.getCacheSet("COURSE:" + userId);
        if (cacheSet!=null){
            if (cacheSet.contains(record.getId())){
                record.setIsCollect(1);
            }else {
                record.setIsCollect(0);
            }
        }else {
            record.setIsCollect(0);
        }
        Long count = orderService.lambdaQuery().eq(TOrder::getGoodType, 1).eq(TOrder::getGoodId, courseId).eq(TOrder::getPaymentStatus,2).eq(TOrder::getUserId, userId).count();
        if (count>0){
            record.setIsPay(1);
        }else {
            record.setIsPay(0);
        }
 
        Set<Object> cacheSet1 = redisCache.getCacheSet("STUDY:" + courseId);
        if (cacheSet1==null){
            record.setStudyNum(0);
        }else {
            record.setStudyNum(cacheSet1.size());
        }
 
        Set<Object> cacheSet2 = redisCache.getCacheSet("COLLECT:" + courseId);
        if (cacheSet2==null){
            record.setCollectNum(0);
        }else {
            record.setCollectNum(cacheSet2.size());
        }
 
        return R.ok(record);
 
    }
 
    @ApiOperation(value = "浏览课程调用",tags = {"web教学视频查询"})
    @PostMapping(value = "/view")
    public R view(Long courseId) {
 
        TCourse byId = courseService.getById(courseId);
        byId.setVisitNum(byId.getVisitNum()+1);
        courseService.updateById(byId);
        return R.ok();
 
    }
 
    @ApiOperation(value = "学习",tags = {"web教学视频查询"})
    @PostMapping(value = "/study")
    public R study(Long courseId) {
        Long userId = tokenService.getLoginUser().getUserId();
 
        Set<Long> users = new HashSet<>();
        users.add(userId);
        redisCache.setCacheSet("STUDY:" + courseId,users);
        return R.ok();
 
    }
 
    @ApiOperation(value = "生成订单",tags = {"web教学视频查询"})
    @PostMapping(value = "/create")
    public R buy( @RequestParam Long id) throws AlipayApiException {
        Long userId = tokenService.getLoginUser().getUserId();
        TCourse byId = courseService.getById(id);
 
        String code = "KC" + WeChatUtil.generateTradeNumber();
        TOrder order = new TOrder();
        order.setCode(code);
        order.setUserId(userId);
        order.setGoodType(1);
        order.setGoodId(id);
        order.setOrderAmount(byId.getCoursePrice());
        order.setPaymentAmount(byId.getCoursePrice());
        if (byId.getCoursePrice().compareTo(new BigDecimal(0))==0){
            order.setPaymentStatus(2);
 
        }
        order.setPaymentStatus(1);
 
 
        orderService.save(order);
        return R.ok(order.getId());
    }
 
 
    @ApiOperation(value = "购买",tags = {"web教学视频查询"})
    @PostMapping(value = "/buy")
    public R<PayDto> buy(@RequestParam Integer type, @RequestParam Long orderId) throws AlipayApiException {
        TOrder byId = orderService.getById(orderId);
        if (type == 1) {
            com.wechat.pay.java.service.payments.nativepay.model.PrepayRequest prepayRequest = new com.wechat.pay.java.service.payments.nativepay.model.PrepayRequest();
            prepayRequest.setAppid(weChatConfig.appId);
            prepayRequest.setMchid(weChatConfig.merchantId);
            prepayRequest.setOutTradeNo(byId.getCode());
            prepayRequest.setDescription("购买课程");
            prepayRequest.setNotifyUrl("http://vwpmxwbhv59i.guyubao.com/call-back/buy");
            com.wechat.pay.java.service.payments.nativepay.model.Amount amount = new com.wechat.pay.java.service.payments.nativepay.model.Amount();
            amount.setTotal(byId.getPaymentAmount().multiply(new BigDecimal(100)).intValue());
            prepayRequest.setAmount(amount);
            // 调用下单方法,得到应答
            PrepayResponse response;
            try {
                com.wechat.pay.java.service.payments.nativepay.model.PrepayResponse prepay = nativePayService.prepay(prepayRequest);
 
                PayDto payDto = new PayDto();
                payDto.setOrderId(orderId);
                payDto.setQrCode(prepay.getCodeUrl());
                return R.ok(payDto);
            } catch (HttpException e) { // 发送HTTP请求失败
//                log.error("发送HTTP请求失败: {}", e.getHttpRequest());
            } catch (ServiceException e) { // 服务返回状态小于200或大于等于300,例如500
//                log.error("服务返回状态异常: {}", e.getResponseBody());
            } catch (MalformedMessageException e) { // 服务返回成功,返回体类型不合法,或者解析返回体失败
//                log.error("返回体类型不合法: {}", e.getMessage());
            } catch (Exception e) {
//                log.error("预下单异常: {}", e.getMessage());
            }
            return null;
        } else {
            String qrCode = AlipayTradePagePay.pay("购买课程",byId.getCode(),byId.getPaymentAmount().toString());
            PayDto payDto = new PayDto();
            payDto.setOrderId(orderId);
            payDto.setQrCode(qrCode);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        int num = 1;
                        int wait = 0;
                        while (num <= 30) {
                            int min = 2000;
                            Thread.sleep(min);
                            Boolean check = AlipayTradeQuery.check(byId.getCode());
                            if (check){
                                byId.setPaymentStatus(2);
                                byId.setPaymentType(2);
                                byId.setPayTime(LocalDateTime.now());
                                orderService.updateById(byId);
 
                                if (byId.getGoodType()==1){
                                    try {
                                        TCourse byId1 = courseService.getById(byId.getGoodId());
                                        byId1.setBuyNum(byId1.getBuyNum()+1);
                                        courseService.updateById(byId1);
                                    }catch (Exception e){
                                        e.printStackTrace();
                                    }
 
                                }
                            }else {
                                num++;
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
            return R.ok(payDto);
        }
    }
 
 
    @ApiOperation(value = "收藏课程",tags = {"web-个人中心"})
    @PostMapping(value = "/info/list")
    public R<Page<TCourse>> infolist(@RequestBody BasePage basePage) {
 
        Long userId = tokenService.getLoginUser().getUserId();
        Set<Long> cacheSet = redisCache.getCacheSet("COURSE:" + userId);
 
 
        if (!cacheSet.isEmpty()) {
            Page<TCourse> page = courseService.lambdaQuery().in(TCourse::getId, cacheSet).page(Page.of(basePage.getPageNum(), basePage.getPageSize()));
            for (TCourse record : page.getRecords()) {
                Set<Object> cacheSet1 = redisCache.getCacheSet("STUDY:" + record.getId());
                if (cacheSet1==null){
                    record.setStudyNum(0);
                }else {
                    record.setStudyNum(cacheSet1.size());
                }
            }
            return R.ok(page);
        }else {
            return R.ok(new Page<>());
        }
    }
 
 
 
 
    @ApiOperation(value = "判断当前课程是否收藏",tags = {"web-个人中心"})
    @PostMapping(value = "/collect/is")
    public R<Boolean> collectis(@RequestParam Long courseId) {
 
        Long userId = tokenService.getLoginUser().getUserId();
        Set<Long> cacheSet = redisCache.getCacheSet("COURSE:" + userId);
        if (cacheSet.contains(courseId)){
            return R.ok(true);
        }else {
            return R.ok(false);
        }
    }
 
 
 
 
 
 
 
}