无关风月
2024-12-31 0c51a577db337520452022d9d6a22b720ef858d4
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
package com.xinquan.order.service.impl;
 
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinquan.common.core.constant.SecurityConstants;
import com.xinquan.common.core.enums.ChargeTypeEnum;
import com.xinquan.common.core.enums.DisabledEnum;
import com.xinquan.common.core.enums.PaymentStatusEnum;
import com.xinquan.common.core.enums.PaymentTypeEnum;
import com.xinquan.common.core.exception.ServiceException;
import com.xinquan.common.core.utils.ip.IpUtils;
import com.xinquan.common.security.service.TokenService;
import com.xinquan.course.api.domain.Course;
import com.xinquan.course.api.feign.RemoteCourseService;
import com.xinquan.meditation.api.domain.Meditation;
import com.xinquan.meditation.api.feign.RemoteMeditationService;
import com.xinquan.order.api.domain.Order;
import com.xinquan.order.domain.OrderPaymentRecord;
import com.xinquan.order.domain.vo.ClientPlaceOrderVO;
import com.xinquan.order.mapper.OrderMapper;
import com.xinquan.order.service.OrderPaymentRecordService;
import com.xinquan.order.service.OrderService;
import com.xinquan.common.core.utils.JuHeFuUtil;
import com.xinquan.order.utils.OrderUtil;
import com.xinquan.system.api.domain.AppUser;
import com.xinquan.system.api.domain.AppUserWalletRecord;
import com.xinquan.system.api.model.LoginUser;
import com.xinquan.user.api.domain.dto.AppUserDTO;
import com.xinquan.user.api.feign.RemoteAppUserService;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.List;
 
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import javax.annotation.Resource;
 
/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author mitao
 * @since 2024-08-21
 */
@Service
@RequiredArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
 
    @Resource
    private  RemoteMeditationService remoteMeditationService;
    @Resource
    private  RemoteCourseService remoteCourseService;
    @Resource
    private  RemoteAppUserService remoteAppUserService;
    @Resource
    private  OrderPaymentRecordService orderPaymentRecordService;
    @Autowired
    private TokenService tokenService;
    /**
     * 创建待支付订单
     *
     * @param targetId    目标id
     * @param orderFrom   订单来源 1=冥想音频 2=课程
     * @param receiverId  被赠送课程APP用户id
     * @param balanceFlag 是否使用余额抵扣 1=是 2=否
     * @param payType     支付方式 1=微信 2=支付宝
     * @return 下单返回数据视图对象
     * @see com.xinquan.order.domain.vo.ClientPlaceOrderVO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ClientPlaceOrderVO placeOrder(Long targetId, Integer orderFrom, Long receiverId, Long orderId,
            Integer balanceFlag, Integer payType,BigDecimal amount,Integer vipType,Integer type) throws Exception {
        // 获取当前登录用户id
        LoginUser loginUser = tokenService.getLoginUser();
        if (loginUser==null){
            return new ClientPlaceOrderVO();
        }
        Long userId = loginUser.getUserid();
        if (amount!=null){
            amount = amount.setScale(2, RoundingMode.HALF_DOWN);
        }
        // 获取用户信息
        AppUser appUser = getAppUserById(userId);
        ClientPlaceOrderVO clientPlaceOrderVO = new ClientPlaceOrderVO();
        Order order = new Order();
        order.setPayType(payType);
        AppUser data = remoteAppUserService.getAppUserById(userId + "").getData();
 
        // 购买冥想音频
        if (orderFrom == 1) {
            Meditation meditation = remoteMeditationService.getMeditationById(targetId,
                    SecurityConstants.INNER).getData();
            String meditationTitle = meditation.getMeditationTitle();
            String detailDescription = "购买疗愈音频";
            String wxOpenId = appUser.getWxOpenId();
            // 创建订单
            String orderNo = OrderUtil.getOrderNoForPrefix("MX");
            if (orderId==null){
                order.setPayType(payType);
                order.setOrderFrom(orderFrom);
                order.setBizOrderNo(orderNo);
                order.setBusinessId(meditation.getId());
                order.setAppUserId(userId);
                order.setRealPayAmount(type==null?meditation.getGeneralPrice():meditation.getIosPrice());
                order.setTotalAmount(type==null?meditation.getGeneralPrice():meditation.getIosPrice());
                order.setPayType(payType);
                order.setBuyContent("购买疗愈【"+meditationTitle+"】");
                order.setGiveUserId(receiverId);
                this.save(order);
            }else{
                 order = this.getById(orderId);
                 order.setBizOrderNo(orderNo);
                 order.setBuyContent("购买疗愈【"+meditationTitle+"】");
                 this.updateById(order);
            }
 
            Long orderId9 = order.getId();
            clientPlaceOrderVO.setOrderNo(orderNo);
            clientPlaceOrderVO.setId(orderId9);
 
            // 如果冥想音频价格设定为单独收费,且需要使用余额抵扣
            if (data.getBalance().compareTo(new BigDecimal("0")) > 0 && balanceFlag.equals(1) && meditation.getChargeType().equals(ChargeTypeEnum.SEPARATE_CHARGE.getCode())) {
                BigDecimal needPayAmount = handleBalancePayment(appUser,
                        type==null?meditation.getGeneralPrice():meditation.getIosPrice(),
                        orderId9);
                if (needPayAmount.compareTo(BigDecimal.ZERO) <= 0) {
                    clientPlaceOrderVO.setZeroFlag(DisabledEnum.YES.getCode());
                    // 抵扣后金额为0 为余额支付
                    order.setPayType(4);
                    order.setBuyContent("购买疗愈【"+meditationTitle+"】");
                    this.updateById(order);
                    return clientPlaceOrderVO;
                }
                if (payType==1){
                    // 微信+余额
                    order.setPayType(5);
                }else if (payType == 2){
                    // 支付宝+余额
                    order.setPayType(6);
                }
                order.setBuyContent("购买疗愈【"+meditationTitle+"】");
                this.updateById(order);
                // 创建支付订单
                createPayment(payType, orderNo, needPayAmount, meditationTitle, "购买疗愈",
                        wxOpenId, orderId9, clientPlaceOrderVO);
            } else {
                // 创建支付订单
                createPayment(payType, orderNo, type==null?order.getRealPayAmount():order.getRealPayAmount(), meditationTitle,
                        "购买疗愈", wxOpenId, orderId9, clientPlaceOrderVO);
            }
        }
        else if (orderFrom == 2){
            // 购买课程
            Course course = remoteCourseService.getCourseById(targetId).getData();
            String courseTitle = course.getCourseTitle();
            String wxOpenId = appUser.getWxOpenId();
            String description = "购买课程";
 
            // 创建订单
            String orderNo = OrderUtil.getOrderNoForPrefix("KC");
            if (orderId==null){
                order.setOrderFrom(orderFrom);
                order.setBizOrderNo(orderNo);
                order.setGiveUserId(receiverId);
                order.setBusinessId(course.getId());
 
                order.setAppUserId(userId);
                order.setBuyContent("购买课程【"+courseTitle+"】");
                order.setRealPayAmount(type==null?course.getGeneralPrice():course.getIosPrice());
                order.setTotalAmount(type==null?course.getGeneralPrice():course.getIosPrice());
                this.save(order);
            }else{
                order = this.getById(orderId);
                order.setBuyContent("购买课程【"+courseTitle+"】");
                order.setBizOrderNo(orderNo);
                this.updateById(order);
 
            }
            Long orderId8 = order.getId();
            clientPlaceOrderVO.setOrderNo(orderNo);
            clientPlaceOrderVO.setId(orderId8);
 
            if (data.getBalance().compareTo(new BigDecimal("0")) > 0 && balanceFlag.equals(1) && course.getChargeType()
                    .equals(ChargeTypeEnum.SEPARATE_CHARGE.getCode())) {
                BigDecimal needPayAmount = handleBalancePayment(appUser, type==null?course.getGeneralPrice():course.getIosPrice(),
                        orderId8);
 
                if (needPayAmount.compareTo(BigDecimal.ZERO) <= 0) {
                    clientPlaceOrderVO.setZeroFlag(DisabledEnum.YES.getCode());
                    // 抵扣后金额为0 为余额支付
                    order.setPayType(4);
                    order.setBuyContent("购买课程【"+courseTitle+"】");
 
                    this.updateById(order);
                    return clientPlaceOrderVO;
                }
                if (payType==1){
                    // 微信+余额
                    order.setPayType(5);
                }else if (payType == 2){
                    // 支付宝+余额
                    order.setPayType(6);
                }
                order.setBuyContent("购买课程【"+courseTitle+"】");
 
                this.updateById(order);
                // 创建支付订单
                createPayment(payType, orderNo, needPayAmount, courseTitle, "购买课程",
                        wxOpenId, orderId8, clientPlaceOrderVO);
            } else {
                // 创建支付订单
                createPayment(payType, orderNo, order.getRealPayAmount(), courseTitle,
                        "购买课程", wxOpenId, orderId8, clientPlaceOrderVO);
            }
        }
        else if (orderFrom == 3){
            String wxOpenId = appUser.getWxOpenId();
            // 创建订单
            String orderNo = OrderUtil.getOrderNoForPrefix("HY");
            order.setOrderFrom(orderFrom);
            order.setBizOrderNo(orderNo);
            order.setAppUserId(userId);
            order.setTotalAmount(amount);
            order.setPayType(payType);
            order.setRealPayAmount(amount);
            String vipType1 ="";
            switch (vipType){
                case 1:
                    vipType1="月会员";
                    break;
                case 2:
                    vipType1="季会员";
                    break;
                case 3:
                    vipType1="年会员";
                    break;
            }
            order.setBuyContent(vipType1);
            this.save(order);
            Long orderId7 = order.getId();
            clientPlaceOrderVO.setOrderNo(orderNo);
            clientPlaceOrderVO.setId(orderId7);
            // 创建支付订单
            createPayment(payType, orderNo, amount, "购买会员",
                    vipType1, wxOpenId, orderId7, clientPlaceOrderVO);
 
        }else {
            // 充值
            String wxOpenId = appUser.getWxOpenId();
            // 创建订单
            String orderNo = OrderUtil.getOrderNoForPrefix("CZ");
            order.setOrderFrom(orderFrom);
            order.setBizOrderNo(orderNo);
            order.setAppUserId(userId);
            order.setTotalAmount(amount);
            order.setRealPayAmount(amount);
            order.setPayType(payType);
            order.setBuyContent("充值");
            this.save(order);
            Long orderId6 = order.getId();
            clientPlaceOrderVO.setOrderNo(orderNo);
            clientPlaceOrderVO.setId(orderId6);
            // 创建支付订单
            createPayment(payType, orderNo, amount, "充值余额",
                    "充值余额", wxOpenId, orderId6, clientPlaceOrderVO);
        }
        return clientPlaceOrderVO;
    }
 
    /**
     * 处理余额抵扣
     *
     * @param appUser      app用户
     * @param generalPrice 通用价格
     * @param orderId      订单号
     * @return 需要支付的金额
     */
    @NotNull
    private BigDecimal handleBalancePayment(AppUser appUser, BigDecimal generalPrice,
            Long orderId) {
        if (appUser.getBalance().compareTo(BigDecimal.ZERO) < 0) {
            throw new ServiceException("用户可用余额不足,请重新选择支付方案");
        }
        Order one = this.lambdaQuery().eq(Order::getId, orderId).one();
 
        // 如果余额大于通用价格 则实际支付价格为0
        if (appUser.getBalance().compareTo(one.getRealPayAmount())>=0){
            // 更新用户余额
//            remoteAppUserService.updateAppUser(
//                    AppUserDTO.builder().balance(
//                                    appUser.getBalance().subtract(one.getRealPayAmount()))
//                            .build(), SecurityConstants.INNER);
            OrderPaymentRecord balancePaymentRecord = new OrderPaymentRecord();
            balancePaymentRecord.setOrderId(orderId);
            balancePaymentRecord.setPayAmount(one.getRealPayAmount());
            balancePaymentRecord.setPaymentType(PaymentTypeEnum.BALANCE_PAY.getCode());
            balancePaymentRecord.setPaymentStatus(PaymentStatusEnum.COMPLETED.getCode());
            List<OrderPaymentRecord> list = orderPaymentRecordService.lambdaQuery().eq(OrderPaymentRecord::getOrderId, orderId)
                    .eq(OrderPaymentRecord::getPaymentType, 4).list();
            if (list.isEmpty()){
                orderPaymentRecordService.save(balancePaymentRecord);
            }
 
            return new BigDecimal("0");
        }else {
            // 更新用户余额
//            remoteAppUserService.updateAppUser(
//                    AppUserDTO.builder().balance(
//                                    one.getRealPayAmount().subtract(appUser.getBalance()))
//                            .build(), SecurityConstants.INNER);
 
            OrderPaymentRecord balancePaymentRecord = new OrderPaymentRecord();
            balancePaymentRecord.setOrderId(orderId);
            balancePaymentRecord.setPaymentType(PaymentTypeEnum.BALANCE_PAY.getCode());
            balancePaymentRecord.setPaymentStatus(PaymentStatusEnum.COMPLETED.getCode());
            balancePaymentRecord.setPayAmount(appUser.getBalance());
            List<OrderPaymentRecord> list = orderPaymentRecordService.lambdaQuery().eq(OrderPaymentRecord::getOrderId, orderId)
                    .eq(OrderPaymentRecord::getPaymentType, 4).list();
            if (list.isEmpty()){
                orderPaymentRecordService.save(balancePaymentRecord);
            }
            // 计算除去余额还需支付的金额
            return one.getRealPayAmount()
                    .subtract(appUser.getBalance());
        }
 
    }
 
    /**
     * 获取登录用户信息
     *
     * @param userId APP用户id
     * @return AppUser
     */
    private AppUser getAppUserById(Long userId) {
        return remoteAppUserService.getAppUserById(userId+"").getData();
    }
 
    /**
     * 创建支付订单
     *
     * @param payType            支付方式 1=微信 2=支付宝
     * @param orderNo            订单编号
     * @param needPayAmount      支付金额
     * @param goodsTitle         商品标题
     * @param goodsDesc          商品描述
     * @param wxOpenId           微信openId
     * @param orderId            订单id
     * @param clientPlaceOrderVO 下单返回数据视图对象
     * @throws Exception
     */
    private void createPayment(Integer payType, String orderNo, BigDecimal needPayAmount,
            String goodsTitle, String goodsDesc, String wxOpenId, Long orderId,
            ClientPlaceOrderVO clientPlaceOrderVO) throws Exception {
        if (payType == 1){
            // 微信托管支付
            // 截取前42个字符 商品描述信息,微信小程序和微信公众号该字段,最大长度 42 个字符
            // 调用第三方支付获取支付信息
            JSONObject payInfo = JuHeFuUtil.createPayment1(orderNo, payType,
                    needPayAmount.toString(), goodsTitle, goodsDesc,
                    IpUtils.getIpAddr(), wxOpenId,
                                    "https://xq.xqzhihui.com/api/order/client/order/order/base/callback"
//                    "https://xq.xqzhihui.com/api/order/client/order/order/base/callback"
            );
            // 第三方支付记录
            OrderPaymentRecord paymentRecord = new OrderPaymentRecord();
            paymentRecord.setOrderId(orderId);
            Order byId = this.getById(orderId);
            this.updateById(byId);
            clientPlaceOrderVO.setPayAmt(payInfo.getString("pay_amt"));
            clientPlaceOrderVO.setPath(payInfo.getJSONObject("expend").getString("path"));
            clientPlaceOrderVO.setPayInfo(payInfo.getJSONObject("expend").getString("pay_info"));
            clientPlaceOrderVO.setOrgId(payInfo.getJSONObject("expend").getString("orgId"));
            clientPlaceOrderVO.setAppId(payInfo.getJSONObject("expend").getString("appId"));
            paymentRecord.setPaymentType(PaymentTypeEnum.WECHAT_PAY.getCode());
            paymentRecord.setPayOrderNo(payInfo.getString("id"));
            clientPlaceOrderVO.setOrderId(payInfo.getString("id"));
            paymentRecord.setPaymentStatus(PaymentStatusEnum.TO_BE_PAID.getCode());
            paymentRecord.setPayAmount(needPayAmount);
            OrderPaymentRecord list = orderPaymentRecordService.lambdaQuery().eq(OrderPaymentRecord::getOrderId, orderId)
                    .ne(OrderPaymentRecord::getPaymentType, 4).one();
            if (list==null){
                orderPaymentRecordService.save(paymentRecord);
            }else{
                list.setPayOrderNo(payInfo.getString("id"));
                orderPaymentRecordService.updateById(list);
            }
            // 设置订单是否需要支付标识
            clientPlaceOrderVO.setZeroFlag(DisabledEnum.NO.getCode());
        }else{
            // 调用第三方支付获取支付信息
            JSONObject payInfo = JuHeFuUtil.createPayment(orderNo, payType,
                    needPayAmount.toString(), goodsTitle, goodsDesc,
                    IpUtils.getIpAddr(), wxOpenId,
                                    "https://xq.xqzhihui.com/api/order/client/order/order/base/callback"
//                    "https://xq.xqzhihui.com/api/order/client/order/order/base/callback"
 
            );
            // 第三方支付记录
            OrderPaymentRecord paymentRecord = new OrderPaymentRecord();
            paymentRecord.setOrderId(orderId);
            paymentRecord.setPayAmount(needPayAmount);
            Order byId = this.getById(orderId);
            this.updateById(byId);
            JSONObject expend = payInfo.getJSONObject("expend");
            String string = expend.getString("qrcode_url");
            clientPlaceOrderVO.setQrcodeUrl(string);
            paymentRecord.setPaymentType(PaymentTypeEnum.ALI_PAY.getCode());
            paymentRecord.setPaymentStatus(PaymentStatusEnum.TO_BE_PAID.getCode());
            paymentRecord.setPayOrderNo(payInfo.getString("id"));
            OrderPaymentRecord list = orderPaymentRecordService.lambdaQuery().eq(OrderPaymentRecord::getOrderId, orderId)
                    .ne(OrderPaymentRecord::getPaymentType, 4).one();
            if (list==null){
                orderPaymentRecordService.save(paymentRecord);
            }else{
                list.setPayOrderNo(payInfo.getString("id"));
                orderPaymentRecordService.updateById(list);
            }
            clientPlaceOrderVO.setPayAmt(payInfo.getString("pay_amt"));
            clientPlaceOrderVO.setOrderId(payInfo.getString("id"));
            // 设置订单是否需要支付标识
            clientPlaceOrderVO.setZeroFlag(DisabledEnum.NO.getCode());
        }
 
    }
 
    /**
     * 根据类型获取已完成的订单列表
     *
     * @param userId    用户id
     * @param orderFrom 订单来源
     * @return
     */
    @Override
    public List<Order> getOrderListByType(Long userId, Integer orderFrom) {
        return this.lambdaQuery().eq(Order::getAppUserId, userId).eq(Order::getOrderFrom, orderFrom)
                .eq(Order::getPaymentStatus, PaymentStatusEnum.COMPLETED.getCode()).list();
    }
 
    @Override
    public String placeOrderApple(Long targetId, Integer orderFrom,
                                  Long receiverId, Integer balanceFlag,
                                  BigDecimal amount, Integer vipType, String transactionIdentifier) {
        // 获取当前登录用户id
        Long userId = tokenService.getLoginUser().getUserid();
        // 获取用户信息
        AppUser appUser = getAppUserById(userId);
        ClientPlaceOrderVO clientPlaceOrderVO = new ClientPlaceOrderVO();
        Order order = new Order();
        // 购买冥想音频
        if (orderFrom == 1) {
            Meditation meditation = remoteMeditationService.getMeditationById(targetId,
                    SecurityConstants.INNER).getData();
            // 创建订单
            String orderNo = OrderUtil.getOrderNoForPrefix("MX");
            order.setOrderFrom(orderFrom);
            order.setBizOrderNo(orderNo);
            order.setBusinessId(meditation.getId());
            order.setAppUserId(userId);
            order.setTotalAmount(meditation.getIosPrice());
            order.setPayType(3);
            order.setBuyContent("购买疗愈");
            this.save(order);
            Long orderId = order.getId();
            clientPlaceOrderVO.setOrderNo(orderNo);
            clientPlaceOrderVO.setId(orderId);
            // 如果冥想音频价格设定为单独收费,且需要使用余额抵扣
            if (balanceFlag.equals(1) && meditation.getChargeType().equals(ChargeTypeEnum.SEPARATE_CHARGE.getCode())) {
                BigDecimal needPayAmount = handleBalancePayment(appUser,
                        meditation.getIosPrice(),
                        orderId);
                if (needPayAmount.compareTo(BigDecimal.ZERO) <= 0) {
                    clientPlaceOrderVO.setZeroFlag(DisabledEnum.YES.getCode());
                    // 抵扣后金额为0 为余额支付
                    order.setPayType(4);
                    order.setRealPayAmount(meditation.getIosPrice());
                    this.updateById(order);
                    return order.getId().toString();
                }else{
                    order.setPayType(7);
                    this.updateById(order);
                    // 创建支付订单
                    OrderPaymentRecord paymentRecord = new OrderPaymentRecord();
                    paymentRecord.setPayAmount(meditation.getIosPrice());
                    paymentRecord.setPayOrderNo(transactionIdentifier);
                    paymentRecord.setOrderId(orderId);
                    paymentRecord.setPaymentType(PaymentTypeEnum.IOS_PAY.getCode());
                    paymentRecord.setPaymentStatus(PaymentStatusEnum.TO_BE_PAID.getCode());
                    orderPaymentRecordService.save(paymentRecord);
                }
 
            } else {
                order.setPayType(3);
                this.updateById(order);
                // 纯内购支付
                OrderPaymentRecord paymentRecord = new OrderPaymentRecord();
                paymentRecord.setPayAmount(meditation.getIosPrice());
                paymentRecord.setPayOrderNo(transactionIdentifier);
                paymentRecord.setOrderId(orderId);
                paymentRecord.setPaymentType(PaymentTypeEnum.IOS_PAY.getCode());
                paymentRecord.setPaymentStatus(PaymentStatusEnum.TO_BE_PAID.getCode());
                orderPaymentRecordService.save(paymentRecord);
            }
        }
        else if (orderFrom == 2){
            // 购买课程
            Course course = remoteCourseService.getCourseById(targetId).getData();
            // 创建订单
            String orderNo = OrderUtil.getOrderNoForPrefix("KC");
            order.setOrderFrom(orderFrom);
            order.setBuyContent("购买课程");
            order.setBizOrderNo(orderNo);
            order.setPayOrderNo(transactionIdentifier);
            order.setGiveUserId(receiverId);
            order.setBusinessId(course.getId());
            order.setAppUserId(userId);
            order.setTotalAmount(course.getIosPrice());
            this.save(order);
            Long orderId = order.getId();
            clientPlaceOrderVO.setOrderNo(orderNo);
            clientPlaceOrderVO.setId(orderId);
            if (balanceFlag.equals(1) && course.getChargeType()
                    .equals(ChargeTypeEnum.SEPARATE_CHARGE.getCode())) {
                BigDecimal needPayAmount = handleBalancePayment(appUser, course.getGeneralPrice(),
                        orderId);
                if (needPayAmount.compareTo(BigDecimal.ZERO) <= 0) {
                    clientPlaceOrderVO.setZeroFlag(DisabledEnum.YES.getCode());
                    // 抵扣后金额为0 为余额支付
                    order.setPayType(4);
                    order.setRealPayAmount(course.getGeneralPrice());
                    this.updateById(order);
                    return order.getId()+"";
                }else{
                    order.setPayType(7);
                    this.updateById(order);
                    // 创建支付订单
                    OrderPaymentRecord paymentRecord = new OrderPaymentRecord();
                    paymentRecord.setPayAmount(course.getIosPrice());
                    paymentRecord.setPayOrderNo(transactionIdentifier);
                    paymentRecord.setOrderId(orderId);
                    paymentRecord.setPaymentType(PaymentTypeEnum.IOS_PAY.getCode());
                    paymentRecord.setPaymentStatus(PaymentStatusEnum.TO_BE_PAID.getCode());
                    orderPaymentRecordService.save(paymentRecord);
                }
            } else {
                order.setPayType(3);
                this.updateById(order);
                // 创建支付订单
                OrderPaymentRecord paymentRecord = new OrderPaymentRecord();
                paymentRecord.setPayAmount(course.getIosPrice());
                paymentRecord.setPayOrderNo(transactionIdentifier);
                paymentRecord.setOrderId(orderId);
                paymentRecord.setPaymentType(PaymentTypeEnum.IOS_PAY.getCode());
                paymentRecord.setPaymentStatus(PaymentStatusEnum.TO_BE_PAID.getCode());
                orderPaymentRecordService.save(paymentRecord);
            }
        }
        else if (orderFrom == 3){
            // 创建订单
            String orderNo = OrderUtil.getOrderNoForPrefix("HY");
            order.setOrderFrom(orderFrom);
            order.setBizOrderNo(orderNo);
            order.setAppUserId(userId);
            order.setTotalAmount(amount);
            order.setRealPayAmount(amount);
            String vipType1 ="";
            switch (vipType){
                case 1:
                    vipType1="月会员";
                    break;
                case 2:
                    vipType1="季会员";
                    break;
                case 3:
                    vipType1="年会员";
                    break;
            }
            order.setBuyContent(vipType1);
            this.save(order);
            Long orderId = order.getId();
 
            order.setPayType(3);
            this.updateById(order);
            // 创建支付订单
            OrderPaymentRecord paymentRecord = new OrderPaymentRecord();
            paymentRecord.setPayAmount(amount);
            paymentRecord.setPayOrderNo(transactionIdentifier);
            paymentRecord.setOrderId(orderId);
            paymentRecord.setPaymentType(PaymentTypeEnum.IOS_PAY.getCode());
            paymentRecord.setPaymentStatus(PaymentStatusEnum.TO_BE_PAID.getCode());
            orderPaymentRecordService.save(paymentRecord);
        }else {
            // 充值
            String wxOpenId = appUser.getWxOpenId();
            // 创建订单
            String orderNo = OrderUtil.getOrderNoForPrefix("CZ");
            order.setOrderFrom(orderFrom);
            order.setBizOrderNo(orderNo);
            order.setAppUserId(userId);
            order.setTotalAmount(amount);
            order.setRealPayAmount(amount);
 
            order.setBuyContent("充值");
            this.save(order);
            Long orderId = order.getId();
            order.setPayType(3);
            this.updateById(order);
            // 创建支付订单
            OrderPaymentRecord paymentRecord = new OrderPaymentRecord();
            paymentRecord.setPayAmount(amount);
            paymentRecord.setPayOrderNo(transactionIdentifier);
            paymentRecord.setOrderId(orderId);
            paymentRecord.setPaymentType(PaymentTypeEnum.IOS_PAY.getCode());
            paymentRecord.setPaymentStatus(PaymentStatusEnum.TO_BE_PAID.getCode());
            orderPaymentRecordService.save(paymentRecord);
        }
        return order.getId()+"";
    }
 
 
 
    @Override
    public String refund(Long uid) throws Exception {
        Order byId = this.getById(uid);
        OrderPaymentRecord two = orderPaymentRecordService.lambdaQuery()
                .eq(OrderPaymentRecord::getPaymentType,4)
                .eq(OrderPaymentRecord::getOrderId, uid)
                .one();
        if (byId.getPayType() == 4){
            // 纯余额支付 直接退还余额
            // 回退余额记录
            AppUserWalletRecord appUserWalletRecord = new AppUserWalletRecord();
            appUserWalletRecord.setAppUserId(byId.getAppUserId());
            appUserWalletRecord.setChangeType(1);
            appUserWalletRecord.setReason("后台退款");
            appUserWalletRecord.setOrderId(byId.getId());
            appUserWalletRecord.setAmount(two.getPayAmount());
            remoteAppUserService.addBalanceRecord(appUserWalletRecord);
            remoteAppUserService.addBalance(byId.getAppUserId(),two.getPayAmount());
            byId.setRefundStatus(3);
            byId.setRefundRemark("后台退款");
            byId.setRefundTime(LocalDateTime.now());
            byId.setPaymentStatus(3);
            byId.setCancelTime(LocalDateTime.now());
            two.setPaymentStatus(3);
 
            this.updateById(byId);
            orderPaymentRecordService.updateById(two);
            switch (byId.getOrderFrom()){
                case 1:
                    // 冥想订单 删除
                    break;
                case 2:
                    // 删除用户与课程的关系表
                    remoteAppUserService.deleteAppUserCourse(byId.getBusinessId(),byId.getAppUserId());
                    break;
                case 3:
                    // 会员订单 将用户会员到期时间回退
                    if (byId.getBuyContent().contains("月")){
                        remoteAppUserService.subVipExpireTime(byId.getAppUserId(),1);
                    }else if (byId.getBuyContent().contains("季")){
                        remoteAppUserService.subVipExpireTime(byId.getAppUserId(),2);
                    }else if (byId.getBuyContent().contains("年")){
                        remoteAppUserService.subVipExpireTime(byId.getAppUserId(),3);
                    }
                    break;
            }
            return "success";
        }else if (byId.getPayType() == 5 || byId.getPayType() == 6 || byId.getPayType() == 7){
            OrderPaymentRecord one = orderPaymentRecordService.lambdaQuery()
                    .eq(OrderPaymentRecord::getOrderId, uid)
                    .ne(OrderPaymentRecord::getPaymentType, 4)
                    .ne(OrderPaymentRecord::getPaymentType, 3)
                    .one();
            JSONObject refund = JuHeFuUtil.refund(one.getPayOrderNo(), byId.getBizOrderNo());
            if (refund.getString("error_msg")!=null){
                return refund.getString("error_msg");
            }
            // 回退余额记录
            AppUserWalletRecord appUserWalletRecord = new AppUserWalletRecord();
            appUserWalletRecord.setAppUserId(byId.getAppUserId());
            appUserWalletRecord.setChangeType(1);
            appUserWalletRecord.setReason("后台退款");
            appUserWalletRecord.setOrderId(byId.getId());
            appUserWalletRecord.setAmount(two.getPayAmount());
            remoteAppUserService.addBalanceRecord(appUserWalletRecord);
            remoteAppUserService.addBalance(byId.getAppUserId(),two.getPayAmount());
            byId.setRefundStatus(3);
            byId.setRefundRemark("后台退款");
            byId.setRefundTime(LocalDateTime.now());
            byId.setPaymentStatus(3);
            byId.setCancelTime(LocalDateTime.now());
            two.setPaymentStatus(3);
            this.updateById(byId);
            orderPaymentRecordService.updateById(two);
 
            switch (byId.getOrderFrom()){
                case 1:
                    // 冥想订单 删除
                    break;
                case 2:
                    // 删除用户与课程的关系表
                    remoteAppUserService.deleteAppUserCourse(byId.getBusinessId(),byId.getAppUserId());
                    break;
                case 3:
                    // 会员订单 将用户会员到期时间回退
                    if (byId.getBuyContent().contains("月")){
                        remoteAppUserService.subVipExpireTime(byId.getAppUserId(),1);
                    }else if (byId.getBuyContent().contains("季")){
                        remoteAppUserService.subVipExpireTime(byId.getAppUserId(),2);
                    }else if (byId.getBuyContent().contains("年")){
                        remoteAppUserService.subVipExpireTime(byId.getAppUserId(),3);
                    }
                    break;
            }
            return "success";
        }
        OrderPaymentRecord one = orderPaymentRecordService.lambdaQuery()
                .eq(OrderPaymentRecord::getOrderId, uid)
                .ne(OrderPaymentRecord::getPaymentType, 4)
                .ne(OrderPaymentRecord::getPaymentType, 3)
                .one();
        JSONObject refund = JuHeFuUtil.refund(one.getPayOrderNo(), byId.getBizOrderNo());
        if (refund.getString("error_msg")!=null){
            return refund.getString("error_msg");
        }
        one.setPaymentStatus(3);
 
        orderPaymentRecordService.updateById(one);
        String string = refund.getString("payment_id");
        if (string!=null){
            byId.setRefundCode(string);
        }
        byId.setRefundTime(LocalDateTime.now());
        byId.setRefundStatus(3);
        byId.setRefundRemark("后台退款");
        this.updateById(byId);
        switch (byId.getOrderFrom()){
            case 1:
                // 冥想订单 删除
                break;
            case 2:
                // 删除用户与课程的关系表
                remoteAppUserService.deleteAppUserCourse(byId.getBusinessId(),byId.getAppUserId());
                break;
            case 3:
                // 会员订单 将用户会员到期时间回退
                if (byId.getBuyContent().contains("月")){
                    remoteAppUserService.subVipExpireTime(byId.getAppUserId(),1);
                }else if (byId.getBuyContent().contains("季")){
                    remoteAppUserService.subVipExpireTime(byId.getAppUserId(),2);
                }else if (byId.getBuyContent().contains("年")){
                    remoteAppUserService.subVipExpireTime(byId.getAppUserId(),3);
                }
                break;
        }
        return "success";
    }
}