huliguo
2025-04-03 de40c5a7d03ffe9bcdb2aabe82e03aef98e94eb8
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
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
package com.ruoyi.order.service.impl;
 
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.account.api.feignClient.*;
import com.ruoyi.account.api.model.*;
import com.ruoyi.account.api.vo.CouponInfoVo;
import com.ruoyi.account.api.vo.PaymentUserCoupon;
import com.ruoyi.account.api.vo.PaymentUserCouponVo;
import com.ruoyi.common.core.constant.ExpressCompanyMap;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.HttpUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.uuid.QRCodeGenerator;
import com.ruoyi.common.core.web.page.PageInfo;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.order.enums.OrderStatus;
import com.ruoyi.order.event.ConfirmDeliveryEvent;
import com.ruoyi.order.mapper.OrderGoodMapper;
import com.ruoyi.order.mapper.OrderMapper;
import com.ruoyi.order.model.Order;
import com.ruoyi.order.model.OrderGood;
import com.ruoyi.order.service.OrderGoodService;
import com.ruoyi.order.service.OrderService;
import com.ruoyi.order.util.ExpressDeliveryUtil;
import com.ruoyi.order.util.payment.PaymentUtil;
import com.ruoyi.order.util.payment.model.RefundCallbackResult;
import com.ruoyi.order.util.payment.model.RefundResult;
import com.ruoyi.order.util.vo.MapTrackKD100Vo;
import com.ruoyi.order.util.vo.QueryKD100ListVo;
import com.ruoyi.order.vo.*;
import com.ruoyi.other.api.domain.*;
import com.ruoyi.other.api.feignClient.*;
import com.ruoyi.other.api.vo.GetSeckillActivityInfo;
import com.ruoyi.system.api.domain.SysConfig;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.feignClient.SysConfigClient;
import com.ruoyi.system.api.feignClient.SysUserClient;
import com.ruoyi.system.api.model.LoginUser;
import lombok.SneakyThrows;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jetbrains.annotations.Nullable;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
 
import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
 
/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author luodangjia
 * @since 2024-11-21
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private OrderGoodMapper orderGoodMapper;
    @Resource
    private AppUserClient appUserClient;
    @Resource
    private TokenService tokenService;
    @Resource
    private ShopClient shopClient;
    @Resource
    private BaseSettingClient baseSettingClient;
 
    @Resource
    private SysUserClient sysUserClient;
 
    @Resource
    private GoodsClient goodsClient;
    @Resource
    private SeckillActivityInfoClient seckillActivityInfoClient;
    @Resource
    private SysConfigClient sysConfigClient;
    @Resource
    private GoodsShopClient goodsShopClient;
    @Resource
    private OrderGoodService orderGoodService;
 
    @Resource
    private RedisTemplate redisTemplate;
 
    @Resource
    private SystemConfigClient systemConfigClient;
 
    @Resource
    private RegionClient regionClient;
    @Resource
    private ApplicationEventPublisher applicationEventPublisher;
 
 
    @Override
    public List<OrderVO> selectOrderListByUserId(Integer status, Long userId) {
        return orderMapper.selectOrderListByUserId(status, userId);
    }
 
 
    @Override
    public OrderDetailVO getOrderDetail(Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        R<Shop> shopR = shopClient.getShopById(order.getShopId());
        if (!R.isSuccess(shopR)) {
            throw new ServiceException("获取门店信息失败");
        }
 
        // 商品
        List<OrderGood> orderGoods = orderGoodMapper.selectList(new LambdaQueryWrapper<OrderGood>()
                .eq(OrderGood::getOrderId, orderId));
 
        List<OrderGoodsVO> goodsList = new ArrayList<>();
        for (OrderGood orderGood : orderGoods) {
            String goodJson = orderGood.getGoodJson();
            Goods goods = JSONObject.parseObject(goodJson, Goods.class);
            OrderGoodsVO orderGoodsVO = new OrderGoodsVO();
            orderGoodsVO.setGoodsId(orderGood.getGoodsId());
            orderGoodsVO.setNum(orderGood.getNum());
            orderGoodsVO.setGoodsName(goods.getName());
            orderGoodsVO.setType(goods.getType());
            orderGoodsVO.setGoodsPic(goods.getHomePagePicture());
            orderGoodsVO.setSellingPrice(orderGood.getSellingPrice());
            orderGoodsVO.setIntegral(orderGood.getIntegral());
            orderGoodsVO.setOriginalPrice(goods.getOriginalPrice());
            goodsList.add(orderGoodsVO);
        }
        // 优惠券
        String couponJson = order.getCouponJson();
        JSONObject jsonObject = new JSONObject();
        if (StringUtils.isNotEmpty(couponJson)) {
            jsonObject = JSONObject.parseObject(couponJson);
        }
 
        OrderDetailVO orderDetailVO = new OrderDetailVO();
        orderDetailVO.setDistributionMode(order.getDistributionMode());
        Shop shop = shopR.getData();
        orderDetailVO.setId(order.getId());
        orderDetailVO.setOrderStatus(order.getOrderStatus());
        orderDetailVO.setPoint(order.getPoint());
        orderDetailVO.setOrderNumber(order.getOrderNumber());
        orderDetailVO.setCreateTime(order.getCreateTime());
        orderDetailVO.setTotalAmount(order.getTotalAmount());
        orderDetailVO.setCouponName(jsonObject.getString("couponName"));
        orderDetailVO.setCouponAmount(order.getDiscountTotalAmount());
        orderDetailVO.setExpressAmount(order.getExpressAmount());
        orderDetailVO.setPointAmount(order.getGetPoint());
        orderDetailVO.setPaymentAmount(order.getPaymentAmount());
        orderDetailVO.setGoodsList(goodsList);
        orderDetailVO.setShopName(shop.getName());
        orderDetailVO.setShopAddress(shop.getAddress());
        orderDetailVO.setLongitude(shop.getLongitude());
        orderDetailVO.setLatitude(shop.getLatitude());
        orderDetailVO.setShopId(shop.getId());
        if (StringUtils.isNotEmpty(order.getExpressResult())) {
            MapTrackKD100Vo mapTrackKD100Vo = JSON.parseObject(order.getExpressResult(), MapTrackKD100Vo.class);
            List<QueryKD100ListVo> data = mapTrackKD100Vo.getData();
            orderDetailVO.setExpress(null != data && data.size() > 0 ? data.get(0).getContext() : "");
        }
 
        // 生成核销码BASE64
        try {
            String base64 = QRCodeGenerator.generateQRCodeBase64(String.valueOf(order.getId()), 124, 124);
            orderDetailVO.setWriteOffCode(base64);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("生成核销码失败");
        }
        return orderDetailVO;
    }
 
 
    @Override
    public boolean check(Order order, Integer shopId, Long userId) {
        // 判断订单是否属于该门店
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        return order.getShopId().equals(shopId);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void writeOff(String id, Integer shopId, String technicianId) {
        LoginUser loginUserApplet = tokenService.getLoginUserApplet();
        Order order = orderMapper.selectById(id);
        boolean check = check(order, shopId, loginUserApplet.getUserid());
        if (!check) {
            throw new ServiceException("该订单与当前扫码门店不一致");
        }
 
        // 售后设置
        R<BaseSetting> baseSettingR = baseSettingClient.getBaseSetting(5);
        if (R.isError(baseSettingR)) {
            throw new ServiceException("售后设置获取失败");
        }
        BaseSetting baseSetting = baseSettingR.getData();
        if (baseSetting == null) {
            throw new ServiceException("售后设置获取失败");
        }
        String content = baseSetting.getContent();
        JSONObject jsonObject = JSONObject.parseObject(content);
        Long days = jsonObject.getLong("days");
        order.setOrderStatus(OrderStatus.COMPLETED.getCode());
        order.setAfterSaleTime(LocalDateTime.now().plusDays(days));
        order.setEndTime(LocalDateTime.now());
        order.setCancellerAppUserId(loginUserApplet.getUserid());
        if (StringUtils.isNotEmpty(technicianId) && !"null".equals(technicianId)) {
            order.setTechnicianId(Integer.valueOf(technicianId));
        }
        orderMapper.updateById(order);
    }
 
 
    /**
     * 管理后台获取订单列表数据
     *
     * @param orderPageList
     * @return
     */
    @Override
    public PageInfo<OrderPageListVo> getOrderPageList(OrderPageList orderPageList) {
        Long userid = tokenService.getLoginUser().getUserid();
        SysUser sysUser = sysUserClient.getSysUser(userid).getData();
        if (2 == sysUser.getRoleType()) {
            orderPageList.setShopId(sysUser.getObjectId());
        }
        //搜索条件,用户姓名
        if (StringUtils.isNotEmpty(orderPageList.getUserName())) {
            List<AppUser> data = appUserClient.getAppUserByNameNoFilter(orderPageList.getUserName()).getData();
            List<Long> collect = data.stream().map(AppUser::getId).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(collect)) {
                return new PageInfo<>();
            }
            if (null != orderPageList.getAppUserIds()) {
                List<Long> appUserIds = orderPageList.getAppUserIds();
                appUserIds.addAll(collect);
                orderPageList.setAppUserIds(appUserIds);
            } else {
                orderPageList.setAppUserIds(collect);
            }
        }
        //搜索条件,用户电话
        if (StringUtils.isNotEmpty(orderPageList.getPhone())) {
            List<AppUser> data = appUserClient.getAppUserByPhoneNoFilter(orderPageList.getPhone()).getData();
            List<Long> collect = data.stream().map(AppUser::getId).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(collect)) {
                return new PageInfo<>();
            }
 
            if (null != orderPageList.getAppUserIds()) {
                List<Long> appUserIds = orderPageList.getAppUserIds();
                if (!containsAny(appUserIds, collect)) {
                    return new PageInfo<>();
                }
                appUserIds.addAll(collect);
                orderPageList.setAppUserIds(appUserIds);
            } else {
                orderPageList.setAppUserIds(collect);
            }
        }
        if (null != orderPageList.getAppUserIds()) {
            orderPageList.setAppUserIds(orderPageList.getAppUserIds().stream().distinct().collect(Collectors.toList()));
        }
 
 
        PageInfo<OrderPageListVo> pageInfo = new PageInfo<>(orderPageList.getPageCurr(), orderPageList.getPageSize());
 
        List<OrderPageListVo> list = this.baseMapper.getOrderPageList(pageInfo, orderPageList);
        for (OrderPageListVo orderPageListVo : list) {
            Long appUserId = orderPageListVo.getAppUserId();
            AppUser appUser = appUserClient.getAppUserById(appUserId);
            if (null != appUser) {
                orderPageListVo.setUserName(appUser.getName());
                orderPageListVo.setPhone(appUser.getPhone());
            }
            String expressJson = orderPageListVo.getExpressJson();
            if (StringUtils.isNotEmpty(expressJson) && !expressJson.equals("NULL")) {
                JSONObject jsonObject = null;
                try {
                    jsonObject = JSONObject.parseObject(expressJson);
                    String companyName = ExpressCompanyMap.getCompanyNameByCode(jsonObject.getString("com"));
                    orderPageListVo.setExpressCompany(companyName);
                    orderPageListVo.setExpressNum(jsonObject.getString("num"));
                } catch (Exception e) {
                }
 
            }
 
        }
        return pageInfo.setRecords(list);
    }
 
    /**
     * 判断 list1 是否包含 list2 中的至少一个元素
     *
     * @param list1 第一个列表
     * @param list2 第二个列表
     * @return 如果 list1 包含 list2 中的至少一个元素,返回 true;否则返回 false
     */
    private boolean containsAny(List<Long> list1, List<Long> list2) {
        // 将 list1 转换为 HashSet 以提高查询效率
        Set<Long> set1 = new HashSet<>(list1);
 
        // 遍历 list2,检查是否有元素存在于 set1 中
        for (Long element : list2) {
            if (set1.contains(element)) {
                return true;
            }
        }
 
        // 如果没有找到共同元素,返回 false
        return false;
    }
 
 
    /**
     * 小程序取消订单
     *
     * @param orderId
     * @return
     */
    @Override
    public R cancel(Long orderId) {
        Order order = this.getById(orderId);
        if (null == order) {
            return R.fail("取消失败");
        }
        Long userid = tokenService.getLoginUserApplet().getUserid();
        if (!order.getAppUserId().equals(userid)) {
            return R.fail("取消失败");
        }
        if (!Arrays.asList(1, 2, 3).contains(order.getOrderStatus())) {
            return R.fail("订单取消失败");
        }
        if (null != order.getAfterSaleTime() && LocalDateTime.now().isAfter(order.getAfterSaleTime())) {
            return R.fail("订单取消失败");
        }
        order.setOrderStatus(5);
        R r = refundPayMoney(order);
        if (200 == r.getCode()) {
            this.updateById(order);
        }
        return r;
    }
 
 
 
 
    /**
     * 取消订单操作
     *
     * @param orderId
     * @return
     */
    @Override
    public R cancelOrder(Long orderId) {
        Order order = this.getById(orderId);
        if (Arrays.asList(5, 6, 7).contains(order.getOrderStatus())) {
            return R.fail("无效的操作");
        }
        if (null != order.getAfterSaleTime() && LocalDateTime.now().isAfter(order.getAfterSaleTime())) {
            return R.fail("订单取消失败");
        }
        order.setOrderStatus(5);
        R r = refundPayMoney(order);
        if (200 == r.getCode()) {
            this.updateById(order);
        }
        return r;
    }
 
 
    /**
     * 返回订单支付金额和回退积分和会员等级
     *
     * @param order
     */
    public R refundPayMoney(Order order) {
        //开始退款
        Integer payMethod = order.getPayMethod();
        BigDecimal expressAmount = order.getExpressAmount() == null ? BigDecimal.ZERO : order.getExpressAmount();
        BigDecimal paymentAmount = order.getPaymentAmount().add(expressAmount);
        AppUser appUser = appUserClient.getAppUserById(order.getAppUserId());
        if (1 == payMethod) {
            //微信退款
            RefundResult refund = PaymentUtil.refund(order.getOrderNumber(), "R" + order.getOrderNumber(), paymentAmount.doubleValue(), "/order/order/refundPayMoneyCallback");
            if ("100".equals(refund.getRa_Status())) {
                order.setRefundStatus(1);
                return R.ok();
            } else {
                return R.fail(refund.getRc_CodeMsg());
            }
        }
        if (2 == payMethod) {
            BigDecimal balance = appUser.getBalance();
            appUser.setBalance(balance.add(paymentAmount).setScale(2, RoundingMode.HALF_EVEN));
            appUser.setShopAmount(appUser.getShopAmount().subtract(paymentAmount).setScale(2, RoundingMode.HALF_EVEN));
            //查询最后一次的消费订单
            Order order1 = this.getOne(new LambdaQueryWrapper<Order>().eq(Order::getAppUserId, order.getAppUserId()).eq(Order::getPayStatus, 2)
                    .eq(Order::getDelFlag, 0).in(Order::getOrderStatus, Arrays.asList(1, 2, 3, 4, 8)).ne(Order::getId, order.getId()).last(" order by create_time desc limit 0, 1"));
            if (null != order1) {
                appUser.setLastShopTime(order1.getCreateTime());
            } else {
                appUser.setLastShopTime(null);
            }
        }
        if (3 == payMethod) {
            //开始运费退款,积分支付,运费是单独进行支付的,所以需要单独退款
            if (null != order.getExpressAmount() && BigDecimal.ZERO.compareTo(order.getExpressAmount()) < 0) {
                if (1 == order.getExpressPayMethod()) {
                    //微信退款
                    RefundResult refund = PaymentUtil.refund(order.getOrderNumber(), "R" + order.getOrderNumber(), expressAmount.doubleValue(), "/order/order/refundExpressPayMoneyCallback");
                    if ("100".equals(refund.getRa_Status())) {
                        order.setRefundStatus(1);
                        return R.ok();
                    } else {
                        return R.fail(refund.getRc_CodeMsg());
                    }
                }
                if (2 == order.getExpressPayMethod()) {
                    BigDecimal balance = appUser.getBalance();
                    appUser.setBalance(balance.add(expressAmount).setScale(2, RoundingMode.HALF_EVEN));
                }
            }
 
            Integer lavePoint = appUser.getLavePoint();
            //积分退款
            appUser.setLavePoint(appUser.getLavePoint() + order.getPoint());
            appUser.setAvailablePoint(appUser.getAvailablePoint() + order.getPoint());
            UserPoint userPoint1 = new UserPoint();
            userPoint1.setType(11);
            userPoint1.setObjectId(order.getId());
            Integer transferablePoint = order.getPoint();
            appUser.setTransferablePoint(appUser.getTransferablePoint() + transferablePoint);
            appUserClient.editAppUserById(appUser);
        }
 
        order.setRefundStatus(2);
        order.setRefundTime(LocalDateTime.now());
        return R.ok();
    }
 
 
    /**
     * 取消订单后回调处理
     *
     * @return
     */
    @Override
    public R refundPayMoneyCallback(RefundCallbackResult refundCallbackResult) {
        String code = refundCallbackResult.getR3_RefundOrderNo().substring(1);
        Order order = this.getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNumber, code));
        if (null == order || order.getPayStatus() == 1 || order.getOrderStatus() == 6) {
            return R.ok();
        }
        order.setRefundCode(refundCallbackResult.getR5_RefundTrxNo());
        order.setRefundStatus(2);
        order.setRefundTime(LocalDateTime.now());
        this.updateById(order);
        return R.ok();
    }
 
    
 
 
    /**
     * 收货操作
     *
     * @param orderId
     * @return
     */
    @Override
    public R receivingOperation(Long orderId) {
        Order order = this.getById(orderId);
        if (order.getOrderStatus() != 2) {
            return R.fail("无效的操作");
        }
        order.setOrderStatus(4);
        R<BaseSetting> baseSettingR = baseSettingClient.getBaseSetting(5);
        if (R.isError(baseSettingR)) {
            return R.fail("售后设置获取失败");
        }
        BaseSetting baseSetting = baseSettingR.getData();
        if (baseSetting == null) {
            return R.fail("售后设置获取失败");
        }
        String content = baseSetting.getContent();
        JSONObject jsonObject = JSONObject.parseObject(content);
        Long days = jsonObject.getLong("days");
        order.setAfterSaleTime(LocalDateTime.now().plusDays(days));
        this.updateById(order);
        return R.ok();
    }
 
 
    /**
     * 获取订单详情
     *
     * @param orderId
     * @return
     */
    @Override
    public OrderInfoVo getOrderInfo(Long orderId) {
        Order order = this.getById(orderId);
        OrderInfoVo orderInfo = new OrderInfoVo();
        orderInfo.setId(orderId.toString());
        orderInfo.setOrderNumber(order.getOrderNumber());
        orderInfo.setOrderStatus(order.getOrderStatus());
        orderInfo.setCreateTime(order.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        AppUser appUser = appUserClient.getAppUserById(order.getAppUserId());
        if (null != appUser) {
            orderInfo.setUserName(appUser.getName());
            orderInfo.setPhone(appUser.getPhone());
        }
        orderInfo.setOrderType(order.getOrderType() == 1 ? "服务" : (StringUtils.isNotEmpty(order.getAddressJson()) ? "单品-快递配送" : "单品-上门自提"));
        Shop shop = shopClient.getShopById(order.getShopId()).getData();
        if (null != shop) {
            orderInfo.setShopName(shop.getName());
        }
        orderInfo.setPaymentMethod(order.getPayMethod());
        orderInfo.setTotalAmount(order.getTotalAmount());
        orderInfo.setDiscountAmount(order.getDiscountTotalAmount());
        orderInfo.setExpressAmount(order.getExpressAmount());
        orderInfo.setPaymentAmount(order.getPaymentAmount());
        orderInfo.setGetPoint(order.getGetPoint());
        if (StringUtils.isNotEmpty(order.getExpressJson()) && !order.getExpressJson().equals("NULL")){
            JSONObject jsonObject = JSON.parseObject(order.getExpressJson());
            orderInfo.setExpressCompany(jsonObject.getString("com"));
            orderInfo.setExpressNumber(jsonObject.getString("num"));
        }
 
        List<OrderGood> orderGoods = orderGoodMapper.selectList(new LambdaQueryWrapper<OrderGood>().eq(OrderGood::getOrderId, orderId).eq(OrderGood::getDelFlag, 0));
        int sum = orderGoods.stream().mapToInt(OrderGood::getNum).sum();
        orderInfo.setGoodsNum(sum);
        List<Object> goodsJson = new ArrayList<>();
        for (OrderGood orderGood : orderGoods) {
            Goods goods = JSON.parseObject(orderGood.getGoodJson(), Goods.class);
            Map<String, Object> map = new HashMap<>();
            map.put("name", goods.getName());
            map.put("imgUrl", goods.getHomePagePicture());
            map.put("number", orderGood.getNum());
            goodsJson.add(map);
        }
        orderInfo.setGoodsJson(JSON.toJSONString(goodsJson));
        orderInfo.setPoint(order.getPoint());
        if (null != order.getAfterSaleTime()) {
            orderInfo.setAfterSaleTime(order.getAfterSaleTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
        if (null != order.getEndTime()) {
            AppUser user = appUserClient.getAppUserById(order.getCancellerAppUserId());
            orderInfo.setCanceller(user.getName());
            orderInfo.setWriteOffTime(order.getEndTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
        return orderInfo;
    }
 
 
    /**
     * 获取商品销售数量
     *
     * @param goodsId
     * @return
     */
    @Override
    public Integer getGoodsSaleNum(Integer goodsId, Integer type, Long userId) {
        return this.baseMapper.getGoodsSaleNum(goodsId, type, userId);
    }
 
 
    /**
     * 获取店铺订单数量
     *
     * @param shopId
     * @param type
     * @return
     */
    @Override
    public Integer getShopSaleNum(Integer shopId, Integer type) {
        return this.baseMapper.getShopSaleNum(shopId, type);
    }
    
 
    @Override
    public Integer getShopSaleNumByShopIds(List<Integer> shopIds, Integer type) {
        return this.baseMapper.getShopSaleNumByShopIds(shopIds, type);
    }
 
    @Override
    public List<OrderExport> getOrderExportList(OrderPageList orderPageList) {
        return Collections.emptyList();
    }
 
    /**
     * 确认订单
     */
    @Override
    public ConfirmOrderVo confirmOrder(Integer goodId,Integer type) {
        ConfirmOrderVo confirmOrderVo=new ConfirmOrderVo();
        //用户信息
        Long userid = tokenService.getLoginUserApplet().getUserid();
        AppUser appUser = appUserClient.getAppUserById(userid);
        //获取商品信息
        Goods good = goodsClient.getGoodsById(goodId).getData();
        if (null == good||good.getDelFlag()==1||good.getStatus()==0) {
            //商品不存在
            throw new ServiceException("商品不存在");
        }
        //查询店铺信息
 
        GoodsShop shop = goodsShopClient.getGoodsShop(goodId).getData();
        System.out.println(shop);
        if (null == shop){
            //门店不存在
            throw new ServiceException("该商品门店不存在");
        }
        //插入基础信息
        confirmOrderVo.setGoodId(goodId);
        confirmOrderVo.setGoodName(good.getName());
        confirmOrderVo.setHomePicture(good.getHomePagePicture());
        confirmOrderVo.setNumber(1);
        confirmOrderVo.setShopId(shop.getShopId());
        confirmOrderVo.setShopName(shop.getShopName());
        confirmOrderVo.setPurchaseLimitNum(good.getPurchaseLimit());
        confirmOrderVo.setOriginalPrice(good.getOriginalPrice());
        //todo 实时计算用户可用积分
 
 
        confirmOrderVo.setResidualPoint(appUser.getAvailablePoint());
        //插入价格
        confirmOrderVo.setCash(good.getSellingPrice());
        confirmOrderVo.setPoint(good.getIntegral());
 
        //计算活动价格信息
        Price price = getPrice(goodId, 1);
        if (null != price) {
            confirmOrderVo.setCash(price.getCash());
            confirmOrderVo.setOrderPoint(price.getPoint());
            confirmOrderVo.setEndTimeStamp(price.getEndTimeStamp());
        }
        //判断是否是积分支付
        if (type == 1) {//现金
            confirmOrderVo.setOrderMoney(confirmOrderVo.getCash());
            //计算积分抵扣的金额  将积分转为金额,去掉小数
            BigDecimal deduction=getCashByPoint(confirmOrderVo.getResidualPoint());
            confirmOrderVo.setDeduction(deduction);
        }else {//积分
            confirmOrderVo.setOrderPoint(good.getIntegral());
        }
        //限购检查
        //判断当前数量是否已经超出限购数量(需要计算已经购买的数量)
        if(null == good.getPurchaseLimit() || -1 == good.getPurchaseLimit()){
            confirmOrderVo.setIsPurchaseLimit(false);
            confirmOrderVo.setPurchaseLimitNum(-1);
        }else{
            //todo 查当前用户的订单
            List<Order> orders = this.list(new LambdaQueryWrapper<Order>().eq(Order::getAppUserId, appUser.getId()).eq(Order::getDelFlag, 0).in(Order::getOrderStatus, Arrays.asList(4, 8)));
            List<Long> orderIds = orders.stream().map(Order::getId).collect(Collectors.toList());
            int sum = 0;
            if(!orderIds.isEmpty()){
                //关于该商品的订单
                List<OrderGood> orderGoodList = orderGoodService.list(new LambdaQueryWrapper<OrderGood>().in(OrderGood::getOrderId, orderIds)
                        .eq(OrderGood::getGoodsId, good.getId()).eq(OrderGood::getDelFlag, 0));
                sum = orderGoodList.stream().mapToInt(OrderGood::getNum).sum();
            }
            confirmOrderVo.setIsPurchaseLimit((1 + sum) > good.getPurchaseLimit());
            confirmOrderVo.setPurchaseLimitNum(good.getPurchaseLimit() - sum);
        }
 
        return confirmOrderVo;
    }
    /**
     * 根据商品的价格配置体系获取商品当前的价格
     * @param goodsId
     * @param type          1普通商品,2秒杀商品
     * @return
     */
    public Price getPrice( Integer goodsId, Integer type){
        //判断是否有在秒杀活动时间中
        Price price = new Price();
        GetSeckillActivityInfo getSeckillActivityInfo = new GetSeckillActivityInfo();
        getSeckillActivityInfo.setGoodsId(goodsId);
        GoodsSeckill goodsSeckill = seckillActivityInfoClient.getSeckillActivityInfo(getSeckillActivityInfo).getData();
        //没有秒杀活动或者添加的普通商品则使用秒杀活动价格
        if(null == goodsSeckill || type == 1){
            return null;
        }
        //秒杀活动价格
        price.setCash(goodsSeckill.getSellingPrice());
        //计算对应积分
        price.setPoint(getPoint(price.getCash()));
        price.setEndTimeStamp(goodsSeckill.getEndTime());
        return price;
    }
    /**
     * 获取现金对应积分
     */
    public Integer getPoint(BigDecimal cash){
        if (cash == null || cash.compareTo(BigDecimal.ZERO) < 0) {
            throw new IllegalArgumentException("金额不能为null或负数");
        }
        // 获取积分兑换比例配置
        R<SysConfig> info = sysConfigClient.getInfo(6L);
        if (info == null || info.getData() == null) {
            throw new RuntimeException("获取积分兑换比例配置失败");
        }
        String configValue = info.getData().getConfigValue();
        if (StringUtils.isBlank(configValue)) {
            throw new RuntimeException("积分兑换比例配置值为空");
        }
        try {
            // 使用BigDecimal处理比例,避免精度问题
            BigDecimal ratio = new BigDecimal(configValue.trim());
            if (ratio.compareTo(BigDecimal.ZERO) <= 0) {
                throw new RuntimeException("积分兑换比例必须大于0");
            }
 
            // 计算积分并四舍五入取整
            return cash.multiply(ratio).intValue();
 
        } catch (NumberFormatException e) {
            throw new RuntimeException("积分兑换比例配置值格式错误", e);
        } catch (ArithmeticException e) {
            throw new RuntimeException("积分计算结果溢出", e);
        }
 
    }
 
    /**
     * 获取积分对应金额
     */
    public BigDecimal getCashByPoint(Integer point){
        // 参数校验
        if (point == null || point < 0) {
            throw new IllegalArgumentException("积分值不能为null或负数");
        }
 
        // 特殊情况:0积分直接返回0金额
        if (point == 0) {
            return BigDecimal.ZERO.setScale(2);
        }
 
        // 获取积分兑换比例配置
        R<SysConfig> info = sysConfigClient.getInfo(6L);
        if (info == null || info.getData() == null) {
            throw new RuntimeException("获取积分兑换比例配置失败");
        }
 
        String configValue = info.getData().getConfigValue(); // 示例:"100" 表示 100积分=1元
        if (StringUtils.isBlank(configValue)) {
            throw new RuntimeException("积分兑换比例配置值为空");
        }
 
        try {
            // 解析兑换比例(转换为BigDecimal保证精度)
            BigDecimal exchangeRate = new BigDecimal(configValue.trim());
            if (exchangeRate.compareTo(BigDecimal.ZERO) <= 0) {
                throw new RuntimeException("积分兑换比例必须为正数");
            }
 
            // 高精度计算(积分/比例)
            return new BigDecimal(point)
                    .divide(exchangeRate, 2, RoundingMode.HALF_UP);
 
        } catch (NumberFormatException e) {
            throw new RuntimeException("积分兑换比例配置值格式错误,应为数字", e);
        } catch (ArithmeticException e) {
            throw new RuntimeException("积分计算错误", e);
        }
    }
}